public static void ImportPrinter(Printer printer, ProfileData profileData, string profilePath)
		{
			var printerInfo = new PrinterInfo()
			{
				Name = printer.Name,
				Id = printer.Id.ToString()
			};
			profileData.Profiles.Add(printerInfo);

			var layeredProfile = ActiveSliceSettings.LoadEmptyProfile();

			//Load printer settings from database as second layer

			layeredProfile.OemProfile = new OemProfile(LoadOemLayer(printer));

			//Ordering matters - Material presets trump Quality
			LoadQualitySettings(layeredProfile, printer);
			LoadMaterialSettings(layeredProfile, printer);

			string fullProfilePath = Path.Combine(profilePath, printer.Id + ".json");

			File.WriteAllText(fullProfilePath, JsonConvert.SerializeObject(layeredProfile, Formatting.Indented));

			//GET LEVELING DATA from DB

			//PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(printer);

			/*
			PrintLevelingPlane.Instance.SetPrintLevelingEquation(
				levelingData.SampledPosition0,
				levelingData.SampledPosition1,
				levelingData.SampledPosition2,
				ActiveSliceSettings.Instance.PrintCenter); */

		}
 public static void CheckForAndDoAutoConnect()
 {
     DataStorage.Printer autoConnectProfile = ActivePrinterProfile.GetAutoConnectProfile();
     if (autoConnectProfile != null)
     {
         ActivePrinterProfile.Instance.ActivePrinter = autoConnectProfile;
         PrinterCommunication.Instance.HaltConnectionThread();
         PrinterCommunication.Instance.ConnectToActivePrinter();
     }
 }
 void AddPrinters()
 {
     for (int index = 1; index <= 5; index++)
     {
         Printer printer = new Printer();
         printer.ComPort = string.Format("COM{0}", index);
         printer.BaudRate = "250000";
         printer.Name = string.Format("Printer {0}", index);
         Datastore.Instance.dbSQLite.Insert(printer);
     }
 }
 public PrinterSetupStatus(Printer printer = null)
 {
     if (printer == null)
     {
         this.ActivePrinter = new Printer();
         this.ActivePrinter.Make = null;
         this.ActivePrinter.Model = null;
         this.ActivePrinter.Name = "Default Printer";
         this.ActivePrinter.BaudRate = null;
         this.ActivePrinter.ComPort = null;
     }
     else
     {
         this.ActivePrinter = printer;
     }
 }
		public PrinterSetupStatus(Printer printer = null)
		{
			if (printer == null)
			{
				this.ActivePrinter = new Printer();
				this.ActivePrinter.Make = null;
				this.ActivePrinter.Model = null;
				this.ActivePrinter.Name = "Default Printer ({0})".FormatWith(ExistingPrinterCount() + 1);
				this.ActivePrinter.BaudRate = null;
				this.ActivePrinter.ComPort = null;
			}
			else
			{
				this.ActivePrinter = printer;
			}
		}
Esempio n. 6
0
		public PrinterListItemView(Printer printerRecord, ConnectionWindow windowController)
			: base(printerRecord, windowController)
		{
			this.Margin = new BorderDouble(1);
			this.BackgroundColor = this.defaultBackgroundColor;
			this.Padding = new BorderDouble(0);
			this.Name = this.printerRecord.Name + " Profile";

			string[] comportNames = FrostedSerialPort.GetPortNames();
			bool portIsAvailable = comportNames.Contains(printerRecord.ComPort);

			printerName = new TextWidget(this.printerRecord.Name);
			printerName.TextColor = this.defaultTextColor;
			printerName.HAnchor = HAnchor.ParentLeftRight;
			printerName.Margin = new BorderDouble(5, 10, 5, 10);

			string availableText = LocalizedString.Get("Unavailable");
			RGBA_Bytes availableColor = new RGBA_Bytes(158, 18, 0);
			if (portIsAvailable)
			{
				availableText = "";
			}

			if (ActivePrinterProfile.Instance.ActivePrinter != null)
			{
				int connectedPrinterHash = ActivePrinterProfile.Instance.ActivePrinter.GetHashCode();
				int printerOptionHash = printerRecord.GetHashCode();
				if (connectedPrinterHash == printerOptionHash)
				{
					availableText = PrinterConnectionAndCommunication.Instance.PrinterConnectionStatusVerbose;
					availableColor = new RGBA_Bytes(0, 95, 107);
				}
			}

			TextWidget availableIndicator = new TextWidget(availableText, pointSize: 10);
			availableIndicator.TextColor = availableColor;
			availableIndicator.Padding = new BorderDouble(3, 0, 0, 3);
			availableIndicator.Margin = new BorderDouble(right: 5);
			availableIndicator.VAnchor = Agg.UI.VAnchor.ParentCenter;

			this.AddChild(printerName);
			this.AddChild(availableIndicator);
			this.HAnchor = HAnchor.ParentLeftRight;

			BindHandlers();
		}
