public override void DoPrint(string[] lines)
        {
            var document = new FormattedDocument(lines, Printer.CharsPerLine).GetFormattedDocument().ToArray();

            foreach (var line in document)
            {
                var data = line.Contains("<") ? line.Split('<').Where(x => !string.IsNullOrEmpty(x)).Select(x => '<' + x) : line.Split('#');
                foreach (var s in data)
                {
                    if (s.Trim().ToLower() == "<w>")
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    if (s.ToLower().StartsWith("<lb"))
                    {
                        SerialPortService.WritePort(Printer.ShareName, RemoveTag(s) + "\n\r");
                    }
                    else if (s.ToLower().StartsWith("<xct"))
                    {
                        var lineData = s.ToLower().Replace("<xct", "").Trim(new[] { ' ', '<', '>' });
                        SerialPortService.WriteCommand(Printer.ShareName, lineData, Printer.CodePage);
                    }
                    else
                    {
                        SerialPortService.WritePort(Printer.ShareName, RemoveTag(s), Printer.CodePage);
                    }
                }
            }
            SerialPortService.ResetCache();
        }
Exemple #2
0
 private void Oven_FormClosing(object sender, FormClosingEventArgs e)
 {
     button_Stop_Click(null, null);
     HistoryFile.DeleteTmpFile();
     SerialPortService.CleanUp();
     Properties.Settings.Default.Save();
 }
Exemple #3
0
        private void SerialPortService_DataReceived(object sender, EventArgs e)
        {
            var buffer = new byte[SerialPortService.BytesToRead];

            SerialPortService.Read(buffer, 0, buffer.Length);


            switch (ConsoleOutput.OutputFormat)
            {
            case Format.Text:
                string text = Encoding.GetString(buffer, 0, buffer.Length);
                ConsoleService.Write(text);
                break;

            case Format.BytesDecimal:
                foreach (byte b in buffer)
                {
                    ConsoleService.Write("{0} ", b);
                }
                break;

            case Format.BytesHex:
                string str = BitConverter.ToString(buffer).Replace("-", " ");
                ConsoleService.Write("{0} ", str);
                break;
            }
        }
Exemple #4
0
 public override void DoPrint(string[] lines)
 {
     foreach (var line in lines)
     {
         var data = line.Contains("<") ? line.Split('<').Where(x => !string.IsNullOrEmpty(x)).Select(x => '<' + x) : line.Split('#');
         data = PrinterHelper.AlignLines(data, Printer.CharsPerLine, false);
         data = PrinterHelper.ReplaceChars(data, Printer.ReplacementPattern);
         foreach (var s in data)
         {
             if (s.Trim().ToLower() == "<w>")
             {
                 System.Threading.Thread.Sleep(100);
             }
             else if (s.ToLower().StartsWith("<lb"))
             {
                 SerialPortService.WritePort(Printer.ShareName, RemoveTag(s) + "\n\r");
             }
             else if (s.ToLower().StartsWith("<xct"))
             {
                 var lineData = s.ToLower().Replace("<xct", "").Trim(new[] { ' ', '<', '>' });
                 SerialPortService.WriteCommand(Printer.ShareName, lineData, Printer.CodePage);
             }
             else
             {
                 SerialPortService.WritePort(Printer.ShareName, RemoveTag(s), Printer.CodePage);
             }
         }
     }
 }
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            var controller     = new SerialSwitchController();
            var serialPort     = new SerialPortService();
            var macro          = new MacroService();
            var cancelableTask = new CancelableTaskService();
            var clock          = new SwitchClock();
            var work           = new WorkSituation();
            var gameCapture    = new GameCapture();
            var macroPool      = new MacroPool(clock, controller, cancelableTask, gameCapture);

            controller.SerialPort = serialPort;
            macro.TaskService     = cancelableTask;
            macro.Work            = work;
            macro.MacroPool       = macroPool;
            clock.Controller      = controller;
            clock.Cancellation    = cancelableTask;

            containerRegistry.RegisterInstance <IGameCapture>(gameCapture);
            containerRegistry.RegisterInstance <ISwitchController>(controller);
            containerRegistry.RegisterInstance <ISerialPortService>(serialPort);
            containerRegistry.RegisterInstance <IMacroService>(macro);
            containerRegistry.RegisterInstance <IMacroPool>(macroPool);
            containerRegistry.RegisterInstance <ITaskService>(cancelableTask);
            containerRegistry.RegisterInstance <ICanceler>(cancelableTask);
            containerRegistry.RegisterInstance <ICancellationRequest>(cancelableTask);
            containerRegistry.RegisterInstance <ISwitchClock>(clock);
            containerRegistry.RegisterInstance <IWorkSituation>(work);
        }
 public MainWindow()
 {
     InitializeComponent();
     _configJson = File.ReadAllText("config.json");
     foreach (var port in SerialPortService.GetSerialPorts())
     {
         SelectorBox.Items.Add(port);
     }
 }
