コード例 #1
0
 /// <summary>
 /// 分析数据
 /// </summary>
 /// <param name="lst_Items"></param>
 /// <param name="data"></param>
 private void Analysis(byte[] data)
 {
     try
     {
         if (data != null && data.Length > 0)
         {
             buffer.AddRange(data);
         }
         int start = buffer.IndexOf(2);
         int end   = buffer.IndexOf(3);
         if (start == -1 || end == -1)
         {
             return;
         }
         start += 1;
         SerialPortConfig serialPortConfig = nx700config.SerialPortConfig;
         string           str = System.Text.Encoding.GetEncoding(serialPortConfig.EncodingName).GetString(buffer.ToArray(), start, end - start);
         buffer.RemoveRange(0, end + 1);
         log.Write("接收到数据:" + str);
         Paser(str);
         Analysis(null);
     }
     catch (Exception ex)
     {
         log.Write("分析数据出错:" + ex.StackTrace, "", LogType.Error);
     }
 }
コード例 #2
0
ファイル: Module.cs プロジェクト: starry-au/vixen-modules
        public override bool Setup()
        {
            using (var portConfig = new SerialPortConfig(this._serialPort))
            {
                if (portConfig.ShowDialog() == DialogResult.OK)
                {
                    this._serialPort = portConfig.SelectedPort;
                    if (_serialPort != null)
                    {
                        this._serialPort.Handshake = Handshake.None;
                        this._serialPort.Encoding  = Encoding.UTF8;

                        // Write back to setup
                        var data = GetModuleData();
                        data.PortName = _serialPort.PortName;
                        data.BaudRate = _serialPort.BaudRate;
                        data.Partity  = _serialPort.Parity;
                        data.DataBits = _serialPort.DataBits;
                        data.StopBits = _serialPort.StopBits;
                        return(true);
                    }
                }

                return(false);
            }
        }
コード例 #3
0
        public static void Init(SerialPortConfig portCfg, RunConfig runConfig)
        {
            Logger.Info("+");

            _serialPort = new SerialPortWraper(portCfg);

            _runConfig = runConfig;

            _unitDictionary = new Dictionary <int, UnitMonitor>();
            foreach (var a in runConfig.UnitAddrs)
            {
                _unitDictionary.Add(a, new UnitMonitor((byte)a, _serialPort, _runConfig));
            }

            foreach (var m in _unitDictionary.Values)
            {
                m.LoadUnitConfigFromFile(m.Address, _runConfig.DataFilePath);
            }

            Logger.Info("unit count: " + _unitDictionary.Count);

            Logger.Info($"Open port {_serialPort.PortName} baud rate: {_serialPort.BaudRate}");

            OpenPort();

            Logger.Info($"Port open: {_serialPort.IsOpen}");
        }
コード例 #4
0
        /// <summary>
        /// 初始化桥接功能
        /// </summary>
        public static bool InitializeBridge()
        {
            bool connected = false;

            try
            {
                string iniFilePath = Application.StartupPath + SqlConfiguration.INI_CFG_PATH;
                //生产环境连接配置
                IWriteSQLConfigValue cfgNormal = new INIFileWriter(iniFilePath);
                //串口设置
                SerialPortConfig.IniFile = iniFilePath;
                SerialPortConfig.Read();
                //设置配置信息
                SqlConfiguration.SetSQLConfig(cfgNormal);
                connected = SqlConfiguration.TestConnection(true);    //测试AdoDirect连接

                PubConstant.SqliteConnstr = "Data Source=" + Application.StartupPath + @"\db\HookData.db";
            }

            catch (Exception ex)
            {
                Msg.ShowException(ex);
            }

            //测试桥接是否成功
            if (false == connected)
            {
                Msg.Warning(TEST_BRIDGE_FAILED);
            }

            return(connected);
        }
コード例 #5
0
 public SerialSourceHandler(string id, string port, int baudRate)
     : base(id)
 {
     _config          = new SerialPortConfig();
     _config.Port     = port;
     _config.BaudRate = baudRate;
 }
コード例 #6
0
ファイル: SeriaProtocol.cs プロジェクト: liyahui520/LIS
 private void communication_RecevieResultEvent(byte[] data)
 {
     try
     {
         if (data != null && data.Length > 0)
         {
             buffer.AddRange(data);
         }
         int start = buffer.IndexOf(2);
         int end   = buffer.IndexOf(3);
         if (start == -1 || end == -1)
         {
             return;
         }
         start += 1;
         SerialPortConfig serialPortConfig = ff6450config.SerialPortConfig;
         string           str = Encoding.GetEncoding(serialPortConfig.EncodingName).GetString(buffer.ToArray(), start, end - start);
         buffer.RemoveRange(0, end + 1);
         log.Write("接收到数据:" + str);
         Result result = Paser(str);
         ff6450.ResultComplete(result);
         communication_RecevieResultEvent(null);
     }
     catch (Exception ex)
     {
         log.Write("分析数据出错:" + ex.Message + "\r\n" + ex.StackTrace, "", LogType.Error);
     }
 }
