private void Awake()
 {
     if (!Instance)
     {
         Instance = this;
     }
 }
示例#2
0
    void Start()
    {
        serialPortManager = SerialPortManager.Instance;
        rigidbody         = GetComponent <Rigidbody2D>();

        serialPortManager.onApplicationStop += DeactivateAllSystems;
    }
示例#3
0
        //Arun Geo Thomas
        private void btnStopOpertion_Click(object sender, EventArgs e)
        {
            if (serialPortManager != null)
            {
                Object thisLock = new Object();
                lock (thisLock)
                {
                    readSerialPortData = false;
                }

                if (serialPortManager.CloseConnection())
                {
                    JSTimer.Stop();


                    lblSerialportMessages.Text = "Disconnected";
                    cbCOMPortsSelector.Enabled = true;
                    btnStartOperation.Enabled  = true;
                    serialPortManager          = null;
                }
                else
                {
                    lblSerialportMessages.Text = "Already Disconnected";
                }
            }
            else
            {
                lblSerialportMessages.Text = "No valid connection";
            }
            ClearUI();
        }
示例#4
0
        //Arun Geo Thomas
        private void btnStartOperation_Click(object sender, EventArgs e)
        {
            if (File.Exists(logFileName))
            {
                File.Delete(logFileName);
            }

            try
            {
                serialPortManager = new SerialPortManager(cbCOMPortsSelector.SelectedItem.ToString());


                if (serialPortManager.Connect())
                {
                    lblSerialportMessages.Text = "Connected";
                    readSerialPortData         = true;
                    serialPortReadThread       = new Thread(new ThreadStart(BackendThreadExecute));
                    serialPortReadThread.Start();
                    cbCOMPortsSelector.Enabled = false;
                    btnStartOperation.Enabled  = false;
                    JSTimer.Start();
                }
                else
                {
                    lblSerialportMessages.Text = "Already Connected";
                }
            }
            catch (Exception ex)
            {
                lblSerialportMessages.Text = "Error Cant Connect: " + ex.Message;
            }
        }
示例#5
0
        public ConfirmQuantityFm(PLC plc, SerialPortManager spManager, ConfirmQuantityDTO sourceModel, bool canEditQuantity)
        {
            _sourceModel     = sourceModel;
            _plc             = plc;
            _spManager       = spManager;
            _canEditQuantity = canEditQuantity;
            _maxQuantity     = sourceModel.Quantity;

            quantityBS.DataSource = _sourceModel;

            InitializeComponent();

            articleLbl.Text       = _sourceModel.Article;
            materialLbl.Text      = _sourceModel.MaterialName;
            unitLocalNameLbl.Text = _sourceModel.UnitLocalName;
            maxQuantityLbl.Text   = _sourceModel.Quantity.ToString();

            quantityEdit.DataBindings.Add("EditValue", quantityBS, "Quantity", true, DataSourceUpdateMode.OnPropertyChanged);
            currentWeightTBox.DataBindings.Add("EditValue", quantityBS, "CurrentWeight", true, DataSourceUpdateMode.OnPropertyChanged);
            oldWeightTBox.DataBindings.Add("EditValue", quantityBS, "OldWeight", true, DataSourceUpdateMode.OnPropertyChanged);

            quantityEdit.ReadOnly = (canEditQuantity) ? false : true;

            ConditionValidationRule rule = new ConditionValidationRule();

            rule.ConditionOperator = ConditionOperator.Between;
            rule.ErrorText         = "Введенное количество превышает доступное, либо равно 0";
            rule.ErrorType         = ErrorType.Critical;
            rule.Value1            = 0.01m;
            rule.Value2            = _maxQuantity;
            confirmValidationProvider.SetValidationRule(quantityEdit, rule);

            StartTimer();
        }
示例#6
0
        /// <summary>
        /// Método que inicializa los datos de la bascula
        /// </summary>
        private void InicializarBascula()
        {
            try
            {
                spManager = new SerialPortManager();
                spManager.NewSerialDataRecieved += (spManager_NewSerialDataRecieved);

                if (spManager != null)
                {
                    spManager.StartListening(AuxConfiguracion.ObtenerConfiguracion().PuertoBascula,
                                             int.Parse(AuxConfiguracion.ObtenerConfiguracion().BasculaBaudrate),
                                             ObtenerParidad(AuxConfiguracion.ObtenerConfiguracion().BasculaParidad),
                                             int.Parse(AuxConfiguracion.ObtenerConfiguracion().BasculaDataBits),
                                             ObtenerStopBits(AuxConfiguracion.ObtenerConfiguracion().BasculaBitStop));

                    //basculaConectada = true;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                SkMessageBox.Show(Application.Current.Windows[ConstantesVista.WindowPrincipal],
                                  Properties.Resources.BasculaMateriaPrima_MsgErrorBascula,
                                  MessageBoxButton.OK, MessageImage.Warning);
            }
        }
        /// <summary>
        /// This method should be called prior to using this class
        /// </summary>
        static internal CompletionCode Init()
        {
            CompletionCode completionCode = CompletionCode.CommDevFailedToInit;

            // Clear this flag in case that CM retries to initialize
            isTerminating = false;

            // Safe mode is disabled by default when initialized
            isSafeModeEnabled = false;

            // Enforce that the update to the flag variable is visible to other threads orderly
            Thread.MemoryBarrier();

            portManagers = new PortManager[numPorts];

            for (int i = 0; i < numPorts; i++)
            {
                portManagers[i] = new SerialPortManager(i, numPriorityLevels);
                completionCode  = portManagers[i].Init();
                if (CompletionCodeChecker.Failed(completionCode) == true)
                {
                    Tracer.WriteError("Failed to initialize portManager: {0} Logical Id: {1}", i,
                                      PortManager.GetPhysicalPortNameFromLogicalId(i));
                    Release();
                    return(completionCode);
                }
            }

            return(completionCode);
        }