Esempio n. 7
0
		public PrinterListItemEdit(Printer printerRecord, ConnectionWindow windowController)
			: base(printerRecord, windowController)
		{
			this.printerRecord = printerRecord;
			this.Margin = new BorderDouble(1);
			this.BackgroundColor = this.defaultBackgroundColor;
			this.Padding = new BorderDouble(0);
			this.HAnchor = HAnchor.ParentLeftRight;

			FlowLayoutWidget printerNameContainer = new FlowLayoutWidget();
			printerNameContainer.HAnchor = HAnchor.ParentLeftRight;

			printerName = new TextWidget(this.printerRecord.Name);
			printerName.TextColor = this.defaultTextColor;
			printerName.Margin = new BorderDouble(5, 10, 0, 10);
			printerName.HAnchor = HAnchor.ParentLeftRight;

			printerNameContainer.AddChild(printerName);

			FlowLayoutWidget rightButtonOverlayContainer = new FlowLayoutWidget(FlowDirection.RightToLeft);
			rightButtonOverlayContainer.HAnchor = HAnchor.ParentLeftRight;
			rightButtonOverlayContainer.VAnchor = VAnchor.ParentBottomTop;

			this.rightButtonOverlay = getItemActionButtons();
			this.rightButtonOverlay.Padding = new BorderDouble(0);
			this.rightButtonOverlay.Visible = true;
			rightButtonOverlayContainer.AddChild(rightButtonOverlay);

			this.AddChild(printerNameContainer);
			this.AddChild(rightButtonOverlayContainer);
		}
		public static PrintLevelingData GetForPrinter(Printer printer)
		{
			if (printer != null)
			{
				if (activePrinter != printer)
				{
					CreateFromJsonOrLegacy(printer.PrintLevelingJsonData, printer.PrintLevelingProbePositions);
					activePrinter = printer;
				}
			}
			return instance;
		}
		private static void LoadMaterialSettings(PrinterSettings layeredProfile, Printer printer)
		{
			var materialAssignments = printer.MaterialCollectionIds?.Split(',');
			if(materialAssignments == null)
			{
				return;
			}

			var collections = Datastore.Instance.dbSQLite.Table<SliceSettingsCollection>().Where(v => v.PrinterId == printer.Id && v.Tag == "material");
			foreach (var collection in collections)
			{
				layeredProfile.MaterialLayers.Add(new PrinterSettingsLayer(LoadSettings(collection))
				{
					LayerID = Guid.NewGuid().ToString(),
					Name = collection.Name
				});
			}
		}
		public static void LoadQualitySettings(PrinterSettings layeredProfile, Printer printer)
		{
			var collections = Datastore.Instance.dbSQLite.Table<SliceSettingsCollection>().Where(v => v.PrinterId == printer.Id && v.Tag == "quality");
			foreach (var collection in collections)
			{
				layeredProfile.QualityLayers.Add(new PrinterSettingsLayer(LoadSettings(collection))
				{
					LayerID = Guid.NewGuid().ToString(),
					Name = collection.Name
				});
			}
		}
Esempio n. 11
0
 public PrinterListItem(Printer printerRecord, ConnectionWindow windowController)
 {
     this.printerRecord = printerRecord;
     this.windowController = windowController;
 }
        private void ConnectToPrinter(Printer printerRecord)
        {
            LinesToWriteQueue.Clear();
            //Attempt connecting to a specific printer
            CommunicationState = CommunicationStates.AttemptingToConnect;
            this.stopTryingToConnect = false;
            firmwareType = FirmwareTypes.Unknown;
            firmwareVersion = null;

            if (SerialPortIsAvailable(this.ActivePrinter.ComPort))
            {
                //Create a timed callback to determine whether connection succeeded
                Timer connectionTimer = new Timer(new TimerCallback(ConnectionCallbackTimer));
                connectionTimer.Change(100, 0);

                //Create and start connection thread
                connectThread = new Thread(Connect_Thread);
				connectThread.Name = "Connect To Printer";
                connectThread.IsBackground = true;
                connectThread.Start();
            }
            else
            {
                Debug.WriteLine(string.Format("Connection failed: {0}", this.ActivePrinter.ComPort));
				connectionFailureMessage = "Unavailable";
                OnConnectionFailed(null);
            }
        }