コード例 #7
0
 /// <summary>
 /// Update own attributes by configuration passed as methods parameter.
 /// </summary>
 /// <param name="spc">Original configuration to update by.</param>
 public virtual void Update(SerialPortConfig parent)
 {
     Port     = parent.Port;
     BaudRate = parent.BaudRate;
     Parity   = parent.Parity;
     DataBits = parent.DataBits;
     StopBits = parent.StopBits;
 }
コード例 #8
0
        private void Button_Cancel_MouseClick(object sender, MouseEventArgs e)
        {
            double r_2 = Math.Pow(e.Location.X - 40, 2.0) + Math.Pow(e.Location.Y - 40, 2.0);

            if (r_2 < 580)
            {
                selectedConfig = originalConfig;
                Close();
            }
        }
コード例 #9
0
        public void DiscoveryTest()
        {
            List <SerialPortConfigParameters> serialPortConfigParameterses = new List <SerialPortConfigParameters>();
            var cfg1 = new SerialPortConfig(_connString1);
            var cfg2 = new SerialPortConfig(_connString2);


            DiscoverSerialConnections disc = new DiscoverSerialConnections(cfg1.GetConnectionObject(), "TestTitle", "TestMessage");
            var conf = disc.Run();
        }
コード例 #10
0
        public static void SaveUserConfig(ZedGraghUtils des, ZedGraghUtils tem,
                                          ZedGraghUtils drg, SerialPortConfig ser)
        {
            //try
            //{
            if (Directory.Exists(savePath) == false)
            {
                Directory.CreateDirectory(savePath);
            }
            FileStream   fs = new FileStream(savePath + userConfigFileName, FileMode.Create);
            BinaryWriter w  = new BinaryWriter(fs);

            w.Write(des.YMax);
            w.Write(des.YMin);
            w.Write(des.DataUp);
            w.Write(des.DataDown);

            w.Write(tem.YMax);
            w.Write(tem.YMin);
            w.Write(tem.DataUp);
            w.Write(tem.DataDown);

            w.Write(ser.BaudRateIndex);
            w.Write(ser.StopBitsIndex);
            w.Write(ser.DataBitsIndex);
            w.Write(ser.ParityIndex);
            w.Write(ser.BiaoAddressValue);

            w.Write(ser.ProLinkPath);

            w.Write(ser.DesValueAddress);
            w.Write(ser.TemValueAddress);

            w.Write(ser.K0Value);
            w.Write(ser.K1Value);
            w.Write(ser.K2Value);

            w.Write(ser.ProtocolIndex);
            w.Write(ser.DesUnitsSelectIndex);
            w.Write(ser.TemUnitsSelectIndex);

            w.Write(drg.YMax);
            w.Write(drg.YMin);
            w.Write(drg.DataUp);
            w.Write(drg.DataDown);

            w.Flush();
            w.Close();
            fs.Close();
            //}
            //catch (Exception es)
            //{
            //    throw (es);
            //}
        }
コード例 #11
0
 public UnitTestPlantMonitor()
 {
     _portCfg = new SerialPortConfig()
     {
         Port          = "COM3",
         BaudRate      = 19200,
         Parity        = System.IO.Ports.Parity.None,
         DataBits      = 8,
         StopBits      = System.IO.Ports.StopBits.One,
         ReceiveLength = 11
     };
 }
コード例 #12
0
        public SerialPortConfig GetSerialPortConfig()
        {
            SerialPortConfig config = new SerialPortConfig();

            config.PortName     = comboBoxComs.SelectedValue.ToString();
            config.Baud         = Convert.ToInt32(comboBoxBaud.SelectedValue);
            config.Parity       = (Parity)comboBoxParity.SelectedItem;
            config.StopBits     = (StopBits)comboBoxStopBits.SelectedItem;
            config.EncodingName = comboBoxEncodeing.SelectedValue.ToString();
            config.DataBits     = int.Parse(this.textBoxDataBits.Text);
            return(config);
        }