示例#8
0
        public override bool Run(IInTaskManager taskManager)
        {
            Mode mode = (memoryType == MemoryType.FLASH) ? Mode.ReadFlashPage : Mode.ReadEepromPage;

            var protocolTx = new ProtocolReadPageTx(serialPortSettings.HeaderTX, mode);
            var protocolRx = new ProtocolReadPageRx(serialPortSettings.HeaderRX, mode);
            var bufferTx   = new IOBufferReadPageTx();

            using (var sp = new SerialPortManager(portName, (int)serialPortSettings.BaudRate,
                                                  serialPortSettings.Parity, serialPortSettings.StopBits, 50, SerialPort.InfiniteTimeout))
            {
                for (;;)
                {
                    taskManager.IfCancellation();
                    if (IfReceived(sp, protocolTx, bufferTx, taskManager.SynchronizationContext))
                    {
                        protocolRx.PageNumber     = protocolTx.PageNumber;
                        protocolRx.PageLineNumber = protocolTx.PageLineNumber;
                        protocolRx.Line           = memory.GetPage(protocolTx.PageNumber).GetLine(protocolTx.PageLineNumber);
                        Transmit(sp, protocolRx, taskManager.SynchronizationContext);
                        RestartReceiv();
                    }
                }
            }
        }
        private void Navbar_OnConnectButtonClicked(object sender, RoutedEventArgs e)
        {
            if (_robotConnectionService == null)
            {
                var portName = _selectedPortName;

                if (string.IsNullOrEmpty(portName))
                {
                    Logger.Error("No ports found");
                    MessageBox.Show("Please select serial port first.", "Port not found");
                    return;
                }

                Logger.Info("Starting connection...");
                _mainViewModel.GuiStatusViewModel.ConnectionStatus = $"Connected to: {portName}";
                _mainViewModel.GuiStatusViewModel.IsConnected      = true;
                _serialPort        = _serialPortFactory.GetPort(portName);
                _serialPortManager = new SerialPortManager(_serialPort);
                _serialPortManager.TryOpen();
                _serialPortAdapter      = new SerialPortAdapter(_serialPort);
                _robotConnectionService = new RobotConnectionService(_serialPortAdapter);
                _robotConnectionService.SpeedCurrentFeedbackReceived       += RobotConnection_CurrentSpeedFeedbackReceived;
                _robotConnectionService.VoltageTemperatureFeedbackReceived += RobotConnection_VoltageTemperatureFeedbackReceived;
                _robotConnectionService.ParametersReceived += RobotConnection_ParametersReceived;

                _sender = new ControlsSender(_robotConnectionService, 50);

                _experimentHandler.Sender = _sender;

                RequestParameters();
            }
        }
示例#10
0
        private void UserInitialization()
        {
            _spManager = new SerialPortManager();

            SerialSettings mySerialSettings = _spManager.CurrentSerialSettings;

            //mySerialSettings.PortName = "COM1";
            //serialSettingsBindingSource.DataSource = mySerialSettings;
            //portNameComboBox.DataSource = mySerialSettings.PortNameCollection;
            //baudRateComboBox.DataSource = mySerialSettings.BaudRateCollection;
            //dataBitsComboBox.DataSource = mySerialSettings.DataBitsCollection;
            //parityComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.Parity));
            //stopBitsComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.StopBits));

            _spManager.NewSerialDataRecieved += new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved);
            FormClosing += new FormClosingEventHandler(Form_FormClosing);


            btnStart.Enabled = false;
            btnStop.Enabled  = false;
            BtnOK.Enabled    = false;

            LoadProduct("P002");
            //BtnCloseQueue.Enabled = false;
        }