Esempio n. 13
0
		public void ChangedToEditPrinter(Printer activePrinter, object state = null)
		{
			this.activePrinter = activePrinter;
			UiThread.RunOnIdle(DoChangeToEditPrinter, state);
		}
		public static void ImportPrinter(Printer printer, ProfileManager profileData, string profilePath)
		{
			var printerInfo = new PrinterInfo()
			{
				Name = printer.Name,
				ID = printer.Id.ToString(),
				Make = printer.Make ?? "",
				Model = printer.Model ?? "",
			};
			profileData.Profiles.Add(printerInfo);

			var printerSettings = new PrinterSettings()
			{
				OemLayer = LoadOemLayer(printer)
			};

			printerSettings.OemLayer[SettingsKey.make] = printerInfo.Make;
			printerSettings.OemLayer[SettingsKey.model] = printer.Model;

			LoadQualitySettings(printerSettings, printer);
			LoadMaterialSettings(printerSettings, printer);

			printerSettings.ID = printer.Id.ToString();

			printerSettings.UserLayer[SettingsKey.printer_name] = printer.Name ?? "";
			printerSettings.UserLayer[SettingsKey.baud_rate] = printer.BaudRate ?? "";
			printerSettings.UserLayer[SettingsKey.auto_connect] = printer.AutoConnect ? "1" : "0";
			printerSettings.UserLayer[SettingsKey.default_material_presets] = printer.MaterialCollectionIds ?? "";
			printerSettings.UserLayer[SettingsKey.windows_driver] = printer.DriverType ?? "";
			printerSettings.UserLayer[SettingsKey.device_token] = printer.DeviceToken ?? "";
			printerSettings.UserLayer[SettingsKey.device_type] = printer.DeviceType ?? "";

			if (string.IsNullOrEmpty(ProfileManager.Instance.LastProfileID))
			{
				ProfileManager.Instance.SetLastProfile(printer.Id.ToString());
			}

			printerSettings.UserLayer[SettingsKey.active_theme_name] = UserSettings.Instance.get(UserSettingsKey.ActiveThemeName);

			// Import macros from the database
			var allMacros =  Datastore.Instance.dbSQLite.Query<CustomCommands>("SELECT * FROM CustomCommands WHERE PrinterId = " + printer.Id);
			printerSettings.Macros = allMacros.Select(macro => new GCodeMacro()
			{
				GCode = macro.Value.Trim(),
				Name = macro.Name,
				LastModified = macro.DateLastModified
			}).ToList();

			string query = string.Format("SELECT * FROM PrinterSetting WHERE Name = 'PublishBedImage' and PrinterId = {0};", printer.Id);
			var publishBedImage = Datastore.Instance.dbSQLite.Query<PrinterSetting>(query).FirstOrDefault();

			printerSettings.UserLayer[SettingsKey.publish_bed_image] = publishBedImage?.Value == "true" ? "1" : "0";

			// Print leveling
			var printLevelingData = PrintLevelingData.Create(
				printerSettings, 
				printer.PrintLevelingJsonData, 
				printer.PrintLevelingProbePositions);

			printerSettings.UserLayer[SettingsKey.print_leveling_data] = JsonConvert.SerializeObject(printLevelingData);
			printerSettings.UserLayer[SettingsKey.print_leveling_enabled] = printer.DoPrintLeveling ? "true" : "false";

			printerSettings.UserLayer["manual_movement_speeds"] = printer.ManualMovementSpeeds;

			// make sure we clear the one time settings
			printerSettings.OemLayer[SettingsKey.spiral_vase] = "";
			printerSettings.OemLayer[SettingsKey.bottom_clip_amount] = "";
			printerSettings.OemLayer[SettingsKey.layer_to_pause] = "";

			// TODO: Where can we find CalibrationFiiles in the current model?
			//layeredProfile.SetActiveValue(""calibration_files"", ???);

			printerSettings.ID = printer.Id.ToString();

			printerSettings.DocumentVersion = PrinterSettings.LatestVersion;

			printerSettings.Helpers.SetComPort(printer.ComPort);

			printerSettings.Save();
		}
 public PrinterActionLink(string text, Printer printer, int fontSize = 10)
     : base(text, fontSize)
 {
     this.LinkedPrinter = printer;
 }
        public EditConnectionWidget(ConnectionWindow windowController, GuiWidget containerWindowToClose, Printer activePrinter = null, object state = null)
            : base(windowController, containerWindowToClose)
        {
			textImageButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
			textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
			textImageButtonFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
			textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
            textImageButtonFactory.borderWidth = 0;

			linkButtonFactory.textColor = ActiveTheme.Instance.PrimaryTextColor;
            linkButtonFactory.fontSize = 8;

            this.BackgroundColor = ActiveTheme.Instance.SecondaryBackgroundColor;
            this.AnchorAll();
            this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off

            GuiWidget mainContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);
            mainContainer.AnchorAll();
            mainContainer.Padding = new BorderDouble(3, 0, 3, 5);
            mainContainer.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;

            string headerTitle;

            if (activePrinter == null)
            {
                headerTitle = string.Format("Add a Printer");
                this.addNewPrinterFlag = true;
                this.ActivePrinter = new Printer();
                this.ActivePrinter.Name = "Default Printer";
                this.ActivePrinter.BaudRate = "250000";
                try
                {
                    this.ActivePrinter.ComPort = FrostedSerialPort.GetPortNames()[0];
                }
                catch
                {
                    //No active COM ports
                }
            }
            else
            {
                this.ActivePrinter = activePrinter;
                string editHeaderTitleTxt = LocalizedString.Get("Edit"); 
				headerTitle = string.Format("{1} - {0}", this.ActivePrinter.Name, editHeaderTitleTxt);
                if (this.ActivePrinter.BaudRate == null)
                {
                    this.ActivePrinter.BaudRate = "250000";
                }
                if (this.ActivePrinter.ComPort == null)
                {
                    try
                    {
                        this.ActivePrinter.ComPort = FrostedSerialPort.GetPortNames()[0];
                    }
                    catch
                    {
                        //No active COM ports
                    }
                }
            }

            FlowLayoutWidget headerRow = new FlowLayoutWidget(FlowDirection.LeftToRight);
            headerRow.Margin = new BorderDouble(0, 3, 0, 0);
            headerRow.Padding = new BorderDouble(0, 3, 0, 3);
            headerRow.HAnchor = HAnchor.ParentLeftRight;
            {

                TextWidget headerLabel = new TextWidget(headerTitle, pointSize:14);
                headerLabel.TextColor = this.defaultTextColor;

                headerRow.AddChild(headerLabel);
            }

            ConnectionControlContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); 
            ConnectionControlContainer.Padding = new BorderDouble(5);
            ConnectionControlContainer.BackgroundColor = ActiveTheme.Instance.SecondaryBackgroundColor;
            ConnectionControlContainer.HAnchor = HAnchor.ParentLeftRight;            
            {
                TextWidget printerNameLabel = new TextWidget(LocalizedString.Get("Printer Name"), 0, 0, 10);
                printerNameLabel.TextColor = this.defaultTextColor;
                printerNameLabel.HAnchor = HAnchor.ParentLeftRight;
                printerNameLabel.Margin = new BorderDouble(0, 0, 0, 1);

                printerNameInput = new MHTextEditWidget(this.ActivePrinter.Name);
                
                printerNameInput.HAnchor |= HAnchor.ParentLeftRight;

                comPortLabelWidget = new FlowLayoutWidget();

                Button refreshComPorts = linkButtonFactory.Generate(LocalizedString.Get("(refresh)"));
                refreshComPorts.Margin = new BorderDouble(left: 5);
                refreshComPorts.VAnchor = VAnchor.ParentBottom;
                refreshComPorts.Click += new ButtonBase.ButtonEventHandler(RefreshComPorts);

                TextWidget comPortLabel = new TextWidget(LocalizedString.Get("Serial Port"), 0, 0, 10);
                comPortLabel.TextColor = this.defaultTextColor;

                comPortLabelWidget.AddChild(comPortLabel);
                comPortLabelWidget.AddChild(refreshComPorts);
                comPortLabelWidget.Margin = new BorderDouble(0, 0, 0, 10);
                comPortLabelWidget.HAnchor = HAnchor.ParentLeftRight;

                FlowLayoutWidget comPortContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);
                comPortContainer.Margin = new BorderDouble(0);
                comPortContainer.HAnchor = HAnchor.ParentLeftRight;
                

                int portIndex = 0;
                foreach (string serialPort in FrostedSerialPort.GetPortNames())
                {
                    //Filter com port list based on usb type (applies to Mac mostly)
                    bool looks_like_mac = serialPort.StartsWith("/dev/tty.");
                    bool looks_like_pc = serialPort.StartsWith("COM");
                    if (looks_like_mac || looks_like_pc)
                    {
                        SerialPortIndexRadioButton comPortOption = createComPortOption(serialPort);
                        comPortContainer.AddChild(comPortOption);
                        portIndex++;
                    }
                }

                //If there are no com ports in the filtered list assume we are missing something and show the unfiltered list
                if (portIndex == 0)
                {

                    foreach (string serialPort in FrostedSerialPort.GetPortNames())
                    {
                        SerialPortIndexRadioButton comPortOption = createComPortOption(serialPort);
                        comPortContainer.AddChild(comPortOption);
                        portIndex++;
                    }
                }

                if (!printerComPortIsAvailable && this.ActivePrinter.ComPort != null)
                {
                    SerialPortIndexRadioButton comPortOption = createComPortOption(this.ActivePrinter.ComPort);
                    comPortOption.Enabled = false;
                    comPortContainer.AddChild(comPortOption);
                    portIndex++;
                }

                //If there are still no com ports show a message to that effect
                if (portIndex == 0)
                {
                    TextWidget comPortOption = new TextWidget(LocalizedString.Get("No COM ports available"));
                    comPortOption.Margin = new BorderDouble(3, 6, 5, 6);
                    comPortOption.TextColor = this.subContainerTextColor;
                    comPortContainer.AddChild(comPortOption);
                }


                TextWidget baudRateLabel = new TextWidget(LocalizedString.Get("Baud Rate"), 0, 0, 10);
                baudRateLabel.TextColor = this.defaultTextColor;
                baudRateLabel.Margin = new BorderDouble(0, 0, 0, 10);
                baudRateLabel.HAnchor = HAnchor.ParentLeftRight;

                baudRateWidget = GetBaudRateWidget();
                baudRateWidget.HAnchor = HAnchor.ParentLeftRight;

                FlowLayoutWidget printerMakeContainer = createPrinterMakeContainer();
                FlowLayoutWidget printerModelContainer = createPrinterModelContainer();

                enableAutoconnect = new CheckBox(LocalizedString.Get("Auto Connect"));
				enableAutoconnect.TextColor = ActiveTheme.Instance.PrimaryTextColor;
                enableAutoconnect.Margin = new BorderDouble(top: 10);
                enableAutoconnect.HAnchor = HAnchor.ParentLeft;
                if (this.ActivePrinter.AutoConnectFlag)
                {
                    enableAutoconnect.Checked = true;
                }

                if (state as StateBeforeRefresh != null)
                {
                    enableAutoconnect.Checked = ((StateBeforeRefresh)state).autoConnect;
                }

                ConnectionControlContainer.VAnchor = VAnchor.ParentBottomTop;
                ConnectionControlContainer.AddChild(printerNameLabel);
                ConnectionControlContainer.AddChild(printerNameInput);
                ConnectionControlContainer.AddChild(printerMakeContainer);
                ConnectionControlContainer.AddChild(printerModelContainer);
                ConnectionControlContainer.AddChild(comPortLabelWidget);
                ConnectionControlContainer.AddChild(comPortContainer);
                ConnectionControlContainer.AddChild(baudRateLabel);
                ConnectionControlContainer.AddChild(baudRateWidget);
                ConnectionControlContainer.AddChild(enableAutoconnect);
            }

            FlowLayoutWidget buttonContainer = new FlowLayoutWidget(FlowDirection.LeftToRight);
            buttonContainer.HAnchor = HAnchor.ParentLeft | HAnchor.ParentRight;
            //buttonContainer.VAnchor = VAnchor.BottomTop;
            buttonContainer.Margin = new BorderDouble(0, 3);
            {
                //Construct buttons
                saveButton = textImageButtonFactory.Generate(LocalizedString.Get("Save"));
                //saveButton.VAnchor = VAnchor.Bottom;

                cancelButton = textImageButtonFactory.Generate(LocalizedString.Get("Cancel"));
                //cancelButton.VAnchor = VAnchor.Bottom;
                cancelButton.Click += new ButtonBase.ButtonEventHandler(CancelButton_Click);

                //Add buttons to buttonContainer
                buttonContainer.AddChild(saveButton);
                buttonContainer.AddChild(cancelButton);
            }

            //mainContainer.AddChild(new PrinterChooser());

            mainContainer.AddChild(headerRow);
            mainContainer.AddChild(ConnectionControlContainer);
            mainContainer.AddChild(buttonContainer);

            this.AddChild(mainContainer);

            BindSaveButtonHandlers();
			BindBaudRateHandlers();
        }
		private MatterControlApplication(double width, double height)
			: base(width, height)
		{
			Name = "MatterControl";

			// set this at startup so that we can tell next time if it got set to true in close
			UserSettings.Instance.Fields.StartCount = UserSettings.Instance.Fields.StartCount + 1;

			this.commandLineArgs = Environment.GetCommandLineArgs();
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

			bool forceSofwareRendering = false;

			GCodeFileLoaded.PauseOnLayerProcessor = PauseOnLayer;

			for (int currentCommandIndex = 0; currentCommandIndex < commandLineArgs.Length; currentCommandIndex++)
			{
				string command = commandLineArgs[currentCommandIndex];
				string commandUpper = command.ToUpper();
				switch (commandUpper)
				{
					case "FORCE_SOFTWARE_RENDERING":
						forceSofwareRendering = true;
						GL.ForceSoftwareRendering();
						break;

					case "CLEAR_CACHE":
						AboutWidget.DeleteCacheData();
						break;

					case "SHOW_MEMORY":
						ShowMemoryUsed = true;
						break;

					case "DO_GC_COLLECT_EVERY_DRAW":
						ShowMemoryUsed = true;
						DoCGCollectEveryDraw = true;
						break;

					case "CREATE_AND_SELECT_PRINTER":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							currentCommandIndex++;
							string argument = commandLineArgs[currentCommandIndex];
							string[] printerData = argument.Split(',');
							if (printerData.Length >= 2)
							{
								Printer ActivePrinter = new Printer();

								ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]);
								ActivePrinter.Make = printerData[0];
								ActivePrinter.Model = printerData[1];

								if (printerData.Length == 3)
								{
									ActivePrinter.ComPort = printerData[2];
								}

								PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter);
								test.LoadDefaultSliceSettings(ActivePrinter.Make, ActivePrinter.Model);
								ActivePrinterProfile.Instance.ActivePrinter = ActivePrinter;
							}
						}

						break;

					case "CONNECT_TO_PRINTER":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter();
						}
						break;

					case "START_PRINT":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							bool hasBeenRun = false;
							currentCommandIndex++;
							string fullPath = commandLineArgs[currentCommandIndex];
							QueueData.Instance.RemoveAll();
							if (!string.IsNullOrEmpty(fullPath))
							{
								string fileName = Path.GetFileNameWithoutExtension(fullPath);
								QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(fileName, fullPath)));
								PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) =>
								{
									if (!hasBeenRun && PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected)
									{
										hasBeenRun = true;
										PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible();
									}
								}, ref unregisterEvent);
							}
						}
						break;

					case "SLICE_AND_EXPORT_GCODE":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							currentCommandIndex++;
							string fullPath = commandLineArgs[currentCommandIndex];
							QueueData.Instance.RemoveAll();
							if (!string.IsNullOrEmpty(fullPath))
							{
								string fileName = Path.GetFileNameWithoutExtension(fullPath);
								PrintItemWrapper printItemWrapper = new PrintItemWrapper(new PrintItem(fileName, fullPath));
								QueueData.Instance.AddItem(printItemWrapper);

								SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
								ExportPrintItemWindow exportForTest = new ExportPrintItemWindow(printItemWrapper);
								exportForTest.ExportGcodeCommandLineUtility(fileName);
							}
						}
						break;
				}

				if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper()))
				{
					// If we are the only instance running then do nothing.
					// Else send these to the running instance so it can load them.
				}
			}

			//WriteTestGCodeFile();