Exemple #7
0
 /// <summary>
 /// 保存Modbus串口设置
 /// </summary>
 public static void SaveSystemSetting(SystemSetting setting)
 {
     _systemSetting = setting;
     BaseDataService.SaveSystemSetting(_systemSetting);
     SerialPortService.PortClose();
     LoadSystemSetting();
     //串口服务实例化
     // SerialPortService = SerialPortService.Instance(_systemSetting.ModbusSetting, GetSlaveConfig(), _systemSetting.WarningCabinetId);
 }
 public void UpdateAvailablePorts()
 {
     AvailablePorts.Clear();
     foreach (string portName in SerialPortService.GetAvailableSerialPorts().OrderBy(s => s))
     {
         AvailablePorts.Add(new ComPortInfo()
         {
             PortName = portName
         });
     }
 }
Exemple #9
0
        public MainForm()
        {
            InitializeComponent();
            _modbusService     = new ModbusService();
            _serialPortService = new SerialPortService();

            Configuration.Instance.LoadConfiguration("configuration.xml");
            _enableNodes = GetEnableNodes();
            var frequencySensorsReading = GetFrequencySensorReading();

            uxCheckStatusTimer.Interval = Convert.ToInt32(frequencySensorsReading);
        }
Exemple #10
0
 private void button7_Click(object sender, EventArgs e)
 {
     button7.Enabled  = false;
     button6.Enabled  = true;
     label8.ForeColor = Color.Red;
     label9.ForeColor = Color.White;
     if (th != null)
     {
         th.Abort();
         th = null;
     }
     _sps.StopService();
     _sps = null;
 }
Exemple #11
0
        public Shell(IApplicationState applicationState)
        {
            _applicationState = applicationState;
            InitializeComponent();
            LanguageProperty.OverrideMetadata(
                typeof(FrameworkElement),
                new FrameworkPropertyMetadata(
                    XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            var selectedIndexChange = DependencyPropertyDescriptor.FromProperty(Selector.SelectedIndexProperty, typeof(TabControl));

            selectedIndexChange.AddValueChanged(MainTabControl, MainTabControlSelectedIndexChanged);

            EventServiceFactory.EventService.GetEvent <GenericEvent <User> >().Subscribe(x =>
            {
                if (x.Topic == EventTopicNames.UserLoggedIn)
                {
                    UserLoggedIn(x.Value);
                }
                if (x.Topic == EventTopicNames.UserLoggedOut)
                {
                    UserLoggedOut(x.Value);
                }
            });

            EventServiceFactory.EventService.GetEvent <GenericEvent <UserControl> >().Subscribe(
                x =>
            {
                if (x.Topic == EventTopicNames.DashboardClosed)
                {
                    SerialPortService.ResetCache();
                    EventServiceFactory.EventService.PublishEvent(EventTopicNames.ResetCache, true);
                }
            });

            UserRegion.Visibility      = Visibility.Collapsed;
            RightUserRegion.Visibility = Visibility.Collapsed;
            Height = Properties.Settings.Default.ShellHeight;
            Width  = Properties.Settings.Default.ShellWidth;

            _timer         = new DispatcherTimer();
            _timer.Tick   += TimerTick;
            TimeLabel.Text = "...";

#if !DEBUG
            WindowStyle = WindowStyle.None;
            WindowState = WindowState.Maximized;
#endif
        }
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    SerialPortService.CleanUp();
                    _COMPort.Dispose();
                    _controller.Dispose();
                    SerialPortService.CleanUp();
                }

                disposedValue = true;
            }
        }
Exemple #13
0
        private async void InputThread()
        {
            try
            {
                while (true)
                {
                    char ch = await ConsoleService.ReadCharAsync();

                    SerialPortService.Write(ch);
                }
            }
            catch (Exception e)
            {
                await DialogService.ShowErrorDialogAsync(e.Message, "Exception");
            }
        }
