static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                MessageBox.Show("usage: generator_ad9833 [port_name]", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            CommPort p;

            p = new CommPort(args[0], string.Empty);
            try
            {
                p.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Comm port opening error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm(p));
        }
Exemple #2
0
        static void Main(string[] args)
        {
            string program_file = null;

            if (args.Length < 1 || args.Length > 2)
            {
                MessageBox.Show("usage: oven_control port_name [program_file]", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (args.Length == 2)
            {
                program_file = args[1];
            }

            CommPort p;

            p = new CommPort(args[0], string.Empty);
            try
            {
                p.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Comm port opening error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm(p, program_file));
        }
Exemple #3
0
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            try
            {
                Settings.Port.PortName  = comboBoxPortName.Text;
                Settings.Port.BaudRate  = Int32.Parse(comboBoxBaudRate.Text);
                Settings.Port.DataBits  = comboBoxDataBits.SelectedIndex + 5;
                Settings.Port.Parity    = (Parity)comboBoxParity.SelectedIndex;
                Settings.Port.StopBits  = (StopBits)comboBoxStopBits.SelectedIndex;
                Settings.Port.Handshake = (Handshake)comboBoxHandshake.SelectedIndex;
                CommPort com = CommPort.Instance;
                com.Open();


                if (com.IsOpen)
                {
                    MessageBox.Show("串口COM打开成功", "提示");
                }
                Settings.Write();

                buttonOpen.Enabled        = false;
                comboBoxPortName.Enabled  = false;
                comboBoxBaudRate.Enabled  = false;
                comboBoxDataBits.Enabled  = false;
                comboBoxParity.Enabled    = false;
                comboBoxStopBits.Enabled  = false;
                comboBoxHandshake.Enabled = false;
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message, "Error");
                return;
            }
            //Close();
        }
        // create port -- start recv thread if we're not bit bang only
        public int Create(bool bit_bang_only)
        {
            bitBangOnly = bit_bang_only;
            if (isOpen)
            {
                return(-1);
            }
            commPort.Open();              // fixMe -- error check
            isOpen = true;

            if (!bit_bang_only)
            {
                // start receive thread
                recvThread              = new Thread(new ThreadStart(RecvThread));
                recvThread.Name         = "SDRSerialSupport.recvThread.COM" + commPort.PortNum;
                recvThread.IsBackground = true;
                recvThread.Start();

                // and the xmit thread
//				xmitThread = new Thread(new ThreadStart(XmitThread));
//				xmitThread.Name = "SDRSerialSupport.xmitThread.COM" + commPort.PortNum;
//				xmitThread.IsBackground = true;
//				xmitThread.Start();
            }
            return(0);            // all is well
        }