#if !DEBUG
			if (File.Exists("RunUnitTests.txt"))
#endif
			{
#if IS_WINDOWS_FORMS
				if (!Clipboard.IsInitialized)
				{
					Clipboard.SetSystemClipboard(new WindowsFormsClipboard());
				}
#endif

				// you can turn this on to debug some bounds issues
				//GuiWidget.DebugBoundsUnderMouse = true;
			}

			GuiWidget.DefaultEnforceIntegerBounds = true;

			if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
			{
				TextWidget.GlobalPointSizeScaleRatio = 1.3;
			}

			using (new PerformanceTimer("Startup", "MainView"))
			{
				this.AddChild(ApplicationController.Instance.MainView);
			}
			this.MinimumSize = minSize;
			this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off

#if false // this is to test freeing gcodefile memory
			Button test = new Button("test");
			test.Click += (sender, e) =>
			{
				//MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile();
				//gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode");
				SystemWindow window = new SystemWindow(100, 100);
				window.ShowAsSystemWindow();
			};
			allControls.AddChild(test);
#endif
			this.AnchorAll();

			if (!forceSofwareRendering)
			{
				UseOpenGL = true;
			}
			string version = "1.5";

			Title = "MatterControl {0}".FormatWith(version);
			if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
			{
				Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra);
			}

			UiThread.RunOnIdle(CheckOnPrinter);

			string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition");
			if (desktopPosition != null && desktopPosition != "")
			{
				string[] sizes = desktopPosition.Split(',');

				//If the desktop position is less than -10,-10, override
				int xpos = Math.Max(int.Parse(sizes[0]), -10);
				int ypos = Math.Max(int.Parse(sizes[1]), -10);

				DesktopPosition = new Point2D(xpos, ypos);
			}
		}
 public PrinterSelectRadioButton(Printer printer)
     : base(printer.Name)
 {
     this.printer = printer;
 }
		public EditConnectionWidget(ConnectionWindow windowController, GuiWidget containerWindowToClose, Printer activePrinter = null, object state = null)
			: base(windowController, containerWindowToClose)
		{
			textImageButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor;
			textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
			textImageButtonFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor;
			textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;
			textImageButtonFactory.borderWidth = 0;

			linkButtonFactory.textColor = ActiveTheme.Instance.PrimaryTextColor;
			linkButtonFactory.fontSize = 8;

			this.BackgroundColor = ActiveTheme.Instance.SecondaryBackgroundColor;
			this.AnchorAll();
			this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off

			GuiWidget mainContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);
			mainContainer.AnchorAll();
			mainContainer.Padding = new BorderDouble(3, 3, 3, 5);
			mainContainer.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;

			string headerTitle;

			if (activePrinter == null)
			{
				headerTitle = string.Format("Add a Printer");
				this.addNewPrinterFlag = true;
				this.ActivePrinter = new Printer();
				this.ActivePrinter.Name = "Default Printer";
				this.ActivePrinter.BaudRate = "250000";
				try
				{
					this.ActivePrinter.ComPort = FrostedSerialPort.GetPortNames().FirstOrDefault();
				}
				catch(Exception e)
				{
					Debug.Print(e.Message);
					GuiWidget.BreakInDebugger();
					//No active COM ports
				}
			}
			else
			{
				this.ActivePrinter = activePrinter;
				string editHeaderTitleTxt = LocalizedString.Get("Edit");
				headerTitle = string.Format("{1} - {0}", this.ActivePrinter.Name, editHeaderTitleTxt);
				if (this.ActivePrinter.BaudRate == null)
				{
					this.ActivePrinter.BaudRate = "250000";
				}
				if (this.ActivePrinter.ComPort == null)
				{
					try
					{
						this.ActivePrinter.ComPort = FrostedSerialPort.GetPortNames().FirstOrDefault();
					}
					catch(Exception e)
					{
						Debug.Print(e.Message);
						GuiWidget.BreakInDebugger();
						//No active COM ports
					}
				}
			}

			FlowLayoutWidget headerRow = new FlowLayoutWidget(FlowDirection.LeftToRight);
			headerRow.Margin = new BorderDouble(0, 3, 0, 0);
			headerRow.Padding = new BorderDouble(0, 3, 0, 3);
			headerRow.HAnchor = HAnchor.ParentLeftRight;
			{
				TextWidget headerLabel = new TextWidget(headerTitle, pointSize: 14);
				headerLabel.TextColor = this.defaultTextColor;

				headerRow.AddChild(headerLabel);
			}

			ConnectionControlContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);
			ConnectionControlContainer.Padding = new BorderDouble(5);
			ConnectionControlContainer.BackgroundColor = ActiveTheme.Instance.SecondaryBackgroundColor;
			ConnectionControlContainer.HAnchor = HAnchor.ParentLeftRight;
			{
				TextWidget printerNameLabel = new TextWidget(LocalizedString.Get("Printer Name"), 0, 0, 10);
				printerNameLabel.TextColor = this.defaultTextColor;
				printerNameLabel.HAnchor = HAnchor.ParentLeftRight;
				printerNameLabel.Margin = new BorderDouble(0, 0, 0, 1);

				printerNameInput = new MHTextEditWidget(this.ActivePrinter.Name);

				printerNameInput.HAnchor |= HAnchor.ParentLeftRight;

				comPortLabelWidget = new FlowLayoutWidget();

				Button refreshComPorts = linkButtonFactory.Generate(LocalizedString.Get("(refresh)"));
				refreshComPorts.Margin = new BorderDouble(left: 5);
				refreshComPorts.VAnchor = VAnchor.ParentBottom;
				refreshComPorts.Click += new EventHandler(RefreshComPorts);

				FlowLayoutWidget comPortContainer = null;

#if !__ANDROID__
				TextWidget comPortLabel = new TextWidget(LocalizedString.Get("Serial Port"), 0, 0, 10);
				comPortLabel.TextColor = this.defaultTextColor;

				comPortLabelWidget.AddChild(comPortLabel);
				comPortLabelWidget.AddChild(refreshComPorts);
				comPortLabelWidget.Margin = new BorderDouble(0, 0, 0, 10);
				comPortLabelWidget.HAnchor = HAnchor.ParentLeftRight;

				comPortContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);
				comPortContainer.Margin = new BorderDouble(0);
				comPortContainer.HAnchor = HAnchor.ParentLeftRight;

				CreateSerialPortControls(comPortContainer, this.ActivePrinter.ComPort);