示例#11
0
        // ------------------ MAIN  ----------------------

        // Setup function
        public void Setup(ControllerForm controllerForm)
        {
            // storing the controller form for later reference
            _controllerForm = controllerForm;

            // Create Serial Port object
            _serialPortManager = new SerialPortManager
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200 } // object initializer
            };

            _cmdMessenger = new CmdMessenger(_serialPortManager);

            // Tell CmdMessenger to "Invoke" commands on the thread running the WinForms UI
            _cmdMessenger.SetControlToInvokeOn(_controllerForm);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Attach to NewLineReceived for logging purposes
            _cmdMessenger.NewLineReceived += NewLineReceived;

            // Attach to NewLineSent for logging purposes
            _cmdMessenger.NewLineSent += NewLineSent;

            // Start listening
            _cmdMessenger.StartListening();

            _controllerForm.SetLedState(true);
            _controllerForm.SetFrequency(2);
        }
示例#12
0
        private void MoveAxis(char axis, bool rightOrUp)
        {
            double distance = double.Parse(txtDistance.Text);

            distance = rightOrUp ? distance : distance * -1;

            StringBuilder sb = new StringBuilder();

            switch (axis)
            {
            case 'x':
                sb = simpleMovements.MoveX(distance, feed);
                break;

            case 'y':
                sb = simpleMovements.MoveY(distance, feed);
                break;

            case 'z':
                sb = simpleMovements.MoveZ(distance, feed);
                break;
            }

            txtLog.Text = sb.ToString();
            SerialPortManager.ExecuteCommands(sb);
        }
示例#13
0
        private void SetSettings()
        {
            //Terminal
            TCP.GetSettings();
            TerminalIpTextBox.Text   = TCP.IP;
            TerminalPortTextBox.Text = TCP.Port.ToString();

            //Decoder
            SerialPortManager spm = new SerialPortManager();

            PortNameComboBox.ItemsSource = spm.CurrentSerialSettings.PortNameCollection;
            BaudRateComboBox.ItemsSource = spm.CurrentSerialSettings.BaudRateCollection;
            DataBitsComboBox.ItemsSource = spm.CurrentSerialSettings.DataBitsCollection;
            ParityComboBox.ItemsSource   = Enum.GetValues(typeof(System.IO.Ports.Parity));
            StopBitsComboBox.ItemsSource = Enum.GetValues(typeof(System.IO.Ports.StopBits));

            try
            {
                spm.CurrentSerialSettings.GetSettings();

                PortNameComboBox.SelectedValue = spm.CurrentSerialSettings.PortNameCollection.Any(x => x == spm.CurrentSerialSettings.PortName) ? spm.CurrentSerialSettings.PortName : null;
                BaudRateComboBox.SelectedValue = spm.CurrentSerialSettings.BaudRate;
                DataBitsComboBox.SelectedValue = spm.CurrentSerialSettings.DataBits;
                ParityComboBox.SelectedValue   = spm.CurrentSerialSettings.Parity;
                StopBitsComboBox.SelectedValue = spm.CurrentSerialSettings.StopBits;
            }
            catch (Exception ex)
            {
                log.Error($"[{ Settings.GetLine(new StackTrace(true))}]:Error getting the settings: {ex}");
            }
        }
示例#14
0
        private void UserInitialization()
        {
            //StreamWriter file = new StreamWriter("C:/Users/HP/Desktop/NXP/tab.csv");
            _spManager = new SerialPortManager(this);
            port1      = new SerialPortManager(this);

            count = 0;
            SerialSettings mySerialSettings = _spManager.CurrentSerialSettings;

            serialSettingsBindingSource.DataSource = mySerialSettings;
            portNameComboBox.DataSource            = mySerialSettings.PortNameCollection;
            baudRateComboBox.DataSource            = mySerialSettings.BaudRateCollection;
            dataBitsComboBox.DataSource            = mySerialSettings.DataBitsCollection;
            parityComboBox.DataSource   = Enum.GetValues(typeof(System.IO.Ports.Parity));
            stopBitsComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.StopBits));

            folderBrowserDialog1.Disposed    += new EventHandler(folderBrowserDialog1_disposed);
            _spManager.NewSerialDataRecieved += new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved);
            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);

            /*
             * //gyro
             * port1._serialPort.BaudRate = 115200;
             * port1._serialPort.PortName = "COM33";
             * port1._serialPort.Parity = System.IO.Ports.Parity.None;
             * port1._serialPort.DataBits = 8;
             * port1._serialPort.StopBits = System.IO.Ports.StopBits.One;
             *
             *
             * port1._serialPort.Open();
             */
        }