Exemple #14
0
        private void start_Click(object sender, EventArgs e)
        {
            button7.Enabled  = true;
            button6.Enabled  = true;
            label8.ForeColor = Color.Red;
            label9.ForeColor = Color.White;
            if (th != null)
            {
                if (th.IsAlive)
                {
                    th.Abort();
                    th = null;
                }
            }
            if (_sps != null)
            {
                _sps.StopService();
            }

            if (Ports.SelectedIndex > -1)
            {
                MessageBox.Show(String.Format("你选择了串口 '{0}'", Ports.SelectedItem));
                try
                {
                    _sps = new PeriodicModeDriver(Ports.SelectedItem.ToString());
                    _sps.ReceiveError   += refresh;
                    _sps.ReceiveSuccess += ReceiveRequest;
                    _sps.StartService();
                    if (_sps.IsOnService == true)
                    {
                        label8.ForeColor = Color.LightGreen;
                    }
                    else
                    {
                        label8.ForeColor = Color.Red;
                    }
                }
                catch (Exception)
                {
                }
            }
            else
            {
                MessageBox.Show("Please select a port first");
            }
        }
Exemple #15
0
        /// <summary>
        /// Read Credit card data
        /// </summary>
        /// <param name="trackDebug"></param>
        /// <returns></returns>
        protected CreditCardTrackData ReadCreditCardTrackData(out string trackDebug)
        {
            string error  = "";
            string tracks = SerialPortService.ReadExisting(Settings.ComPort, Settings.ComBaudRate, Settings.ComReadTimeout, ref error);

            if (!String.IsNullOrEmpty(tracks))
            {
                trackDebug = "Track1:" + tracks;
                var trackData = ParseSwipeData(tracks);
                if (trackData != null)
                {
                    return(trackData);
                }
            }
            trackDebug = "Track1:" + error;

            return(null);
        }
Exemple #16
0
 private void button6_Click(object sender, EventArgs e)
 {
     if (Ports.SelectedIndex > -1)
     {
         MessageBox.Show(String.Format("你选择了串口 '{0}'", Ports.SelectedItem));
         button7.Enabled  = true;
         label9.ForeColor = Color.White;
         string port      = Ports.SelectedItem.ToString();
         int    portindex = Ports.SelectedIndex;
         if (portindex > -1)
         {
             button6.Enabled = false;
             try
             {
                 label8.ForeColor = Color.Blue;
                 th = new Thread(() =>
                 {
                     try
                     {
                         _sps = new RegularModeDriver(port);
                         _sps.ReceiveError   += refresh;
                         _sps.ReceiveSuccess += ReceiveRequest;
                         _sps.StartService();
                     }
                     catch (Exception)
                     {
                     }
                 });
                 th.Start();
             }
             catch (Exception)
             {
             }
         }
         else
         {
             MessageBox.Show("Please select a port first");
         }
     }
     else
     {
         MessageBox.Show("Please select a port first");
     }
 }
        private async Task PasteAndSendCommandImpl()
        {
            try
            {
                if (ConsoleService.IsEnabled)
                {
                    string text = ClipboardService.GetText();

                    int index = ConsoleService.SelectionStart;
                    await ConsoleService.InsertText(index, text);

                    SerialPortService.Write(text);
                }
            }
            catch (ArgumentException e)
            {
                await DialogService.ShowErrorDialogAsync(e.Message, "Exception");
            }
        }
Exemple #18
0
        private void EndSessionCommandImpl()
        {
            if (_cts != null)
            {
                _cts.Cancel();
            }

            ConsoleService.IsEnabled = false;

            SerialPortService.DataReceived -= SerialPortService_DataReceived;

            SerialPortService.Close();

            IsRunning = false;

            if (Ended != null)
            {
                Ended(this, new EventArgs());
            }
        }
Exemple #19
0
        /// <summary>
        /// 加载系统设置信息
        /// </summary>
        private static void LoadSystemSetting()
        {
            try
            {
                //获取系统设置信息
                _systemSetting = BaseDataService.GetSystemSetting();

                //串口服务实例化
                SerialPortService = SerialPortService.Instance(_systemSetting.ModbusSetting, GetSlaveConfig(), _systemSetting.WarningCabinetId);

                //分拣数据服务实例化
                sortingService = new SortingService(_systemSetting.CabinetNumber, _systemSetting.SortingPatten, _systemSetting.SortingSolution, _systemSetting.InterfaceType, _systemSetting.BoxWeight);
                //声音服务
                soundService = new SoundService();
            }
            catch (Exception ex)
            {
                SaveErrLogHelper.SaveErrorLog(string.Empty, ex.ToString());
            }
        }