コード例 #13
0
        public SerialPortStream Reset(SerialPortStream serialPort, SerialPortConfig config)
        {
            Logger?.Trace("Toggling DTR/RTS...");

            serialPort.DtrEnable = Invert;
            serialPort.RtsEnable = Invert;

            Thread.Sleep(Wait1);

            serialPort.DtrEnable = !Invert;
            serialPort.RtsEnable = !Invert;

            Thread.Sleep(Wait2);

            return(serialPort);
        }
コード例 #14
0
        public SerialPortStream Reset(SerialPortStream serialPort, SerialPortConfig config)
        {
            const int timeoutVirtualPortDiscovery  = 10000;
            const int virtualPortDiscoveryInterval = 100;

            Logger?.Info("Issuing forced 1200bps reset...");
            string currentPortName = serialPort.PortName;

            string[] originalPorts = SerialPortStream.GetPortNames();

            // Close port ...
            serialPort.Close();

            // And now open port at 1200 bps
            serialPort = new SerialPortStream(currentPortName, 1200)
            {
                Handshake = Handshake.DtrRts
            };
            serialPort.Open();

            // Close and wait for a new virtual COM port to appear ...
            serialPort.Close();

            string newPort = WaitHelper.WaitFor(
                timeoutVirtualPortDiscovery, virtualPortDiscoveryInterval,
                () => SerialPortStream.GetPortNames().Except(originalPorts).SingleOrDefault(),
                (i, item, interval) =>
                item == null
                        ? $"T+{i * interval} - Port not found"
                        : $"T+{i * interval} - Port found: {item}"
                );

            if (newPort == null)
            {
                throw new ArduinoUploaderException($"No (unambiguous) virtual COM port detected (after {timeoutVirtualPortDiscovery}ms).");
            }

            return(new SerialPortStream {
                BaudRate = config.BaudRate,
                PortName = newPort,
                DataBits = 8,
                Parity = Parity.None,
                StopBits = StopBits.One,
                Handshake = Handshake.DtrRts
            });
        }
        public SerialPortStream Reset(SerialPortStream serialPort, SerialPortConfig config)
        {
            if (config.DTRPin.HasValue)
            {
                if (this.Controller == null)
                {
                    this.Controller = new GpioController(PinNumberingScheme.Board);
                    this.Controller.OpenPin(config.DTRPin.Value, PinMode.Output);
                }

                this.Controller.Write(config.DTRPin.Value, PinValue.High);
                System.Threading.Thread.Sleep(32);
                this.Controller.Write(config.DTRPin.Value, PinValue.Low);
            }

            serialPort.DtrEnable = Toggle;
            return(serialPort);
        }
コード例 #16
0
ファイル: PscModule.cs プロジェクト: starry-au/vixen-modules
 public override bool Setup()
 {
     using (SerialPortConfig serialPortConfig = new SerialPortConfig(_port, allowBaudEdit: false)) {
         if (serialPortConfig.ShowDialog() == DialogResult.OK)
         {
             SerialPort port = serialPortConfig.SelectedPort;
             if (port != null)
             {
                 _data.PortName = port.PortName;
                 _data.BaudRate = port.BaudRate;
                 _data.DataBits = port.DataBits;
                 _data.Parity   = port.Parity;
                 _data.StopBits = port.StopBits;
                 _UpdateFromData();
                 return(true);
             }
         }
     }
     return(false);
 }
コード例 #17
0
ファイル: SeriaProtocol.cs プロジェクト: liyahui520/LIS
 public bool Start()
 {
     if (Serial == null)
     {
         SerialPortConfig serialPortConfig = bc2800Config.SerialPortConfig;
         Serial          = new MySerialPort(serialPortConfig.PortName, serialPortConfig.Baud, serialPortConfig.Parity, serialPortConfig.DataBits, serialPortConfig.StopBits);
         Serial.Encoding = Encoding.GetEncoding(serialPortConfig.EncodingName);
         Serial.SerialDataReceivedCompleteEventHandler += Serial_SerialDataReceivedCompleteEventHandler;
         Serial.DtrEnable = true;
         Serial.RtsEnable = true;
     }
     if (!Serial.IsOpen)
     {
         if (!Serial.Open())
         {
             this.Error = Serial.Erroe;
             return(false);
         }
     }
     return(true);
 }