示例#15
0
 public Scales()
 {
     nxFrame     = new NxDataFrame();
     portManager = new SerialPortManager();
     checker     = new System.Threading.Timer((unused) => checkOnlineStatus(), null, System.Threading.Timeout.Infinite, (int)checkerSpan.TotalMilliseconds);
     portManager.NewSerialDataRecieved += portManager_NewSerialDataRecieved;
 }
        /// <summary>
        /// This method should be called prior to using this class
        /// </summary>
        static internal CompletionCode Init()
        {
            CompletionCode completionCode = CompletionCode.CommDevFailedToInit;

            // populdate Blade_En State Cache.
            foreach (byte Id in physicalServerIdTable)
            {
                CachedBladePowerStatus.Add(Id, new BladeEnState());
            }

            // Clear this flag in case that CM retries to initialize
            isTerminating = false;

            // Enforce that the update to the flag variable is visible to other threads orderly
            Thread.MemoryBarrier();

            portManagers = new PortManager[numPorts];

            for (int i = 0; i < numPorts; i++)
            {
                portManagers[i] = new SerialPortManager(i, numPriorityLevels);
                completionCode  = portManagers[i].Init();
                if (CompletionCodeChecker.Failed(completionCode) == true)
                {
                    Tracer.WriteError("Failed to initialize portManager: {0} Logical Id: {1}", i,
                                      PortManager.GetPhysicalPortNameFromLogicalId(i));
                    Release();
                    return(completionCode);
                }
            }

            return(completionCode);
        }
示例#17
0
        /*
         * User custom initialization.
         */
        private void UserInitialization()
        {
            // New serial port manager
            _spManager = new SerialPortManager();

            // Read current serial port settings
            SerialSettings mySerialSettings = _spManager.CurrentSerialSettings;

            // Bind serial port & user interface data sources with serial port settings
            serialSettingsBindingSource.DataSource = mySerialSettings;
            portNameComboBox.DataSource            = mySerialSettings.PortNameCollection;
            baudRateComboBox.DataSource            = mySerialSettings.BaudRateCollection;
            dataBitsComboBox.DataSource            = mySerialSettings.DataBitsCollection;
            parityComboBox.DataSource   = Enum.GetValues(typeof(System.IO.Ports.Parity));
            stopBitsComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.StopBits));

            // Add evnet handling functions to serial port manager
            _spManager.NewSerialDataRecieved += new EventHandler <SerialDataEventArgs>(_spManager_NewSerialDataRecieved);
            _spManager.ErrorHandler          += new EventHandler <EventArgs>(_spManager_ErrorHandler);

            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);

            // Diable "Disconnect" button
            btnStop.Enabled = false;

            // Add empty point to make chart visible before first sample arrived
            chart1.Series[0].Points.AddXY(double.NaN, double.NaN);
        }
示例#18
0
        public override bool Run(IInTaskManager taskManager)
        {
            var protocolTx = new ProtocolResetTx(serialPortSettings.HeaderTX);
            var protocolRx = new ProtocolResetRx(serialPortSettings.HeaderRX);
            var bufferRx   = new IOBufferResetRx();

            using (var sp = new SerialPortManager(portName, (int)serialPortSettings.BaudRate,
                                                  serialPortSettings.Parity, serialPortSettings.StopBits, 50, SerialPort.InfiniteTimeout))
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                for (;;)
                {
                    Transmit(sp, protocolTx, taskManager.SynchronizationContext);
                    RestartReceiv();
                    stopWatch.Restart();
                    while (stopWatch.Elapsed < TimeSpan.FromMilliseconds(100))
                    {
                        taskManager.IfCancellation();

                        if (IfReceived(sp, protocolRx, bufferRx, taskManager.SynchronizationContext))
                        {
                            stopWatch.Stop();
                            return(true);
                        }
                    }
                }
            }
        }