Exemple #20
0
        private void StartSessionCommandImpl()
        {
            ConsoleService.IsCaretVisible = true;

            ConsoleService.IsEnabled = true;
            ConsoleService.Clear();

            WriteHeaderToScreen();

            SerialPortService.DataReceived += SerialPortService_DataReceived;

            SerialPortService.Open();

            StartBackgroundTask();

            IsRunning = true;

            if (Started != null)
            {
                Started(this, new EventArgs());
            }
        }
        public MainWindow()
        {
            InitializeComponent();

            // Initialize COM Port GUI options and add handler for COM Port changes
            cbPorts.ItemsSource             = SerialPortService.GetAvailableSerialPorts();
            SerialPortService.PortsChanged += (sender, eventArgs) => {
                cbPorts.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
                    cbPorts.ItemsSource = SerialPortService.GetAvailableSerialPorts();
                }));
            };

            _COMPort.DataReceived += COMPortDataReceived;

            _controller.Connected += (sender, eventArgs) => {
                btnConnectController.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
                    btnConnectController.Content = $"Disconnect";
                    Controller.Text = $"Controller {_controller.UserIndex}";
                    Controller.Background = Brushes.GreenYellow;
                }));
            };

            _controller.ConnectedFailed += (sender, eventArgs) => {
                MessageBox.Show("Could not connect to controller!");
            };

            _controller.Disconnected += (sender, eventArgs) => {
                btnConnectController.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
                    btnConnectController.Content = "Connect";
                    Controller.Text = "Not Connected";
                    Controller.Background = Brushes.Red;
                }));
                MessageBox.Show("The controller has been disconnected!");
            };

            // Add handler to call closed function upon program exit
            Closed += new EventHandler(OnMainWindowClosed);
        }
        private async Task PasteAndSendLinesCommandImpl()
        {
            try
            {
                if (ConsoleService.IsEnabled)
                {
                    string text = ClipboardService.GetText();

                    var lines = Regex.Split(text, $"(?={SettingsService.NewLine})");
                    if (lines.Length > 1)
                    {
                        foreach (var line in lines)
                        {
                            if (!Session.IsRunning)
                            {
                                // The session has ended break the loop.
                                break;
                            }

                            int index = ConsoleService.SelectionStart;
                            await ConsoleService.InsertText(index, line);

                            SerialPortService.Write(line);

                            if (SettingsService.LinePushDelay > 0)
                            {
                                await TaskHelpers.Delay(SettingsService.LinePushDelay);
                            }
                        }
                    }
                }
            }
            catch (ArgumentException e)
            {
                await DialogService.ShowErrorDialogAsync(e.Message, "Exception");
            }
        }
 public MainWindow()
 {
     AvailableSerialPorts = SerialPortService.GetSerialPorts();
     InitializeComponent();
     DataContext = this;
 }
Exemple #24
0
 public static bool isCollect()
 {
     LoadSystemSetting();
     return(SerialPortService.isCollect());
 }
Exemple #25
0
        public void Initialize()
        {
            SerialPorts = SerialPortService.GetPortNames();
            if (SettingsService.PortName == null)
            {
                SerialPort = SerialPorts.FirstOrDefault();
            }
            else
            {
                SerialPort = SettingsService.PortName;
            }

            DataBitsItems = new[]
            {
                5, 6, 7, 8
            };
            DataBits = SettingsService.DataBits;

            BaudRateItems = new[]
            {
                9600,
                19200,
                38400,
                57600,
                115200,
                230400,
                460800,
                921600
            };
            BaudRate = SettingsService.BaudRate;

            ParityItems = (Parity[])Enum.GetValues(typeof(Parity));
            Parity      = SettingsService.Parity;

            StopBitsItems = ((StopBits[])Enum.GetValues(typeof(StopBits))).Skip(1);
            StopBits      = SettingsService.StopBits;

            HandshakesItems = (Handshake[])Enum.GetValues(typeof(Handshake));
            Handshake       = SettingsService.Handshake;

            DtrEnabled = SettingsService.DtrEnable;
            RtsEnabled = SettingsService.RtsEnable;

            Encodings = new[]
            {
                "ASCII",
                "UTF-8",
                "Unicode",
                "BigEndianUnicode"
            };
            Encoding = SettingsService.Encoding;

            OutputFormatList = (Format[])Enum.GetValues(typeof(Format));
            OutputFormat     = SettingsService.OutputFormat;

            IntputFormatList = (Format[])Enum.GetValues(typeof(Format));
            InputFormat      = SettingsService.InputFormat;

            PrintInputToScreen = SettingsService.PrintInput;

            LinePushDelay = SettingsService.LinePushDelay;

            NewLine = Regex.Escape(SettingsService.NewLine);
        }