コード例 #18
0
ファイル: SlevyrController.cs プロジェクト: marsikv/slevyr
        static SlevyrController()
        {
            Logger.Info("+");

            var unitAddrs = Settings.Default.UnitAddrs.Split(';').Select(int.Parse);

            RunConfig = new RunConfig
            {
                IsMockupMode       = Settings.Default.MockupMode,
                IsRefreshTimerOn   = Settings.Default.IsRefreshTimerOn,
                IsReadOkNgTime     = Settings.Default.IsReadOkNgTime,
                RefreshTimerPeriod = Settings.Default.RefreshTimerPeriod,
                WorkerSleepPeriod  = Settings.Default.WorkerSleepPeriod,
                RelaxTime          = Settings.Default.RelaxTime,
                ReadResultTimeOut  = Settings.Default.ReadResultTimeOut,
                SendCommandTimeOut = Settings.Default.SendCommandTimeOut,
                DataFilePath       = Settings.Default.JsonFilePath,
                UnitAddrs          = unitAddrs,
                IsWriteEmptyToLog  = Settings.Default.IsWriteEmptyToLog
            };

            PortConfig = new SerialPortConfig
            {
                Port          = Settings.Default.Port,
                BaudRate      = Settings.Default.BaudRate,
                Parity        = System.IO.Ports.Parity.None,
                DataBits      = 8,
                StopBits      = System.IO.Ports.StopBits.One,
                ReceiveLength = 11
            };

            SlevyrService.Init(PortConfig, RunConfig);

            Logger.Info("unit count: " + SlevyrService.UnitCount);

            if (RunConfig.IsRefreshTimerOn)
            {
                SlevyrService.StartWorker();
            }
        }
コード例 #19
0
ファイル: SafeSerialPort.cs プロジェクト: urish/M3D
    public SafeSerialPort(SerialPortConfig portConfig, object portThreadSync)
    {
        this.portThreadSync = portThreadSync;
        lock (portThreadSync)
        {
            lock (threadsync)
            {
                if (portConfig == null)
                {
                    throw new ArgumentNullException(nameof(portConfig));
                }

                _port = new SerialPort(portConfig.Name, portConfig.BaudRate, portConfig.Parity, portConfig.DataBits, portConfig.StopBits)
                {
                    RtsEnable    = portConfig.RtsEnable,
                    DtrEnable    = portConfig.DtrEnable,
                    ReadTimeout  = 5000,
                    WriteTimeout = 5000
                };
            }
        }
    }
コード例 #20
0
        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            SerialPortConfig.ServicePort = ServicePortTB.Text;
            SerialPortConfig.ZigBeeId    = ZigBeeIdTB.Text;
            if (PortNameCB.SelectedIndex != -1)
            {
                SerialPortConfig.PortName = PortNameCB.SelectedItem.ToString();
            }
            SerialPortConfig.PortBaudRate  = int.Parse(BaudRateTB.Text);
            SerialPortConfig.PortParity    = (Parity)Enum.Parse(typeof(Parity), ParityCB.SelectedItem.ToString(), true);
            SerialPortConfig.DataBits      = int.Parse(DataBitsTB.Text);
            SerialPortConfig.PortHandshake = (Handshake)Enum.Parse(typeof(Handshake), HandshakeCB.SelectedItem.ToString(), true);
            SerialPortConfig.PortStopBits  = (StopBits)Enum.Parse(typeof(StopBits), StopBitsCB.SelectedItem.ToString(), true);
            SerialPortConfig.ReadTimeout   = int.Parse(ReadTimeoutTB.Text);
            SerialPortConfig.WriteTimeout  = int.Parse(WriteTimeoutTB.Text);
            SerialPortConfig.Save();

            MessageBox.Show("设置成功,服务将自动重启....");
            System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
            Application.Current.Shutdown();
            // App.Current.Shutdown();
        }
コード例 #21
0
        public Form_SerialPortSetting(SerialPortConfig initialConfig = new SerialPortConfig())
        {
            InitializeComponent();

            Button_Accept.BackgroundImage = ImageList_Main.Images["Button_Circle.png"];
            Button_Cancel.BackgroundImage = ImageList_Main.Images["Button_Cross.png"];
            Button_Accept.Tag             = 0;
            Button_Cancel.Tag             = 0;

            selectedConfig = initialConfig;
            originalConfig = initialConfig;

            RefreshSerialPortList();

            if (serialPortList.Length == 0)
            {
                ComboBox_SerialPortList.Items.Add("刷新");
            }
            ComboBox_BaudRate.SelectedIndex = initialConfig.BaudRateIndex;
            ComboBox_DataBits.SelectedIndex = initialConfig.DataBitsIndex;
            ComboBox_StopBits.SelectedIndex = (int)initialConfig.StopBits;
            ComboBox_Parity.SelectedIndex   = (int)initialConfig.Parity;
        }