示例#19
0
        /// <summary>
        /// Método que inicializa los datos de la bascula
        /// </summary>
        private void InicializarDickeyJohn()
        {
            try
            {
                spManager = new SerialPortManager();
                spManager.NewSerialDataRecieved += (SpManagerNewSerialDataRecieved);

                if (spManager != null)
                {
                    spManager.StartListening(AuxConfiguracion.ObtenerConfiguracion().PuertoDickey,
                                             int.Parse(AuxConfiguracion.ObtenerConfiguracion().DickeyBaudrate),
                                             ObtenerParidad(AuxConfiguracion.ObtenerConfiguracion().DickeyParidad),
                                             int.Parse(AuxConfiguracion.ObtenerConfiguracion().DickeyDataBits),
                                             ObtenerStopBits(AuxConfiguracion.ObtenerConfiguracion().DickeyBitStop));
                    dudHumedad.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                dudHumedad.IsEnabled = true;
                Logger.Error(ex);
                SkMessageBox.Show(Application.Current.Windows[ConstantesVista.WindowPrincipal],
                                  Properties.Resources.CapturaHumedad_MsgErrorDickey,
                                  MessageBoxButton.OK, MessageImage.Warning);
            }
        }
示例#20
0
        public SystemInfoCtrl()
        {
            resources     = new ComponentResourceManager(typeof(SystemInfoCtrl));
            this.CtrlType = CtrlType.SystemInoCtrl;
            InitializeComponent();

            serialPortCom = SerialPortManager.GetInstance();
        }
示例#21
0
        public override bool Run(IInTaskManager <double> taskManager)
        {
            Mode mode = (memoryType == MemoryType.FLASH) ? Mode.WriteFlashPage : Mode.WriteEepromPage;

            var txProtocol = new ProtocolWritePageTx(serialPortSettings.HeaderTX, mode);
            var rxProtocol = new ProtocolWritePageRx(serialPortSettings.HeaderRX, mode);
            var bufferRx   = new IOBufferWritePageRx();

            using (var sp = new SerialPortManager(portName, (int)serialPortSettings.BaudRate,
                                                  serialPortSettings.Parity, serialPortSettings.StopBits, 50, SerialPort.InfiniteTimeout))
            {
                var nonEmptyPages = GetNonEmptyPagesWithNumber();

                Stopwatch stopWatch = new Stopwatch();
                int       pageCount = 0;
                foreach (var page in nonEmptyPages)
                {
                    for (int pageLineNumber = 0; pageLineNumber < Page.NumberOfLines; pageLineNumber++)
                    {
                        txProtocol.PageNumber     = page.Key;
                        txProtocol.PageLineNumber = pageLineNumber;
                        txProtocol.Line           = page.Value.GetLine(pageLineNumber);
                        for (;;)
                        {
                            Transmit(sp, txProtocol, taskManager.SynchronizationContext);
                            RestartReceiv();
                            stopWatch.Restart();
                            while (stopWatch.Elapsed < TimeSpan.FromMilliseconds(100))
                            {
                                taskManager.IfCancellation();
                                if (IfReceived(sp, rxProtocol, bufferRx, taskManager.SynchronizationContext))
                                {
                                    if (rxProtocol.PageNumber == page.Key)
                                    {
                                        if (rxProtocol.PageLineNumber == pageLineNumber)
                                        {
                                            goto label1;
                                        }
                                        else
                                        {
                                            RestartReceiv();
                                        }
                                    }
                                    else
                                    {
                                        RestartReceiv();
                                    }
                                }
                            }
                        }
                        label1 :;
                    }
                    taskManager.OnProgress((double)pageCount++ / (nonEmptyPages.Count - 1) * 100.00);
                }
                Thread.Sleep(1000);
                return(true);
            }
        }
示例#22
0
        private void BtnSetHome_Click(object sender, EventArgs e)
        {
            GCodeHome home  = new GCodeHome();
            string    gCode = home.SetHomePoint();

            txtLog.Text = gCode;

            SerialPortManager.ExecuteCommand(gCode);
        }
示例#23
0
        public void DataReceived(byte[] by)
        {
            PortDataParameter param = DataParsing.Parsing(by);

            OverTimeManager.Stop();
            try
            {
                if (param.Command.DCommand == PortEnums.DCommands.Default)
                {
                    if (param.DistanceDeviceParam != null && param.DistanceDeviceParam.Command == PortEnums.DistanceCommands.InitializeDevice)
                    {
                        if (param.DistanceDeviceParam.AuxiliaryCommand == PortEnums.AuxiliaryCommands.Success)
                        {
                            if (!EncryptNewDevice)
                            {
                                byte[] bys = PortAgreement.DistanceCardEncryption(NewPwd);
                                SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, bys);
                                EncryptNewDevice = true;
                                OverTimeManager.Start();
                                return;
                            }
                            else
                            {
                                ViewCallFunction.ViewEncryptMessage("定距卡加密结束。");
                                ViewCallFunction.ViewEncryptOver();
                            }
                        }
                        else
                        {
                            ViewCallFunction.ViewEncryptMessage("定距卡加密失败,请重新操作。");
                            ViewCallFunction.ViewEncryptOver();
                        }
                        EncryptNewDevice = false;
                    }
                    else if (param.DistanceCardParam != null && param.DistanceCardParam.Command == PortEnums.DistanceCommands.ModifyAllCardPwd)
                    {
                        if (param.DistanceCardParam.AuxiliaryCommand == PortEnums.AuxiliaryCommands.Success)
                        {
                            DistanceCardParameter distanceParam = param.DistanceCardParam;
                            string msg = $"定距卡:{distanceParam.CardNumber} 密码(口令)加密{(distanceParam.CardTypeParameter.CardType != PortEnums.CardTypes.PwdError ? "成功" : "失败")}";
                            ViewCallFunction.ViewEncryptMessage(msg);
                        }
                        else
                        {
                            DeviceNewPwd();
                        }
                        OverTimeManager.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                Log4Helper.ErrorInfo(ex.Message, ex);
                ViewCallFunction.ViewEncryptOver();
                ViewCallFunction.ViewAlert(ex.Message);
            }
        }
示例#24
0
 public void DataReceived(byte[] by)
 {
     try
     {
         PortDataParameter param = DataParsing.Parsing(by);
         if (param.DistanceCardParam == null)
         {
             return;
         }
         OverTimeManager.Stop();
         if (param.DistanceCardParam.Command == PortEnums.DistanceCommands.ReadACard)
         {
             if (param.DistanceCardParam.AuxiliaryCommand == PortEnums.AuxiliaryCommands.Success)
             {
                 int state = CardManager.LossLists[0].CardReportLoss;
                 by = DistanceLoss.PersonnelLoseOrRecovery(CardManager.LossLists, state == 1 ? 1 : 2);
                 bool ret = SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by);
                 if (!ret)
                 {
                     ViewCallFunction.ViewCloseLoading();
                 }
                 else
                 {
                     OverTimeManager.Start();
                 }
             }
             else
             {
                 ViewCallFunction.ViewCloseLoading();
                 ViewCallFunction.ViewMessage("未能获取到挂失卡,请重新操作。", "2");
             }
         }
         else if (param.DistanceCardParam.Command == PortEnums.DistanceCommands.WriteACard)
         {
             if (param.DistanceCardParam.AuxiliaryCommand == PortEnums.AuxiliaryCommands.Success)
             {
                 foreach (CardInfo item in CardManager.LossLists)
                 {
                     item.CardReportLoss = item.CardReportLoss == 1 ? 0 : 1;
                 }
                 CardManager.Update(CardManager.LossLists.ToArray());
                 CardManager.LossLists = null;
                 ViewCallFunction.ViewLoseOver();
             }
             else
             {
                 ViewCallFunction.ViewCloseLoading();
             }
         }
     }
     catch (Exception ex)
     {
         Log4Helper.ErrorInfo(ex.Message, ex);
         ViewCallFunction.ViewCloseLoading();
         ViewCallFunction.ViewAlert(ex.Message);
     }
 }
示例#25
0
        private void BtnHoming_Click(object sender, EventArgs e)
        {
            GCodeHome home  = new GCodeHome();
            string    gCode = home.ReturnToHome(SAFE_VERTICAL_HEIGHT_CM);

            txtLog.Text = gCode;

            SerialPortManager.ExecuteCommand(gCode);
        }
示例#26
0
        protected void Transmit(SerialPortManager sp, ProtocolBase protocol, SynchronizationContext syncContext)
        {
            var buffer = protocol.Pack();

            syncContext.Post(delegate {
                logger.Log(string.Format("Tx: {0}", buffer.ToString()), Category.Debug, Priority.None);
            }, null);
            sp.Write(protocol.Pack());
        }
示例#27
0
        public LoRaCore(string portname, int baudrate, string address)
        {
            _address = address;

            _serialPortManager = new SerialPortManager(portname, baudrate);
            _serialPortManager.DataReceived           += SerialPortManager_DataReceived;
            _serialPortManager.SerialPortErrorOccured += SerialPortManager_SerialPortErrorOccured;

            OnTransceiverConnectedEvent();
        }
示例#28
0
        async void ExecuteRefreshPorts()
        {
            ComPorts.Clear();
            await Task.Delay(1000);

            foreach (var port in SerialPortManager.GetPortsInformation())
            {
                ComPorts.Add(new SerialPort(port));
            }
        }
        protected override void SaveConfiguration(object configuration)
        {
            var serialPortConfiguration = configuration as SerialPortConfigurationCollection;

            if (serialPortConfiguration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            SerialPortManager.SaveConfiguration(serialPortConfiguration);
        }
示例#30
0
        /// <summary>
        /// Método que inicializa los datos de la bascula
        /// </summary>
        private void InicializarBascula()
        {
            try
            {
                var parametrosPL        = new ConfiguracionParametrosPL();
                var parametroSolicitado = new ConfiguracionParametrosInfo
                {
                    TipoParametro  = (int)TiposParametrosEnum.DispositivoBascula,
                    OrganizacionID = organizacionID
                };
                var parametros = parametrosPL.ParametroObtenerPorTrampaTipoParametro(parametroSolicitado,
                                                                                     trampaInfo.TrampaID);
                _configBasculaCorte = ObtenerParametroDispositivo(parametros);

                _spManager = new SerialPortManager();
                _spManager.NewSerialDataRecieved += (spManager_NewSerialDataRecieved);

                if (_spManager != null)
                {
                    _spManager.StartListening(_configBasculaCorte.Puerto,
                                              _configBasculaCorte.Baudrate,
                                              _configBasculaCorte.Paridad,
                                              _configBasculaCorte.Databits,
                                              _configBasculaCorte.BitStop);
                }
                _spManager.StopListening();
                txtPesoTara.IsEnabled  = false;
                txtPesoBruto.IsEnabled = false;
                basculaConectada       = true;
            }
            catch (UnauthorizedAccessException ex)
            {
                Logger.Error(ex);

                /*_spManager.Dispose();
                 * if (_spManager != null)
                 *  _spManager.StartListening(_configBasculaCorte.Puerto,
                 *      _configBasculaCorte.Baudrate,
                 *      _configBasculaCorte.Paridad,
                 *      _configBasculaCorte.Databits,
                 *      _configBasculaCorte.BitStop);
                 * _spManager.StopListening();
                 * txtPesoTara.IsEnabled = false;
                 * txtPesoBruto.IsEnabled = false;
                 * basculaConectada = true;*/
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                SkMessageBox.Show(Application.Current.Windows[ConstantesVista.WindowPrincipal],
                                  Properties.Resources.SalidaIndividualGanado_MensajeErrorBascula,
                                  MessageBoxButton.OK, MessageImage.Warning);
            }
        }
示例#31
0
        private void UserInitialization()
        {
            _spManager = new SerialPortManager();
            SerialSettings mySerialSettings = _spManager.CurrentSerialSettings;
            serialSettingsBindingSource.DataSource = mySerialSettings;
            portNameComboBox.DataSource = mySerialSettings.PortNameCollection;
            baudRateComboBox.DataSource = mySerialSettings.BaudRateCollection;
            dataBitsComboBox.DataSource = mySerialSettings.DataBitsCollection;
            parityComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.Parity));
            stopBitsComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.StopBits));

            _spManager.NewSerialDataRecieved += new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved);
        }