#endif

				TextWidget baudRateLabel = new TextWidget(LocalizedString.Get("Baud Rate"), 0, 0, 10);
				baudRateLabel.TextColor = this.defaultTextColor;
				baudRateLabel.Margin = new BorderDouble(0, 0, 0, 10);
				baudRateLabel.HAnchor = HAnchor.ParentLeftRight;

				baudRateWidget = GetBaudRateWidget();
				baudRateWidget.HAnchor = HAnchor.ParentLeftRight;

				FlowLayoutWidget printerMakeContainer = createPrinterMakeContainer();
				FlowLayoutWidget printerModelContainer = createPrinterModelContainer();

				enableAutoconnect = new CheckBox(LocalizedString.Get("Auto Connect"));
				enableAutoconnect.TextColor = ActiveTheme.Instance.PrimaryTextColor;
				enableAutoconnect.Margin = new BorderDouble(top: 10);
				enableAutoconnect.HAnchor = HAnchor.ParentLeft;
				if (this.ActivePrinter.AutoConnectFlag)
				{
					enableAutoconnect.Checked = true;
				}

				if (state as StateBeforeRefresh != null)
				{
					enableAutoconnect.Checked = ((StateBeforeRefresh)state).autoConnect;
				}

				SerialPortControl serialPortScroll = new SerialPortControl();

				if (comPortContainer != null)
				{
					serialPortScroll.AddChild(comPortContainer);
				}

				ConnectionControlContainer.VAnchor = VAnchor.ParentBottomTop;
				ConnectionControlContainer.AddChild(printerNameLabel);
				ConnectionControlContainer.AddChild(printerNameInput);
				ConnectionControlContainer.AddChild(printerMakeContainer);
				ConnectionControlContainer.AddChild(printerModelContainer);
				ConnectionControlContainer.AddChild(comPortLabelWidget);
				ConnectionControlContainer.AddChild(serialPortScroll);
				ConnectionControlContainer.AddChild(baudRateLabel);
				ConnectionControlContainer.AddChild(baudRateWidget);