Exemple #5
0
 /// <summary>
 /// 开启串口封装的方法
 /// </summary>
 private void OpenPort()
 {
     //从配置文件获得当前串口配置
     if (_commPort.Opened)
     {
         _commPort.Close();
     }
     _commPort.GetCommPortSet("commportSet");
     //打开串口
     try
     {
         _commPort.Open();
         if (_commPort.Opened)
         {
             Tools.FormBottomPortStatus = true;
         }
         else
         {
             Tools.FormBottomPortStatus = false;
         }
     }
     catch
     {
         _tools.PrompMessage(1);
     }
 }
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args.Length != 1)
            {
                MessageBox.Show("usage: gen_freq_meter_level_meter [port_name]", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(1);
                return;
            }

            if (!"NODEVICE".Equals(e.Args[0]))
            {
                string answer;

                try
                {
                    p              = new CommPort(e.Args[0], string.Empty);
                    p.ReadTimeout  = 300;
                    p.WriteTimeout = 300;
                    p.Open();
                    p.Write("I");
                    Thread.Sleep(100);
                    answer = p.ReadExisting();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Comm port openning error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Shutdown(2);
                    return;
                }

                if (answer != "GNFMLM10")
                {
                    MessageBox.Show("Wrong device answer to identify command: " + (answer == null ? string.Empty : answer), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Shutdown(3);
                    return;
                }

                nextCommands = new Queue <DeviceCommand>();
            }
            else
            {
                nextCommands = null;
            }

            settings = new Dictionary <string, string>();
            if (File.Exists(settingsFile))
            {
                foreach (string line in File.ReadAllLines(settingsFile))
                {
                    string[] parts = line.Split(' ');
                    if (parts.Length == 2)
                    {
                        settings.Add(parts[0], parts[1]);
                    }
                }
            }

            base.OnStartup(e);
        }
        /// <summary>
        ///     Establish a link with an instrument
        ///     Handles retries for failed connections
        /// </summary>
        /// <param name="retryAttempts"></param>
        /// <returns></returns>
        public async Task Connect(int retryAttempts = MaxConnectionAttempts)
        {
            var connectionAttempts = 0;

            CancellationTokenSource = new CancellationTokenSource();
            var ct = CancellationTokenSource.Token;

            var result = Task.Run(async() =>
            {
                while (!IsConnected)
                {
                    connectionAttempts++;
                    Log.Info($"[{CommPort.Name}] Connecting to Instrument... Attempt {connectionAttempts} of {MaxConnectionAttempts}");

                    try
                    {
                        if (!CommPort.IsOpen())
                        {
                            await CommPort.Open();
                        }

                        await ConnectToInstrument();
                    }
                    catch (Exception ex)
                    {
                        Log.Warn(ex.Message);
                    }

                    if (!IsConnected)
                    {
                        if (connectionAttempts < retryAttempts)
                        {
                            Thread.Sleep(ConnectionRetryDelayMs);
                        }
                        else
                        {
                            throw new Exception($"{CommPort.Name} Could not connect to instrument.");
                        }
                    }
                }
            }, ct);

            try
            {
                await result;
            }
            catch (AggregateException e)
            {
                foreach (var v in e.InnerExceptions)
                {
                    Log.Warn(e.Message + " " + v.Message);
                }
            }
            finally
            {
                CancellationTokenSource.Dispose();
            }
        }
 public override bool Connect()
 {
     try
     {
         if (_vcom.IsOpen)
         {
             _vcom.Close();
         }
         _vcom.Open(_connectionInfo.VComName4Socket);
     }
     catch (Exception e)
     {
         Logger.Error(e.ToString());
         return(false);
     }
     return(true);
 }
Exemple #9
0
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args.Length != 1)
            {
                MessageBox.Show("usage: lmeter [port_name]", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(1);
                return;
            }

            string answer;

            try
            {
                p              = new CommPort(e.Args[0], string.Empty);
                p.ReadTimeout  = 300;
                p.WriteTimeout = 300;
                p.Open();
                p.Write("I");
                Thread.Sleep(100);
                answer = p.ReadExisting();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Comm port opening error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(2);
                return;
            }

            if (answer != "LMETER1.0")
            {
                MessageBox.Show("Wrong device answer to identify command: " + (answer == null ? string.Empty : answer), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(3);
                return;
            }

            string cs = ConfigurationManager.AppSettings["C"];

            if (cs == null || !double.TryParse(cs, out c))
            {
                MessageBox.Show("Wrong C parameter: " + (cs == null ? string.Empty : cs), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(4);
                return;
            }

            base.OnStartup(e);
        }
Exemple #10
0
 /// <summary>
 /// 打开
 /// </summary>
 public void Open()
 {
     if (_Commport.PortOpened)
     {
         _Commport.Close();
     }
     _Commport.Open();
     if (_Commport.PortOpened)
     {
         _Commport.OnDataArrivedEvent -= new DataArrivedDelegate(Commport_OnDataArrivedEvent);
         _Commport.OnDataArrivedEvent += new DataArrivedDelegate(Commport_OnDataArrivedEvent);
     }
     else
     {
         throw new Exception("串口打开失败");
     }
 }
Exemple #11
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            CommPort c = new CommPort(cmbCommport.ComPort, 2400);

            c.Open();
            if (c.PortOpened)
            {
                while (true)
                {
                    c.DtrEnable = true;
                    System.Threading.Thread.Sleep(2000);
                    c.DtrEnable = false;
                    System.Threading.Thread.Sleep(2000);
                }
            }
            else
            {
                MessageBox.Show("串口打开失败");
            }
        }
Exemple #12
0
        public bool Open()
        {
            Trace.Assert(CommPort != null);
            try
            {
                if (CommPort.IsOpen)
                {
                    CommPort.Close();
                }

                logger.Verbose($"Protocol.Open:{GetCommPortSettings()}");
                Trace.Assert(!CommPort.IsOpen);
                CommPort.Open();
                logger.Verbose($"- {(CommPort.IsOpen ? "OPEN" : "NOT OPENED")}");
                SendCommand("ECHO=OFF");
            }
            catch (Exception exception)
            {
                logger.Error($"Could Not Open {GetCommPortSettings()} \n{exception.Message}\nPlease Check Comm Settings.");
            }

            return(CommPort.IsOpen);
        }
Exemple #13
0
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args.Length != 1)
            {
                MessageBox.Show("usage: charger [port_name]", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(1);
                return;
            }

            string answer;

            try
            {
                p              = new CommPort(e.Args[0], string.Empty);
                p.ReadTimeout  = 300;
                p.WriteTimeout = 300;
                p.Open();
                p.Write("I\r");
                Thread.Sleep(100);
                answer = p.ReadExisting();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Comm port opening error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(2);
                return;
            }

            if (answer != "CHG10")
            {
                MessageBox.Show("Wrong device answer to identify command: " + (answer == null ? string.Empty : answer), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(3);
                return;
            }

            base.OnStartup(e);
        }
Exemple #14
0
 public void Connect()
 {
     _Commport.Open();
 }
Exemple #15
0
 /// <summary>
 /// 打开串口通讯设备
 /// </summary>
 /// <returns></returns>
 public void Open()
 {
     _commPort.Open();
 }
Exemple #16
0
 /// <summary>
 /// 打开扫瞄枪
 /// </summary>
 public void Open()
 {
     _comm.Open();
 }
Exemple #17
0
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args.Length != 1)
            {
                MessageBox.Show("usage: drillironc [port_name]", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(1);
                return;
            }

            string answer;

            try
            {
                p              = new CommPort(e.Args[0], string.Empty);
                p.ReadTimeout  = 300;
                p.WriteTimeout = 300;
                p.Open();
                p.Write("I");
                Thread.Sleep(100);
                answer = p.ReadExisting();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Comm port opening error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(2);
                return;
            }

            if (answer != "DRILLIRONC1.0")
            {
                MessageBox.Show("Wrong device answer to identify command: " + (answer == null ? string.Empty : answer), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(3);
                return;
            }

            drill_title   = ConfigurationManager.AppSettings["drill_title"];
            program_title = ConfigurationManager.AppSettings["program_title"];

            heaterProfiles = new List <HeaterProfile> [3];
            for (int i = 0; i < 3; i++)
            {
                heaterProfiles[i] = new List <HeaterProfile>();
            }
            for (int i = 1; ; i++)
            {
                double multipler, adder;
                int    heaterID;
                string prefix    = "profile" + i;
                string parameter = prefix + "_title";
                string title     = ConfigurationManager.AppSettings[parameter];
                if (title == null)
                {
                    break;
                }
                parameter = prefix + "_heaterID";
                string value = ConfigurationManager.AppSettings[parameter];
                if (value == null || !int.TryParse(value, out heaterID) || heaterID < 1 || heaterID > 3)
                {
                    MessageBox.Show("Wrong " + parameter + " parameter: " + (value == null ? string.Empty : value), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Shutdown(4);
                    return;
                }
                parameter = prefix + "_adder";
                value     = ConfigurationManager.AppSettings[parameter];
                if (value == null || !double.TryParse(value, out adder))
                {
                    MessageBox.Show("Wrong " + parameter + " parameter: " + (value == null ? string.Empty : value), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Shutdown(4);
                    return;
                }
                parameter = prefix + "_multipler";
                value     = ConfigurationManager.AppSettings[parameter];
                if (value == null || !double.TryParse(value, out multipler) || multipler == 0)
                {
                    MessageBox.Show("Wrong " + parameter + " parameter: " + (value == null ? string.Empty : value), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Shutdown(4);
                    return;
                }
                parameter = prefix + "_dual_temp";
                value     = ConfigurationManager.AppSettings[parameter];
                bool dual_temp_enabled = value != null && value.Equals("true", StringComparison.OrdinalIgnoreCase);
                heaterProfiles[heaterID - 1].Add(new HeaterProfile(title, i, heaterID, multipler, adder, dual_temp_enabled));
            }
            nextCommands = new Queue <DeviceCommand>();
            settings     = new Dictionary <string, string>();
            if (File.Exists(settingsFile))
            {
                foreach (string line in File.ReadAllLines(settingsFile))
                {
                    string[] parts = line.Split(' ');
                    if (parts.Length == 2)
                    {
                        settings.Add(parts[0], parts[1]);
                    }
                }
            }
            base.OnStartup(e);
        }
Exemple #18
0
        private void FrmTestHardware_Load(object sender, EventArgs e)
        {
            #region 中英文转换

            if (_isEnglish)
            {
                Text                      = "Hardware Checking"; //硬件检测
                LblLHP.Text               = "LHP";               //左手心
                LblLHB.Text               = "LHB";               //左手背
                LblRHP.Text               = "RHP";               //右手心
                LblRHB.Text               = "RHB";               //右手背
                LblLF.Text                = "LF";                //左脚
                LblRF.Text                = "RF";                //右脚
                LblHighVoltage.Text       = "High Voltage";      //探头高压
                Lblαcountrate.Text        = "αcount rate";       //α计数率
                LblαTotalcnt.Text         = "αTotal cnt";        //α总计数
                Lblβcountrate.Text        = "βcount rate";       //β计数率
                LblβTotalcnt.Text         = "βTotal cnt";        //β总计数
                LblStatus.Text            = "Status";            //工作状态
                LblV.Text                 = "V";
                LblAlphacps.Text          = "cps";
                LblAlphacnt.Text          = "cnt";
                LblBetacps.Text           = "cps";
                LblBetacnt.Text           = "cnt";
                GrpFrisker.Text           = "Frisker";             //衣物探头
                LblFriskercount.Text      = "Count rate";          //计数
                GrpSensorstate.Text       = "Sensor state";        //红外状态
                LblFriskerState.Text      = "Frisker";             //衣物
                LblRHandState.Text        = "RHand";               //右手
                LblLHandState.Text        = "LHand";               //左手
                GrpDetectorSelfTest.Text  = "Detector Self-Test";  //探头自检
                BtnAlphaCheck.Text        = "α";                   //α自检
                BtnBetaCheck.Text         = "β";                   //β自检
                GrpSelfTestParameter.Text = "Self-Test Parameter"; //自检参数
                BtnSelfCheck.Text         = "Run";                 //自检
                CmbControl.Text           = "L";
                CmbPulse.Text             = "L";
                LblControl.Text           = "Control";    //控制
                LblPWidth.Text            = "P Width";    //脉宽
                LblPulse.Text             = "Pulse";      //脉冲
                LblSelfcount.Text         = "Count rate"; //计数
            }

            #endregion 中英文转换

            //初始化运行状态为默认状态
            _platformState = HardwarePlatformState.Default;
            //初始化测量时间为系统参数时间
            _measuringTime = _sqltime + 1;

            #region 开启端口

            //从配置文件获得当前串口配置
            if (_commPort.Opened == true)
            {
                _commPort.Close();
            }

            _commPort.GetCommPortSet("commportSet");
            //打开串口
            try
            {
                _commPort.Open();
                if (_commPort.Opened)
                {
                    Tools.FormBottomPortStatus = true;
                }
                else
                {
                    Tools.FormBottomPortStatus = false;
                }
            }
            catch
            {
                if (_isEnglish == true)
                {
                    MessageBox.Show("Port open error! Please check whether the communication is normal.");
                    //return;
                }
                else
                {
                    MessageBox.Show("端口打开错误!请检查通讯是否正常。");
                    //return;
                }
            }

            #endregion 开启端口

            //获得通道信息
            Channel channel = new Channel();
            channelS = channel.GetChannel();
            if (bkWorkerReceiveData.IsBusy == false)
            {
                //开启异步线程
                bkWorkerReceiveData.RunWorkerAsync();
            }
        }
Exemple #19
0
        public RS232()
        {
            try
            {
                InitializeComponent();

                CommPort com = CommPort.Instance;


                int      found    = 0;
                string[] portList = com.GetAvailablePorts();
                for (int i = 0; i < portList.Length; ++i)
                {
                    string name = portList[i];
                    comboBoxPortName.Items.Add(name);
                    if (name == Settings.Port.PortName)
                    {
                        found = i;
                    }
                }
                if (portList.Length > 0)
                {
                    comboBoxPortName.SelectedIndex = found;
                }

                Int32[] baudRates =
                {
                    100,     300,   600,   1200,   2400,   4800, 9600, 14400, 19200,
                    38400, 56000, 57600, 115200, 128000, 256000, 0
                };
                found = 0;
                for (int i = 0; baudRates[i] != 0; ++i)
                {
                    comboBoxBaudRate.Items.Add(baudRates[i].ToString());
                    if (baudRates[i] == Settings.Port.BaudRate)
                    {
                        found = i;
                    }
                }
                comboBoxBaudRate.SelectedIndex = found;

                comboBoxDataBits.Items.Add("5");
                comboBoxDataBits.Items.Add("6");
                comboBoxDataBits.Items.Add("7");
                comboBoxDataBits.Items.Add("8");
                comboBoxDataBits.SelectedIndex = Settings.Port.DataBits - 5;

                foreach (string s in Enum.GetNames(typeof(Parity)))
                {
                    comboBoxParity.Items.Add(s);
                }
                comboBoxParity.SelectedIndex = (int)Settings.Port.Parity;

                foreach (string s in Enum.GetNames(typeof(StopBits)))
                {
                    comboBoxStopBits.Items.Add(s);
                }
                comboBoxStopBits.SelectedIndex = (int)Settings.Port.StopBits;

                foreach (string s in Enum.GetNames(typeof(Handshake)))
                {
                    comboBoxHandshake.Items.Add(s);
                }
                comboBoxHandshake.SelectedIndex = (int)Settings.Port.Handshake;

                com.StatusChanged += OnStatusChanged;

                //com.DataReceived += OnDataReceived;

                com.Open();
            }
            catch (Exception ex)
            {
                LogClass.WriteLogFile("Exception:" + ex.ToString());
            }
        }