示例#32
0
文件: Receive.cs 项目: c37-cae/T-Bone
        // Setup function
        public void Setup()
        {
            _ledState = false;

            // Create Serial Port object
            _serialPortManager = new SerialPortManager();
            _serialPortManager.CurrentSerialSettings.PortName = "COM6";     // Set com port
            _serialPortManager.CurrentSerialSettings.BaudRate = 115200;     // Set baud rate
            _cmdMessenger = new CmdMessenger(_serialPortManager);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Start listening
            _cmdMessenger.StartListening();
        }
示例#33
0
 protected bool IfReceived(SerialPortManager sp, ProtocolBase protocol, IOBuffer buffer, SynchronizationContext syncContext)
 {
     byte receivedByte;
     if (sp.ReadByte(out receivedByte))
     {
         switch (step)
         {
             case 0:
                 if (receivedByte == protocol.Header)
                 {
                     step++;
                     buffer[counterOfTheReceivedBytes++] = receivedByte;
                 }
                 break;
             case 1:
                 if ((receivedByte & 0x80) == 0x80)
                     RestartReceiv();
                 else
                 {
                     buffer[counterOfTheReceivedBytes++] = receivedByte;
                     if (counterOfTheReceivedBytes == buffer.Size)
                     {
                         if (protocol.UnPack(buffer))
                         {
                             syncContext.Post(delegate
                             {
                                 logger.Log(string.Format("Rx: {0}", buffer.ToString()), Category.Debug, Priority.None);
                             }, null);
                             return true;
                         }
                         else
                             RestartReceiv();
                     }
                 }
                 break;
         }
     }
     return false;
 }