#if !__ANDROID__
				ConnectionControlContainer.AddChild(enableAutoconnect);
#endif
			}

			FlowLayoutWidget buttonContainer = new FlowLayoutWidget(FlowDirection.LeftToRight);
			buttonContainer.HAnchor = HAnchor.ParentLeft | HAnchor.ParentRight;
			//buttonContainer.VAnchor = VAnchor.BottomTop;
			buttonContainer.Margin = new BorderDouble(0, 5, 0, 3);
			{
				//Construct buttons
				saveButton = textImageButtonFactory.Generate(LocalizedString.Get("Save"));
				//saveButton.VAnchor = VAnchor.Bottom;

				cancelButton = textImageButtonFactory.Generate(LocalizedString.Get("Cancel"));
				//cancelButton.VAnchor = VAnchor.Bottom;
				cancelButton.Click += new EventHandler(CancelButton_Click);

				//Add buttons to buttonContainer
				buttonContainer.AddChild(saveButton);
				buttonContainer.AddChild(new HorizontalSpacer());
				buttonContainer.AddChild(cancelButton);
			}

			//mainContainer.AddChild(new PrinterChooser());

			mainContainer.AddChild(headerRow);
			mainContainer.AddChild(ConnectionControlContainer);
			mainContainer.AddChild(buttonContainer);

			this.AddChild(mainContainer);

			BindSaveButtonHandlers();
			BindBaudRateHandlers();
		}
