Json Profiles

This commit is contained in:
John Lewin 2016-04-18 11:31:31 -07:00
parent bfa2ddafd8
commit 4496720772
93 changed files with 3069 additions and 4120 deletions

View file

@ -0,0 +1,281 @@
/*
Copyright (c) 2016, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using MatterHackers.MatterControl.PrinterCommunication;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.Agg;
using System.Linq;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public enum NamedSettingsLayers { MHBaseSettings, OEMSettings, Quality, Material, User, All }
public class ActiveSliceSettings
{
private static readonly string userDataPath = DataStorage.ApplicationDataStorage.ApplicationUserDataPath;
private static readonly string profilesPath = Path.Combine(userDataPath, "Profiles");
private static readonly string profilesDBPath = Path.Combine(profilesPath, "profiles.json");
public static RootedObjectEventHandler ActivePrinterChanged = new RootedObjectEventHandler();
private static SettingsProfile activeInstance = null;
public static SettingsProfile Instance
{
get
{
return activeInstance;
}
set
{
if (activeInstance != value)
{
// If we have an active printer, run Disable otherwise skip to prevent empty ActiveSliceSettings due to null ActivePrinter
if (activeInstance != null)
{
PrinterConnectionAndCommunication.Instance.Disable();
}
activeInstance = value;
if (activeInstance != null)
{
BedSettings.SetMakeAndModel(activeInstance.Make, activeInstance.Model);
}
OnActivePrinterChanged(null);
}
}
}
static ActiveSliceSettings()
{
// Ensure the profiles directory exists
Directory.CreateDirectory(profilesPath);
// Load or import the profiles.json document
if (File.Exists(profilesDBPath))
{
ProfileData = JsonConvert.DeserializeObject<ProfileData>(File.ReadAllText(profilesDBPath));
}
else
{
ProfileData = new ProfileData();
// Import class profiles from the db into local json files
DataStorage.ClassicDB.ClassicSqlitePrinterProfiles.ImportPrinters(ProfileData, profilesPath);
File.WriteAllText(profilesDBPath, JsonConvert.SerializeObject(ProfileData, Formatting.Indented));
// TODO: Upload new profiles to webservice
}
if (!string.IsNullOrEmpty(ProfileData.ActiveProfileID))
{
Instance = LoadProfile(ProfileData.ActiveProfileID);
}
else
{
// Load an empty profile with just the MatterHackers base settings from config.json
Instance = new SettingsProfile(LoadEmptyProfile());
}
}
public static void SetActiveProfileID(int id)
{
ProfileData.ActiveProfileID = id.ToString();
File.WriteAllText(profilesDBPath, JsonConvert.SerializeObject(ProfileData, Formatting.Indented));
}
public static LayeredProfile LoadEmptyProfile()
{
return new LayeredProfile(new OemProfile(), LoadMatterHackersBaseLayer());
}
public static ProfileData ProfileData { get; private set; }
public static void CheckForAndDoAutoConnect()
{
bool connectionAvailable;
var autoConnectProfile = GetAutoConnectProfile(out connectionAvailable);
if (autoConnectProfile != null)
{
//ActiveSliceSettings.Instance = autoConnectProfile;
if (connectionAvailable)
{
PrinterConnectionAndCommunication.Instance.HaltConnectionThread();
PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter();
}
}
}
internal static void SwitchToProfile(int id)
{
var profile = LoadProfile(id);
SetActiveProfileID(id);
if (profile != null)
{
Instance = profile;
}
}
internal static SettingsProfile LoadProfile(int id)
{
string profileID = ProfileData.Profiles.Where(p => p.Id == id.ToString()).FirstOrDefault()?.Id.ToString();
if (!string.IsNullOrEmpty(profileID))
{
return LoadProfile(profileID);
}
return null;
}
internal static SettingsProfile LoadProfile(string profileID)
{
string profilePath = Path.Combine(profilesPath, profileID + ".json");
return File.Exists(profilePath) ? LoadProfileFromDisk(profilePath) : null;
}
internal static void AcquireNewProfile(string make, string model, string printerName)
{
string guid = Guid.NewGuid().ToString();
OemProfile printerProfile = LoadHttpOemProfile(make, model);
SettingsLayer baseConfig = LoadMatterHackersBaseLayer();
var layeredProfile = new LayeredProfile(
printerProfile,
baseConfig);
layeredProfile.DocumentPath = Path.Combine(profilesPath, guid + ".json");
layeredProfile.Save();
ProfileData.Profiles.Add(new PrinterInfo
{
Name = printerName,
Id = guid
});
Instance = new SettingsProfile(layeredProfile);
}
private static SettingsProfile LoadProfileFromDisk(string profilePath)
{
return new SettingsProfile(LayeredProfile.LoadFile(profilePath));
}
private static SettingsLayer LoadMatterHackersBaseLayer()
{
// TODO: Build if missing?
string baseConfigPath = Path.Combine(profilesPath, "config.json");
return JsonConvert.DeserializeObject<SettingsLayer>(File.ReadAllText(baseConfigPath));
}
private static OemProfile LoadHttpOemProfile(string make, string model)
{
var client = new WebClient();
string profileText = client.DownloadString(string.Format("http://matterdata.azurewebsites.net/api/oemprofiles/{0}/{1}/", make, model));
var printerProfile = JsonConvert.DeserializeObject<OemProfile>(profileText);
return printerProfile;
}
private static void OnActivePrinterChanged(EventArgs e)
{
ActivePrinterChanged.CallEvents(null, e);
}
private static SettingsProfile GetAutoConnectProfile(out bool connectionAvailable)
{
// Load the last selected profile, see if the port is active
// Return the profile if valid
// otherwise (not the best idea IMO), iterate all profiles, trying to find relevant matches and change the selection dynamically rather than as last selected by the user
/*
string[] comportNames = FrostedSerialPort.GetPortNames();
Printer printerToSelect = null;
connectionAvailable = false;
foreach (Printer printer in Datastore.Instance.dbSQLite.Query<Printer>("SELECT * FROM Printer;"))
{
if (printer.AutoConnectFlag)
{
printerToSelect = printer;
bool portIsAvailable = comportNames.Contains(printer.ComPort);
if (portIsAvailable)
{
// We found a printer that we can select and connect to.
connectionAvailable = true;
return printer;
}
}
}
// return a printer we can connect to even though we can't connect
return printerToSelect;
*/
connectionAvailable = false;
return null;
}
/*
private static SettingsProfile LoadBestProfile()
{
// Conceptually, load settings means
// Read from state the currently selected profile/printer token
// - Check for/update/load the base MatterHackers layer
// - Check for/update/load the OEM layer
// - Set the quality layer to the currently selected quality profile
// - Set the material layer to the currently selected material profile
// - Check for/update/load the customer layer
// Load profiles document
var activeProfile = ProfileData.Profiles.Where(p => p.ProfileToken == ProfileData.ActiveProfileID).FirstOrDefault();
if (activeProfile != null)
{
printerProfilePath = Path.Combine(profilesPath, activeProfile.ProfileToken + ".json");
}
// or this
return LoadProfileFromDisk(printerProfilePath);
} */
}
public enum SlicingEngineTypes { Slic3r, CuraEngine, MatterSlice };
}