コード例 #22
0
ファイル: MainForm.cs プロジェクト: rokez98/TOKS
        private void OpenSerialPort()
        {
            var serialPortConfig = new SerialPortConfig()
            {
                RecieverPortName = (string)recieverPortComboBox.SelectedItem,
                SenderPortName   = (string)senderPortComboBox.SelectedItem,
                PortId           = Convert.ToByte(SenderAddress.Value),
                BaudRate         = (EBaudRate)baudrateComboBox.SelectedItem,
                Parity           = (Parity)parityComboBox.SelectedItem,
                DataBits         = (EDataBits)dataBitsComboBox.SelectedItem,
                StopBits         = (StopBits)stopBitsComboBox.SelectedItem,
                IsMonitorStation = isMonitorStationCheckBox.Checked
            };

            try
            {
                _serialPortCommunicator.Open(serialPortConfig, OnMessageRecieved, OnErrorRecieved);
            }
            catch (Exception ex)
            {
                ShowErrorBox($"Cannot open selected port with selected configuration: {ex.Message}");
                CloseSerialPort();
            }
        }
コード例 #23
0
 public Stk500V2BootloaderProgrammer(SerialPortConfig serialPortConfig, IMcu mcu)
     : base(serialPortConfig, mcu)
 {
 }
コード例 #24
0
ファイル: serialportio.cs プロジェクト: alexrigin/HMS2
    public SerialPortIo(SerialPortConfig portConfig)
    {
        if (portConfig == null) throw new ArgumentNullException("portConfig");

        // http://zachsaw.blogspot.com/2010/07/net-serialport-woes.html
        SerialPortFixer.Execute(portConfig.Name);

        var port = new SerialPort(
            portConfig.Name,
            portConfig.BaudRate,
            portConfig.Parity,
            portConfig.DataBits,
            portConfig.StopBits)
        {
            RtsEnable = portConfig.RtsEnable,
            DtrEnable = portConfig.DtrEnable,
            ReadTimeout = 5000,
            WriteTimeout = 5000
        };
        port.Open();

        try
        {
            this._internalSerialStream = port.BaseStream;
            this._port = port;
            this._port.DiscardInBuffer();
            this._port.DiscardOutBuffer();
        }
        catch (Exception ex)
        {
            Stream internalStream = this._internalSerialStream;

            if (internalStream == null)
            {

                FieldInfo field = typeof(SerialPort).GetField(
                    "internalSerialStream",
                    BindingFlags.Instance | BindingFlags.NonPublic);

                // This will happen if the SerialPort class is changed
                // in future versions of the .NET Framework
                if (field == null)
                {
                    //.Log.WarnFormat(
                    //    "An exception occured while creating the serial port adaptor, "
                    //    + "the internal stream reference was not acquired and we were unable "
                    //    + "to get it using reflection. The serial port may not be accessible "
                    //    + "any further until the serial port object finalizer has been run: {0}",
                    //    ex);

                    throw;
                }

                internalStream = (Stream)field.GetValue(port);
            }

            //this.Log.DebugFormat(
            //    "An error occurred while constructing the serial port adaptor: {0}", ex);

            SafeDisconnect(port, internalStream);
            throw;
        }
    }
コード例 #25
0
        public void GetDiscoverySendCommandTest()
        {
            var cfg = new SerialPortConfig(_connString1);

            cfg.GetDiscoverySendCommand().Should().Be("*IDN?");
        }
コード例 #26
0
        public void GetDiscoveryReadMatchTest()
        {
            var cfg = new SerialPortConfig(_connString1);

            cfg.GetDiscoveryReadMatch().Should().Be("RND 320-KD3005P");
        }
コード例 #27
0
        public void GetNewLineTest()
        {
            var cfg = new SerialPortConfig(_connString1);

            cfg.GetNewLine().Should().Be("\n");
        }
コード例 #28
0
        public void GetHandshakeTest()
        {
            var cfg = new SerialPortConfig(_connString2);

            cfg.GetHandshake().Should().Be(Handshake.None);
        }
コード例 #29
0
        public void GetDataBitsTest()
        {
            var cfg = new SerialPortConfig(_connString2);

            cfg.GetDataBits().Should().Be(8);
        }
コード例 #30
0
 public Form_SerialConfig(SerialPortConfig pSerrialPortConfig)
 {
     InitializeComponent();
     mSerialPortConfig = pSerrialPortConfig;
     buttonConnect.Focus();
 }
コード例 #31
0
        public void GetStopBitsTest()
        {
            var cfg = new SerialPortConfig(_connString2);

            cfg.GetStopBits().Should().Be(StopBits.One);
        }