Esempio n. 20
0
		public void ChangeToAddPrinter()
		{
			this.activePrinter = null;
			UiThread.RunOnIdle(DoChangeToAddPrinter);
		}
		private static void LoadMaterialSettings(LayeredProfile layeredProfile, Printer printer)
		{
			var materialAssignments = printer.MaterialCollectionIds.Split(',');

			var collections = Datastore.Instance.dbSQLite.Table<SliceSettingsCollection>().Where(v => v.PrinterId == printer.Id && v.Tag == "material");
			foreach (var collection in collections)
			{
				var settingsDictionary = LoadSettings(collection);
				layeredProfile.MaterialLayers[collection.Name] = new SettingsLayer(settingsDictionary);
			}
		}
Esempio n. 22
0
        public PrinterListItemEdit(Printer printerRecord, ConnectionWindow windowController)
            :base(printerRecord, windowController)
        {            
            linkButtonFactory.fontSize = 10;
            linkButtonFactory.padding = 0;
            linkButtonFactory.margin = new BorderDouble(3, 0);
            
            this.printerRecord = printerRecord;
            this.Margin = new BorderDouble(1);
            this.BackgroundColor = this.defaultBackgroundColor;
            this.Padding = new BorderDouble(5);
            this.HAnchor = HAnchor.ParentLeftRight;

            printerName = new TextWidget(this.printerRecord.Name);
            printerName.TextColor = this.defaultTextColor;
            printerName.HAnchor = HAnchor.ParentLeftRight;

			editLink = linkButtonFactory.Generate(new LocalizedString("edit").Translated);
            editLink.VAnchor = VAnchor.ParentCenter;

			removeLink = linkButtonFactory.Generate(new LocalizedString("remove").Translated);
            removeLink.VAnchor = VAnchor.ParentCenter;

            this.AddChild(printerName);
            this.AddChild(editLink);
            this.AddChild(removeLink);     

            BindHandlers();
        }
		public static void LoadQualitySettings(LayeredProfile layeredProfile, Printer printer)
		{
			var collections = Datastore.Instance.dbSQLite.Table<SliceSettingsCollection>().Where(v => v.PrinterId == printer.Id && v.Tag == "quality");
			foreach (var collection in collections)
			{
				var settingsDictionary = LoadSettings(collection);
				layeredProfile.QualityLayers[collection.Name] = new SettingsLayer(settingsDictionary);
			}
		}
		private MatterControlApplication(double width, double height, out bool showWindow)
			: base(width, height)
		{
			Name = "MatterControl";
			showWindow = false;

			// set this at startup so that we can tell next time if it got set to true in close
			UserSettings.Instance.Fields.StartCount = UserSettings.Instance.Fields.StartCount + 1;

			this.commandLineArgs = Environment.GetCommandLineArgs();
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

			bool forceSofwareRendering = false;

			for (int currentCommandIndex = 0; currentCommandIndex < commandLineArgs.Length; currentCommandIndex++)
			{
				string command = commandLineArgs[currentCommandIndex];
				string commandUpper = command.ToUpper();
				switch (commandUpper)
				{
					case "TEST":
						CheckKnownAssemblyConditionalCompSymbols();
						return;

					case "FORCE_SOFTWARE_RENDERING":
						forceSofwareRendering = true;
						GL.ForceSoftwareRendering();
						break;

					case "MHSERIAL_TO_ANDROID":
						{
							Dictionary<string, string> vidPid_NameDictionary = new Dictionary<string, string>();
							string[] MHSerialLines = File.ReadAllLines(Path.Combine("..", "..", "StaticData", "Drivers", "MHSerial", "MHSerial.inf"));
							foreach (string line in MHSerialLines)
							{
								if (line.Contains("=DriverInstall,"))
								{
									string name = Regex.Match(line, "%(.*).name").Groups[1].Value;
									string vid = Regex.Match(line, "VID_(.*)&PID").Groups[1].Value;
									string pid = Regex.Match(line, "PID_([0-9a-fA-F]+)").Groups[1].Value;
									string vidPid = "{0},{1}".FormatWith(vid, pid);
									if (!vidPid_NameDictionary.ContainsKey(vidPid))
									{
										vidPid_NameDictionary.Add(vidPid, name);
									}
								}
							}

							using (StreamWriter deviceFilter = new StreamWriter("deviceFilter.txt"))
							{
								using (StreamWriter serialPort = new StreamWriter("serialPort.txt"))
								{
									foreach (KeyValuePair<string, string> vidPid_Name in vidPid_NameDictionary)
									{
										string[] vidPid = vidPid_Name.Key.Split(',');
										int vid = Int32.Parse(vidPid[0], System.Globalization.NumberStyles.HexNumber);
										int pid = Int32.Parse(vidPid[1], System.Globalization.NumberStyles.HexNumber);
										serialPort.WriteLine("customTable.AddProduct(0x{0:X4}, 0x{1:X4}, cdcDriverType);  // {2}".FormatWith(vid, pid, vidPid_Name.Value));
										deviceFilter.WriteLine("<!-- {2} -->\n<usb-device vendor-id=\"{0}\" product-id=\"{1}\" />".FormatWith(vid, pid, vidPid_Name.Value));
									}
								}
							}
						}
						return;

					case "CLEAR_CACHE":
						AboutWidget.DeleteCacheData();
						break;

					case "SHOW_MEMORY":
						ShowMemoryUsed = true;
						break;

					case "DO_GC_COLLECT_EVERY_DRAW":
						ShowMemoryUsed = true;
						DoCGCollectEveryDraw = true;
						break;

					case "CREATE_AND_SELECT_PRINTER":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							currentCommandIndex++;
							string argument = commandLineArgs[currentCommandIndex];
							string[] printerData = argument.Split(',');
							if (printerData.Length >= 2)
							{
								Printer ActivePrinter = new Printer();

								ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]);
								ActivePrinter.Make = printerData[0];
								ActivePrinter.Model = printerData[1];

								if (printerData.Length == 3)
								{
									ActivePrinter.ComPort = printerData[2];
								}

								PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter);
								test.LoadDefaultSliceSettings(ActivePrinter.Make, ActivePrinter.Model);
								ActivePrinterProfile.Instance.ActivePrinter = ActivePrinter;
							}
						}

						break;

					case "CONNECT_TO_PRINTER":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter();
						}
						break;

					case "START_PRINT":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							bool hasBeenRun = false;
							currentCommandIndex++;
							string fullPath = commandLineArgs[currentCommandIndex];
							QueueData.Instance.RemoveAll();
							if (!string.IsNullOrEmpty(fullPath))
							{
								string fileName = Path.GetFileNameWithoutExtension(fullPath);
								QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(fileName, fullPath)));
								PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) =>
								{
									if (!hasBeenRun && PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected)
									{
										hasBeenRun = true;
										PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible();
									}
								}, ref unregisterEvent);
							}
						}
						break;

					case "SLICE_AND_EXPORT_GCODE":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							currentCommandIndex++;
							string fullPath = commandLineArgs[currentCommandIndex];
							QueueData.Instance.RemoveAll();
							if (!string.IsNullOrEmpty(fullPath))
							{
								string fileName = Path.GetFileNameWithoutExtension(fullPath);
								PrintItemWrapper printItemWrapper = new PrintItemWrapper(new PrintItem(fileName, fullPath));
								QueueData.Instance.AddItem(printItemWrapper);

								SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
								ExportPrintItemWindow exportForTest = new ExportPrintItemWindow(printItemWrapper);
								exportForTest.ExportGcodeCommandLineUtility(fileName);
							}
						}
						break;
				}

				if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper()))
				{
					// If we are the only instance running then do nothing.
					// Else send these to the running instance so it can load them.
				}
			}

			//WriteTestGCodeFile();