Exemple #26
0
 public static byte[] DoloadBoard(byte[] data)
 {
     return(SerialPortService.DoloadBoard(data));
 }
Exemple #27
0
        public void DeviceInit()
        {
            DevicePluginName = "DeviceCfg";

            // Device Discovery
            connected = false;

            // Create Device info object
            DeviceInformation = new DeviceInformation();

            try
            {
                // Initialize Device
                device = HidDevices.Enumerate(Device_IDTech.IDTechVendorID).FirstOrDefault();

                if (device != null)
                {
                    // Get Capabilities
                    Debug.WriteLine("");
                    Debug.WriteLine("device capabilities ----------------------------------------------------------------");
                    Debug.WriteLine("  Usage                          : " + Convert.ToString(device.Capabilities.Usage, 16));
                    Debug.WriteLine("  Usage Page                     : " + Convert.ToString(device.Capabilities.UsagePage, 16));
                    Debug.WriteLine("  Input Report Byte Length       : " + device.Capabilities.InputReportByteLength);
                    Debug.WriteLine("  Output Report Byte Length      : " + device.Capabilities.OutputReportByteLength);
                    Debug.WriteLine("  Feature Report Byte Length     : " + device.Capabilities.FeatureReportByteLength);
                    Debug.WriteLine("  Number of Link Collection Nodes: " + device.Capabilities.NumberLinkCollectionNodes);
                    Debug.WriteLine("  Number of Input Button Caps    : " + device.Capabilities.NumberInputButtonCaps);
                    Debug.WriteLine("  Number of Input Value Caps     : " + device.Capabilities.NumberInputValueCaps);
                    Debug.WriteLine("  Number of Input Data Indices   : " + device.Capabilities.NumberInputDataIndices);
                    Debug.WriteLine("  Number of Output Button Caps   : " + device.Capabilities.NumberOutputButtonCaps);
                    Debug.WriteLine("  Number of Output Value Caps    : " + device.Capabilities.NumberOutputValueCaps);
                    Debug.WriteLine("  Number of Output Data Indices  : " + device.Capabilities.NumberOutputDataIndices);
                    Debug.WriteLine("  Number of Feature Button Caps  : " + device.Capabilities.NumberFeatureButtonCaps);
                    Debug.WriteLine("  Number of Feature Value Caps   : " + device.Capabilities.NumberFeatureValueCaps);
                    Debug.WriteLine("  Number of Feature Data Indices : " + device.Capabilities.NumberFeatureDataIndices);

                    // Using the device notifier to detect device removed event
                    device.Removed        += DeviceRemovedHandler;
                    Device.OnNotification += OnNotification;

                    Device.Init(SerialPortService.GetAvailablePorts(), ref DeviceInformation.deviceMode);

                    // Notify Main Form
                    SetDeviceMode(DeviceInformation.deviceMode);

                    if (DeviceInformation.emvConfigSupported)
                    {
                        // Initialize Universal SDK
                        IDT_Device.setCallback(MessageCallBack);
                        //IDT_Device.setCallbackIP(MessageCallBackIP);
                        IDT_Device.startUSBMonitoring();
                        Debug.WriteLine("DeviceCfg::DeviceInit(): - device TYPE={0}", IDT_Device.getDeviceType());

                        NotificationRaise(new DeviceNotificationEventArgs {
                            NotificationType = NOTIFICATION_TYPE.NT_INITIALIZE_DEVICE, Message = new object[] { "COMPLETED" }
                        });
                    }
                    else
                    {
                        // connect to device
                        Device.Connect();
                    }
                    // Set as Attached
                    attached = true;
                }
                else
                {
                    throw new Exception("NoDevice");
                }
            }
            catch (Exception xcp)
            {
                throw xcp;
            }
        }
Exemple #28
0
 public TimingProcessDailyCoursesJob(IZ_CourseService CourseService, IZ_SectionTimeService SectionTimeService, SerialPortService PortService)
 {
     this.CourseService      = CourseService;
     this.SectionTimeService = SectionTimeService;
     this.PortService        = PortService;
 }
 private void OnRefresh(object sender, RoutedEventArgs e)
 {
     AvailableSerialPorts = SerialPortService.GetSerialPorts();
 }
Exemple #30
0
 public SynchronizeElectronicClockTimeJob(IZ_RoomService roomService, SerialPortService PortService)
 {
     this.roomService = roomService;
     this.PortService = PortService;
 }