示例#34
0
        // ------------------ MAIN  ----------------------
        // Setup function
        public void Setup(ChartForm chartForm)
        {
            // getting the chart control on top of the chart form.
            _chartForm = chartForm;

            // Set up chart
            _chartForm.SetupChart();

            // Create Serial Port object
            _serialPortManager = new SerialPortManager
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200 } // object initializer
            };

            _cmdMessenger = new CmdMessenger(_serialPortManager);

            // Tell CmdMessenger to "Invoke" commands on the thread running the WinForms UI
            _cmdMessenger.SetControlToInvokeOn(chartForm);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Attach to NewLineReceived for logging purposes
            _cmdMessenger.NewLineReceived += NewLineReceived;

            // Attach to NewLineSent for logging purposes
            _cmdMessenger.NewLineSent += NewLineSent;

            // Start listening
            _cmdMessenger.StartListening();

            // Send command to start sending data
            var command = new SendCommand((int)Command.StartLogging);

            // Send command
            _cmdMessenger.SendCommand(command);
        }
示例#35
0
        // ------------------ M A I N  ----------------------
        // Setup function
        public void Setup()
        {
            // Create Serial Port object
            _serialPortManager = new SerialPortManager
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200 } // object initializer
            };
            _cmdMessenger = new CmdMessenger(_serialPortManager);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Attach to NewLineReceived for logging purposes
            _cmdMessenger.NewLineReceived += NewLineReceived;

            // Attach to NewLineSent for logging purposes
            _cmdMessenger.NewLineSent += NewLineSent;

            // Start listening
            _cmdMessenger.StartListening();
        }
 /// <summary> Constructor. </summary>
 /// <param name="communications">   The Serial port object. </param>
 /// <param name="fieldSeparator">   The field separator. </param>
 /// <param name="commandSeparator"> The command separator. </param>
 /// <param name="escapeCharacter">  The escape character. </param>
 public CmdMessenger(SerialPortManager communications, char fieldSeparator, char commandSeparator,
                     char escapeCharacter)
 {
     Init(communications, fieldSeparator, commandSeparator, escapeCharacter);
 }
 /// <summary> Constructor. </summary>
 /// <param name="communications"> The Serial port object. </param>
 /// <param name="fieldSeparator"> The field separator. </param>
 public CmdMessenger(SerialPortManager communications, char fieldSeparator)
 {
     Init(communications, fieldSeparator, ';', '/');
 }
        private char _fieldSeparator; // The field separator

        #endregion Fields

        #region Constructors

        /// <summary> Constructor. </summary>
        /// <param name="communications"> The Serial port object. </param>
        public CmdMessenger(SerialPortManager communications)
        {
            Init(communications, ',', ';', '/');
        }
        /// <summary> Initialises this object. </summary>
        /// <param name="communications">   The Serial port object. </param>
        /// <param name="fieldSeparator">   The field separator. </param>
        /// <param name="commandSeparator"> The command separator. </param>
        /// <param name="escapeCharacter">  The escape character. </param>
        private void Init(SerialPortManager communications, char fieldSeparator, char commandSeparator,
                          char escapeCharacter)
        {
            _controlToInvokeOn = null;
            _communications = communications;
            _communications = communications;
            _fieldSeparator = fieldSeparator;
            _commandSeparator = commandSeparator;
            _escapeCharacter = escapeCharacter;

            communications.EolDelimiter = _commandSeparator;
            Escaping.EscapeChars(fieldSeparator, commandSeparator, escapeCharacter);
            _callbackList = new Dictionary<int, MessengerCallbackFunction>();
            PrintLfCr = false;
            _communications.NewLineReceived += NewSerialDataReceived;
        }
        // ------------------ M A I N  ----------------------
        // Setup function
        public void Setup()
        {
            // Create Serial Port object
            _serialPortManager = new SerialPortManager
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200 } // object initializer
            };
            _cmdMessenger = new CmdMessenger(_serialPortManager);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Start listening
            _cmdMessenger.StartListening();

            _receivedPlainTextCount = 0;

            // Send command requesting a series of 100 float values send in plain text
            var commandPlainText = new SendCommand((int)Command.RequestPlainTextFloatSeries);
            commandPlainText.AddArgument(SeriesLength);
            commandPlainText.AddArgument(SeriesBase);
            // Send command
            _cmdMessenger.SendCommand(commandPlainText);

            // Now wait until all values have arrived
            while (!_receivePlainTextFloatSeriesFinished) {}

            // Send command requesting a series of 100 float values send in plain text
            var commandBinary = new SendCommand((int)Command.RequestBinaryFloatSeries);
            commandBinary.AddBinArgument((UInt16)SeriesLength);
            commandBinary.AddBinArgument(SeriesBase);
            // Send command
            _cmdMessenger.SendCommand(commandBinary);

            // Now wait until all values have arrived
            while (!_receiveBinaryFloatSeriesFinished) { }
        }