#if !DEBUG
			if (File.Exists("RunUnitTests.txt"))
#endif
			{
#if IS_WINDOWS_FORMS
				if (!Clipboard.IsInitialized)
				{
					Clipboard.SetSystemClipboard(new WindowsFormsClipboard());
				}
#endif

				// you can turn this on to debug some bounds issues
				//GuiWidget.DebugBoundsUnderMouse = true;
			}

			GuiWidget.DefaultEnforceIntegerBounds = true;

			if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
			{
				TextWidget.GlobalPointSizeScaleRatio = 1.3;
			}

			using (new PerformanceTimer("Startup", "MainView"))
			{
				this.AddChild(ApplicationController.Instance.MainView);
			}
			this.MinimumSize = minSize;
			this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off

#if false // this is to test freeing gcodefile memory
			Button test = new Button("test");
			test.Click += (sender, e) =>
			{
				//MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile();
				//gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode");
				SystemWindow window = new SystemWindow(100, 100);
				window.ShowAsSystemWindow();
			};
			allControls.AddChild(test);
#endif
			this.AnchorAll();

			if (!forceSofwareRendering)
			{
				UseOpenGL = true;
			}
			string version = "1.4";

			Title = "MatterControl {0}".FormatWith(version);
			if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
			{
				Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra);
			}

			UiThread.RunOnIdle(CheckOnPrinter);

			string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition");
			if (desktopPosition != null && desktopPosition != "")
			{
				string[] sizes = desktopPosition.Split(',');

				//If the desktop position is less than -10,-10, override
				int xpos = Math.Max(int.Parse(sizes[0]), -10);
				int ypos = Math.Max(int.Parse(sizes[1]), -10);

				DesktopPosition = new Point2D(xpos, ypos);
			}

			showWindow = true;
		}
		public static Dictionary<string, string> LoadOemLayer(Printer printer)
		{
			SliceSettingsCollection collection;
			if (printer.DefaultSettingsCollectionId != 0)
			{
				int activePrinterSettingsID = printer.DefaultSettingsCollectionId;
				collection = Datastore.Instance.dbSQLite.Table<SliceSettingsCollection>().Where(v => v.Id == activePrinterSettingsID).Take(1).FirstOrDefault();
			}
			else
			{
				collection = new SliceSettingsCollection();
				collection.Name = printer.Name;
				collection.Commit();

				printer.DefaultSettingsCollectionId = collection.Id;
			}

			return LoadSettings(collection);
		}
		private void ConnectToPrinter(Printer printerRecord)
		{
			PrinterOutputCache.Instance.Clear();
			LinesToWriteQueue.Clear();
			//Attempt connecting to a specific printer
			this.stopTryingToConnect = false;
			firmwareType = FirmwareTypes.Unknown;
			firmwareVersion = null;
			firmwareUriGcodeSend = false;

			// On Android, there will never be more than one serial port available for us to connect to. Override the current .ComPort value to account for
			// this aspect to ensure the validation logic that verifies port availability/in use status can proceed without additional workarounds for Android
#if __ANDROID__
			string currentPortName = FrostedSerialPort.GetPortNames().FirstOrDefault();

			if (!string.IsNullOrEmpty(currentPortName))
			{
				this.ActivePrinter.ComPort = currentPortName;
			}
#endif

			if (SerialPortIsAvailable(this.ActivePrinter.ComPort))
			{
				//Create a timed callback to determine whether connection succeeded
				Timer connectionTimer = new Timer(new TimerCallback(ConnectionCallbackTimer));
				connectionTimer.Change(100, 0);

				//Create and start connection thread
				connectThread = new Thread(Connect_Thread);
				connectThread.Name = "Connect To Printer";
				connectThread.IsBackground = true;
				connectThread.Start();
			}
			else
			{
				Debug.WriteLine("Connection failed: {0}".FormatWith(this.ActivePrinter.ComPort));

				connectionFailureMessage = string.Format(
									"{0} is not available".Localize(),
									this.ActivePrinter.ComPort);

				OnConnectionFailed(null);
			}
		}
Esempio n. 27
0
 public void ChangedToEditPrinter(Printer activePrinter)
 {
     this.activePrinter = activePrinter;
     UiThread.RunOnIdle(DoChangeToEditPrinter);
 }