View file

@ -0,0 +1,306 @@
/*
Copyright (c) 2016, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System;
using System.IO;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public class LayeredProfile
{
[JsonIgnore]
internal SettingsLayer QualityLayer { get; private set; }
[JsonIgnore]
internal SettingsLayer MaterialLayer { get; private set; }
public LayeredProfile(OemProfile printerProfile, SettingsLayer baseConfig)
{
this.OemProfile = printerProfile;
this.BaseLayer = baseConfig;
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
QualityLayer = GetQualityLayer(ActiveQualityKey);
MaterialLayer = GetMaterialLayer(ActiveMaterialKey); ;
}
public OemProfile OemProfile { get; set; }
internal SettingsLayer GetMaterialLayer(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
// Find the first matching layer in either the user or the OEM layers
SettingsLayer layer = null;
if (!MaterialLayers.TryGetValue(key, out layer))
{
OemProfile.MaterialLayers.TryGetValue(key, out layer);
}
return layer;
}
internal SettingsLayer GetQualityLayer(string key)
{
// Find the first matching layer in either the user or the OEM layers
SettingsLayer layer = null;
if (key != null && !QualityLayers.TryGetValue(key, out layer))
{
OemProfile.QualityLayers.TryGetValue(key, out layer);
}
return layer;
}
public string ActiveMaterialKey
{
get
{
return GetValue("MatterControl.ActiveMaterialKey");
}
internal set
{
SetActiveValue("MatterControl.ActiveMaterialKey", value);
MaterialLayer = GetMaterialLayer(value);
Save();
}
}
public string ActiveQualityKey
{
get
{
return GetValue("MatterControl.ActiveQualityKey");
}
internal set
{
SetActiveValue("MatterControl.ActiveQualityKey", value);
QualityLayer = GetQualityLayer(value);
Save();
}
}
public string GetMaterialPresetKey(int extruderIndex)
{
if (extruderIndex >= MaterialSettingsKeys.Count)
{
return null;
}
return MaterialSettingsKeys[extruderIndex];
}
public void SetMaterialPreset(int extruderIndex, string materialKey)
{
if (extruderIndex >= PrinterCommunication.PrinterConnectionAndCommunication.MAX_EXTRUDERS)
{
throw new ArgumentOutOfRangeException("Requested extruder index is outside of bounds: " + extruderIndex);
}
// TODO: This should really be in SettingsProfile and should be run when the extruder count changes
if (MaterialSettingsKeys.Count <= extruderIndex)
{
var resizedArray = new string[extruderIndex + 1];
MaterialSettingsKeys.CopyTo(resizedArray);
MaterialSettingsKeys = new List<string>(resizedArray);
}
MaterialSettingsKeys[extruderIndex] = materialKey;
if (extruderIndex == 0)
{
ActiveMaterialKey = materialKey;
ApplicationController.Instance.ReloadAdvancedControlsPanel();
}
Save();
}
public List<string> MaterialSettingsKeys { get; set; } = new List<string>();
public string DocumentPath { get; set; }
internal void Save()
{
File.WriteAllText(DocumentPath, JsonConvert.SerializeObject(this));
}
/// <summary>
/// User settings overrides
/// </summary>
public SettingsLayer UserLayer { get; } = new SettingsLayer();
public IEnumerable<string> AllMaterialKeys()
{
return MaterialLayers.Keys.Union(this.OemProfile.MaterialLayers.Keys);
}
public IEnumerable<string> AllQualityKeys()
{
return QualityLayers.Keys.Union(this.OemProfile.QualityLayers.Keys);
}
internal static LayeredProfile LoadFile(string printerProfilePath)
{
var layeredProfile = JsonConvert.DeserializeObject<LayeredProfile>(File.ReadAllText(printerProfilePath));
layeredProfile.DocumentPath = printerProfilePath;
return layeredProfile;
}
// TODO: Hookup OEM layers
/// <summary>
/// Should contain both user created and oem specified material layers
/// </summary>
public Dictionary<string, SettingsLayer> MaterialLayers { get; } = new Dictionary<string, SettingsLayer>();
// TODO: Hookup OEM layers
/// <summary>
/// Should contain both user created and oem specified quality layers
/// </summary>
public Dictionary<string, SettingsLayer> QualityLayers { get; } = new Dictionary<string, SettingsLayer>();
///<summary>
///Returns the settings value at the 'top' of the stack
///</summary>
public string GetValue(string sliceSetting)
{
return GetValue(sliceSetting, settingsLayers);
}
public string GetValue(string sliceSetting, IEnumerable<SettingsLayer> layers)
{
foreach (SettingsLayer layer in layers)
{
string value;
if (layer.TryGetValue(sliceSetting, out value))
{
return value;
}
}
return "";
}
public SettingsLayer BaseLayer { get; set; }
private IEnumerable<SettingsLayer> settingsLayers
{
get
{
if (this.UserLayer != null)
{
yield return this.UserLayer;
}
if (this.MaterialLayer != null)
{
yield return this.MaterialLayer;
}
if (this.QualityLayer != null)
{
yield return this.QualityLayer;
}
if (this.OemProfile.OemLayer != null)
{
yield return this.OemProfile.OemLayer;
}
yield return this.BaseLayer;
}
}
internal void SetActiveValue(string sliceSetting, string sliceValue)
{
SetActiveValue(sliceSetting, sliceValue, UserLayer);
}
internal void SetActiveValue(string sliceSetting, string sliceValue, SettingsLayer layer)
{
layer[sliceSetting] = sliceValue;
Save();
}
internal void ClearValue(string sliceSetting)
{
ClearValue(sliceSetting, UserLayer);
}
internal void ClearValue(string sliceSetting, SettingsLayer layer)
{
if(layer.ContainsKey(sliceSetting))
{
layer.Remove(sliceSetting);
}
// TODO: Reconsider this frequency
Save();
}
}
public class OemProfile
{
public OemProfile() { }
public OemProfile(Dictionary<string, string> settingsDictionary)
{
OemLayer = new SettingsLayer(settingsDictionary);
}
/// <summary>
/// Printer settings from OEM
/// </summary>
public SettingsLayer OemLayer { get; } = new SettingsLayer();
/// <summary>
/// List of Material presets from OEM
/// </summary>
public Dictionary<string, SettingsLayer> MaterialLayers { get; } = new Dictionary<string, SettingsLayer>();
/// <summary>
/// List of Quality presets from OEM
/// </summary>
public Dictionary<string, SettingsLayer> QualityLayers { get; } = new Dictionary<string, SettingsLayer>();
}
}

View file

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<ClassDiagram MajorVersion="1" MinorVersion="1">
<Class Name="MatterHackers.MatterControl.SlicerConfiguration.ActiveSliceSettings">
<Position X="7.25" Y="0.5" Width="1.75" />
<AssociationLine Name="Instance" Type="MatterHackers.MatterControl.SlicerConfiguration.SettingsProfile">
<MemberNameLabel ManuallyPlaced="true" ManuallySized="true">
<Position X="0.574" Y="-0.225" Height="0.182" Width="1.128" />
</MemberNameLabel>
</AssociationLine>
<TypeIdentifier>
<HashCode>IBAAAAEAAABAAAAAAAAAAAAAAIAAABAAQAgAAEAAAAA=</HashCode>
<FileName>SlicerConfiguration\Settings\ActiveSliceSettings.cs</FileName>
</TypeIdentifier>
<ShowAsAssociation>
<Property Name="Instance" />
</ShowAsAssociation>
</Class>
<Class Name="MatterHackers.MatterControl.SlicerConfiguration.SettingsProfile">
<Position X="3.5" Y="0.5" Width="2" />
<NestedTypes>
<Class Name="MatterHackers.MatterControl.SlicerConfiguration.SettingsProfile.SettingsConverter" Collapsed="true">
<TypeIdentifier>
<NewMemberFileName>SlicerConfiguration\Settings\SettingsProfile.cs</NewMemberFileName>
</TypeIdentifier>
</Class>
</NestedTypes>
<AssociationLine Name="profileLayers" Type="MatterHackers.MatterControl.SlicerConfiguration.LayeredProfile">
<MemberNameLabel ManuallyPlaced="true">
<Position X="0.102" Y="0.256" />
</MemberNameLabel>
</AssociationLine>
<TypeIdentifier>
<HashCode>JCADAcoArLgkCEwJMG9CQD0AAEAjEMYASRgMAA5VAAQ=</HashCode>
<FileName>SlicerConfiguration\Settings\SettingsProfile.cs</FileName>
</TypeIdentifier>
<ShowAsAssociation>
<Field Name="profileLayers" />
</ShowAsAssociation>
</Class>
<Class Name="MatterHackers.MatterControl.SlicerConfiguration.LayeredProfile">
<Position X="7.25" Y="2" Width="1.75" />
<TypeIdentifier>
<HashCode>AAAACMQEKABAAAABEEAGAAQBAgABAAQEAAQIAAAQBAA=</HashCode>
<FileName>SlicerConfiguration\Settings\LayeredProfile.cs</FileName>
<NewMemberFileName>SlicerConfiguration\ActiveSliceSettings.cs</NewMemberFileName>
</TypeIdentifier>
<ShowAsAssociation>
<Property Name="QualityLayer" />
<Property Name="MaterialLayer" />
<Property Name="OemProfile" />
<Property Name="UserLayer" />
</ShowAsAssociation>
</Class>
<Class Name="MatterHackers.MatterControl.SlicerConfiguration.SettingsLayer">
<Position X="10.25" Y="2.25" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAIAAAgAAAAAAEAAAAAQAAAAAAAAAAEAAAAAAAAA=</HashCode>
<FileName>SlicerConfiguration\Settings\SettingsProfile.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="MatterHackers.MatterControl.SlicerConfiguration.OemProfile">
<Position X="7.25" Y="7.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAASAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>SlicerConfiguration\Settings\LayeredProfile.cs</FileName>
<NewMemberFileName>SlicerConfiguration\ActiveSliceSettings.cs</NewMemberFileName>
</TypeIdentifier>
</Class>
<Class Name="MatterHackers.MatterControl.DataStorage.Printer" Collapsed="true">
<Position X="0.75" Y="7.25" Width="1.5" />
<TypeIdentifier>
<HashCode>IAAAgQgCCCAAAAAAIAAAAgQAAAAAEAAAAAwAIBJEAAA=</HashCode>
<FileName>DataStorage\Models.cs</FileName>
</TypeIdentifier>
</Class>
<Font Name="Segoe UI" Size="9" />
</ClassDiagram>

File diff suppressed because it is too large Load diff