using System; using System.Collections.Generic; using System.Diagnostics; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; using Tango.Core; namespace Tango.ContinuousPumpsActivation.UI.Model { public class PumpModel : ExtendedObject { const char ETX = '\x0d'; private List _availablePortNames; public List AvailablePortNames { get { return _availablePortNames; } set { _availablePortNames = value; RaisePropertyChangedAuto(); } } private string _pumpName; public string PumpName { get { return _pumpName; } set { _pumpName = value; RaisePropertyChangedAuto(); } } private string _portName; public string PortName { get { return _portName; } set { if (_portName != value) { _portName = value; OnPortNameChanged(); RaisePropertyChangedAuto(); } } } private SerialPort _port; public SerialPort Port { get { return _port; } set { _port = value; RaisePropertyChangedAuto(); } } private double _status; public double Status { get { return _status; } set { _status = value; RaisePropertyChangedAuto(); } } private double _setValue; public double SetValue { get { return _setValue; } set { _setValue = value; RaisePropertyChangedAuto(); } } private Color _pumpColor; public Color PumpColor { get { return _pumpColor; } set { _pumpColor = value; RaisePropertyChangedAuto(); } } public PumpModel(string pumpname, string defaultPortname, Color color, List availablePortNames) { PumpName = pumpname; PortName = defaultPortname; Status = 0.0; SetValue = 0.0; PumpColor = color; AvailablePortNames = availablePortNames; } private void OnPortNameChanged() { if (Port != null && Port.IsOpen) { Port.Close(); } Port = null; SetAndOpenPort(); } public void SetAndOpenPort() { if (String.IsNullOrEmpty(PortName)) return; try { if (Port == null) { Port = new SerialPort(PortName, 19200, Parity.None, 8, StopBits.One); Port.ErrorReceived += Port_ErrorReceived; Port.DataReceived += Port_DataReceived; Port.Open(); //Write("spgmnr1"); } else if(!Port.IsOpen) { Port.Open(); } } catch (Exception ex) { Debug.WriteLine($"Error: {ex.Message}"); } } public void StartPump() { if(Port != null && Port.IsOpen) { Status = SetValue; double value = 1000000 * SetValue; var s = String.Format($"run2,0,{value },0,0,0{ETX}"); Write(s); } } private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e) { // throw new NotImplementedException(); } private void Port_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { throw new NotImplementedException(); } public void StopPump() { Status = 0; if (Port!= null && Port.IsOpen) { Write($"stoppump{ETX}"); } } public void ClosePort() { if (Port != null && Port.IsOpen) { Port.Close(); } } public void Write(string command) { if(Port != null && Port.IsOpen) { byte[] data = Encoding.ASCII.GetBytes(command); Port.Write(data, 0, data.Length); //Port.Write(command); } } } }