示例#41
0
 protected void Transmit(SerialPortManager sp, ProtocolBase protocol, SynchronizationContext syncContext)
 {
     var buffer = protocol.Pack();
     syncContext.Post(delegate {
         logger.Log(string.Format("Tx: {0}", buffer.ToString()), Category.Debug, Priority.None);
     }, null);
     sp.Write(protocol.Pack());
 }
示例#42
0
        // ------------------ MAIN  ----------------------
        // Setup function
        public void Setup(ControllerForm controllerForm)
        {
            // storing the controller form for later reference
            _controllerForm = controllerForm;

            // Create Serial Port object
            _serialPortManager = new SerialPortManager
            {
                CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200 } // object initializer
            };

            _cmdMessenger = new CmdMessenger(_serialPortManager);

            // Tell CmdMessenger to "Invoke" commands on the thread running the WinForms UI
            _cmdMessenger.SetControlToInvokeOn(_controllerForm);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Attach to NewLineReceived for logging purposes
            _cmdMessenger.NewLineReceived += NewLineReceived;

            // Attach to NewLineSent for logging purposes
            _cmdMessenger.NewLineSent += NewLineSent;

            // Start listening
            _cmdMessenger.StartListening();

            _controllerForm.SetLedState(true);
            _controllerForm.SetFrequency(2);
        }
示例#43
0
        // Setup function
        public void Setup()
        {
            _ledState = false;

            // Create Serial Port object
            _serialPortManager = new SerialPortManager
                {
                    CurrentSerialSettings = {PortName = "COM6", BaudRate = 115200} // object initializer
                };
            _cmdMessenger = new CmdMessenger(_serialPortManager);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Start listening
            _cmdMessenger.StartListening();
        }
示例#44
0
文件: Form1.cs 项目: kicasta/Libelium
        private void UserInitialization()
        {
            interpreter = new Interpreter();
            sw1 = new StreamWriter("readings.out");
            sw2 = new StreamWriter("formatReadings.out");
            sw3 = new StreamWriter("exceptionLog.out");
            spManager = new SerialPortManager();
            SerialSettings mySerialSettings = spManager.CurrentSerialSettings;
            serialSettingsBindingSource.DataSource = mySerialSettings;
            portName.DataSource = mySerialSettings.PortNameCollection;
            baudRate.DataSource = mySerialSettings.BaudRateCollection;

            spManager.NewSerialDataRecieved += new EventHandler<SerialDataEventArgs>(spManager_NewSerialDataRecieved);
            this.FormClosing += new FormClosingEventHandler(WaspGUI_FormClosing);
        }