Esempio n. 1
0
        /// <summary>
        ///按位获取输出信号
        /// </summary>
        /// <param name="nIndex"></param>
        /// <returns></returns>
        public override bool ReadIoOutBit(int nIndex)
        {
            if (!m_bOpen)
            {
                return(false);
            }
            int    nAxisIndex   = (nIndex & 0xff00) >> 8;
            int    nBitIndex    = nIndex & 0x00ff;
            byte   bitData      = 0;
            byte   slaveAddress = (byte)m_nCardNo;
            ushort coilAddress  = (ushort)nBitIndex;

            try
            {
                lock (_syncRoot)
                    return(_master.ReadCoils(slaveAddress, (ushort)(coilAddress + 80), 1)[0]);
            }
            catch (Exception ex)
            {
                if (_serialPort.IsOpen)
                {
                    _serialPort.Close();
                }
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }
                _master.Dispose();
                _master = ModbusSerialMaster.CreateRtu(_serialPort);
                _logger.Warn(ex.Message);
                return(false);
            }
        }
Esempio n. 2
0
 private void MnuFileExit_Click(object sender, EventArgs e)
 {
     if (MessageBox.Show(this, "Do you want to close?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
     {
         serialPort.Close();
         serialPort.Dispose();
         master.Dispose();
         this.Dispose();
     }
 }
Esempio n. 3
0
        public string parameterSeting(byte addr, UInt16 reg_addr, byte reg_lenth, Single value, string type, SerialPort port)
        {
            string result = "Success";
            IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

            master.Transport.ReadTimeout  = 1000;
            master.Transport.WriteTimeout = 1000;
            if (!port.IsOpen)
            {
                try
                {
                    port.Open();
                }
                catch (InvalidOperationException)
                {
                    result = "Port was open";
                }
                catch (UnauthorizedAccessException)
                {
                    result = "Port was open";
                }
                catch (IOException)
                {
                    result = "Port was not found";
                }
            }
            if (result == "Success")
            {
                try
                {
                    byte[] temp_bytes = BitConverter.GetBytes(value);
                    UInt32 temp_int   = 0;
                    temp_int += (uint)temp_bytes[3] << 3 * 8;
                    temp_int += (uint)temp_bytes[2] << 2 * 8;
                    temp_int += (uint)temp_bytes[1] << 1 * 8;
                    temp_int += (uint)temp_bytes[0] << 0 * 8;
                    ushort[] data = { (ushort)temp_int, (ushort)(temp_int >> 16) };
                    master.WriteMultipleRegisters(addr, reg_addr, data);
                }
                catch (InvalidOperationException)
                {
                    result = "Port not Found";
                }
                catch (TimeoutException)
                {
                    result = "Time out";
                }
                catch (Modbus.SlaveException ex)
                {
                    result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                }
            }
            port.Close();
            master.Dispose();
            return(result);
        }
Esempio n. 4
0
        protected override void OnStop()
        {
            if (workerThread.IsAlive)
            {
                WriteLog("Aborting thread...");
                workerThread.Abort();
            }

            MBRtu.Dispose();

            WriteLog("Service stopped.");
        }
Esempio n. 5
0
 public void Disconnect()
 {
     try
     {
         m_master.Dispose();
         m_port.Close();
         m_port.Dispose();
     }
     catch
     {
     }
 }
Esempio n. 6
0
        private void InitSerialPort()
        {
            try
            {
                if (master != null)
                {
                    master.Dispose();
                }
                if (serialPort != null)
                {
                    serialPort.Close();
                    serialPort.Dispose();
                    serialPort = null;
                }
                if (serialPort == null)
                {
                    serialPort = new SerialPort(Serial_PARA.SerialPort);
                }

                serialPort.BaudRate = Serial_PARA.BaudRate;

                serialPort.DataBits = Serial_PARA.DataBits;

                serialPort.Parity = Serial_PARA.SerialCheck;

                serialPort.StopBits = Serial_PARA.StopBits;

                serialPort.ReadTimeout = Serial_PARA.ReadTimeout;

                serialPort.WriteTimeout = Serial_PARA.WriteTimeout;

                serialPort.RtsEnable = Serial_PARA.RTSEnable;
                serialPort.PortName  = Serial_PARA.SerialPort;
                serialPort.NewLine   = NewLine;
                if (!serialPort.IsOpen)
                {
                    try
                    {
                        serialPort.Open();
                    }
                    catch (Exception exm)
                    {
                        LogOutput(exm.Message);
                    }
                }
            }
            catch (Exception exm)
            {
                LogOutput(exm.Message);
            }
        }
Esempio n. 7
0
        public void Dispose()
        {
            if (_serialPort != null)
            {
                _serialPort.Dispose();
                _serialPort = null;
            }

            if (_master == null)
            {
                return;
            }

            _master.Dispose();
            _master = null;
        }
Esempio n. 8
0
        private void uartportcontrl_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)uartportcontrl.IsChecked)
            {
                try
                {
                    serialPort.PortName = uartname.SelectedItem.ToString();
                    serialPort.BaudRate = 115200;
                    serialPort.DataBits = 8;
                    serialPort.Parity   = Parity.None;
                    serialPort.StopBits = StopBits.One;
                    serialPort.Open();

                    imodbusserialmaster = ModbusSerialMaster.CreateAscii(serialPort);

                    uartname.IsEnabled  = false;
                    buteRaate.IsEnabled = false;
                    addmsg($">> 打开串口成功!");
                }
                catch (Exception ex)
                {
                    uartportcontrl.IsChecked = false;
                    uartname.IsEnabled       = true;
                    buteRaate.IsEnabled      = true;
                    addmsg($"ERROR:打开串口失败!{ex.ToString()}");
                }
            }
            else
            {
                try
                {
                    serialPort.Close();
                    imodbusserialmaster.Dispose();
                    uartname.IsEnabled  = true;
                    buteRaate.IsEnabled = true;
                    addmsg($">> 关闭串口成功!");
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show($"关闭串口失败,请插拔串口,并重启软件! {ex.ToString()}");
                }
            }
        }
Esempio n. 9
0
 public static bool Close()
 {
     try
     {
         if (serialPort != null && serialPort.IsOpen)
         {
             serialPort.Close();
         }
         if (master != null)
         {
             master.Dispose();
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     return(true);
 }
Esempio n. 10
0
        /// <summary>
        /// 통신 종료
        /// </summary>
        public void Stop()
        {
            try
            {
                dataGridViewBMSStatus.SafeInvoke(d => d.Rows.Clear());
                foreach (DataRow row in mDataTable.Rows)
                {
                    dataGridViewBMSStatus.SafeInvoke(d => d.Rows.Add(row["Name"], "null", "null", "null", "null", "null", "null", "null", "null", row["Contact1"], row["Contact2"], row["Contact3"], row["Contact4"]));
                }



                // UI 업데이트 종료
                //timer1.Stop();
                timer1.Enabled = false;

                // 모드버스 통신 스레드 종료
                RequestStop();


                // 모드버스 디스크립터 종료
                if (master != null)
                {
                    master.Dispose();
                }


                // COM 포트 닫기
                if (mComport.IsOpen)
                {
                    mComport.Close();
                }


                // 에러카운트 초기화(에러 발생시 탭이 점멸시 확인하는 에러 갯수 - 하나의 에러가 취소 되더라도 다른 애러가 있다면 점멸을 계속 유지하기)
                mErrorCount = 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 11
0
        protected override void Start()
        {
            if (master != null)
            {
                master.Dispose();
            }
            if (_serialPort != null)
            {
                _serialPort.Close();
                _serialPort.Dispose();
                _serialPort = null;
            }

            try
            {
                byte[] array = new byte[8];

                #region
                {
                    InitSerialPort(ref _serialPort);



                    if (Serial_PARA.ModbusType == ModbusType.ASCII)
                    {
                        master = ModbusSerialMaster.CreateAscii(_serialPort);
                    }
                    else
                    {
                        master = ModbusSerialMaster.CreateRtu(_serialPort);
                    }
                    //通用部分设置
                    master.Transport.ReadTimeout             = Serial_PARA.ReadTimeout;           //读取数据超时1000ms
                    master.Transport.WriteTimeout            = Serial_PARA.WriteTimeout;          //写入数据超时1000ms
                    master.Transport.Retries                 = Serial_PARA.CollectFaultsNumber;   //重试次数
                    master.Transport.WaitToRetryMilliseconds = Serial_PARA.CollectFaultsInternal; //重试间隔

                    Thread.Sleep(800);
                    //此处采用多线程技术创建一个实时读取数据的任务
                    for (int i = 0; i < this.RealDevices.Count; i++)
                    {
                        RealData mRealData = this.RealDevices[i];
                        //创建一个子任务
                        Task.Run(() =>
                        {
                            while (true && this.ServerIsRun)
                            {
                                if (this.ServerIsSuspend)
                                {
                                    continue;
                                }

                                try
                                {
                                    Task.Run(() =>
                                    {
                                        //发送获取数据的命令
                                        string error = "";
                                        if (!this.RequestData(mRealData.Device, mRealData, out error, mRealData.Fragment))
                                        {
                                            this.DeviceException("ERROR=Modbus_Serial_10001," + error);
                                        }
                                    });
                                }
                                catch (Exception e)
                                {
                                    this.DeviceException("ERROR=Modbus_Serial_10002," + e.Message);
                                }


                                //更新周期
                                Thread.Sleep(mRealData.Device.IO_DEVICE_UPDATECYCLE * 1000);
                            }
                        });
                    }

                    this.CommunctionStartChanged(this.IOServer, this.IOServer.SERVER_IP + " " + this.IOServer.SERVER_NAME + "启动服务");
                }
                #endregion
            }
            catch
            {
            }
        }
Esempio n. 12
0
        protected override void Start()
        {
            if (master != null)
            {
                master.Dispose();
            }
            if (_serialPort != null)
            {
                _serialPort.Close();
                _serialPort.Dispose();
                _serialPort = null;
            }

            try
            {
                Serial_PARA = new Modbus_Serial_PARA();
                byte[] array = new byte[8];
                if (_serialPort == null)
                {
                    _serialPort = new SerialPort(Serial_PARA.SerialPort);
                }
                #region
                {
                    _serialPort.BaudRate = Serial_PARA.BaudRate;
                    _serialPort.DataBits = Serial_PARA.DataBits;
                    switch (Serial_PARA.SerialCheck)
                    {
                    case SerialCheck.无:
                    {
                        _serialPort.Parity = Parity.None;
                    }
                    break;

                    case SerialCheck.奇校验:
                    {
                        _serialPort.Parity = Parity.Odd;
                    }
                    break;

                    case SerialCheck.偶校验:
                    {
                        _serialPort.Parity = Parity.Even;
                    }
                    break;

                    case SerialCheck.常0:
                    {
                        _serialPort.Parity = Parity.Space;
                    }
                    break;

                    case SerialCheck.常1:
                    {
                        _serialPort.Parity = Parity.Mark;
                    }
                    break;
                    }

                    _serialPort.StopBits     = Serial_PARA.StopBits;
                    _serialPort.ReadTimeout  = 1000;
                    _serialPort.WriteTimeout = 1000;
                    _serialPort.RtsEnable    = Serial_PARA.RTSEnable;
                    _serialPort.NewLine      = NewLine;
                    _serialPort.Open();
                    master = ModbusSerialMaster.CreateRtu(_serialPort);
                    Thread.Sleep(800);
                    //此处采用多线程技术创建一个实时读取数据的任务
                    for (int i = 0; i < this.RealDevices.Count; i++)
                    {
                        RealData mRealData = this.RealDevices[i];
                        //创建一个子任务
                        Task.Run(() =>
                        {
                            while (true && this.ServerIsRun)
                            {
                                if (this.ServerIsSuspend)
                                {
                                    continue;
                                }
                                if (mRealData.ReadSendByte.Count > 0)
                                {
                                    for (int c = 0; c < mRealData.ReadSendByte.Count; c++)
                                    {
                                        try
                                        {
                                            //发送获取数据的命令
                                            string error = "";
                                            if (!this.Send(mRealData.Device, mRealData.ReadSendByte[c], out error))
                                            {
                                                this.DeviceException("ERROR=Modbus_Serial_10001," + error);
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            this.DeviceException("ERROR=Modbus_Serial_10002," + e.Message);
                                        }
                                    }
                                }
                                //更新周期
                                Thread.Sleep(mRealData.Device.IO_DEVICE_UPDATECYCLE);
                            }
                        });
                    }

                    this.CommunctionStartChanged(this.IOServer, this.IOServer.SERVER_IP + " " + this.IOServer.SERVER_NAME + "启动服务");
                    //实时接收数据
                    Task.Run(() => {
                        while (true)
                        {
                            try
                            {
                                //判断串口是否处于打开状态,如果不在打开状态,则重新打开
                                if (!_serialPort.IsOpen)
                                {
                                    _serialPort.Open();
                                }
                                //读取数据
                                if (_serialPort.BytesToRead > 0)
                                {
                                }
                            }
                            catch (Exception emx)
                            {
                                //处理异常
                                this.DeviceException("ERROR=Modbus_Serial_10006," + emx.Message);
                                //等待10秒
                                Thread.Sleep(10000);
                                //重新初始化
                                if (Serial_PARA.Counting >= Serial_PARA.CollectFaultsNumber)
                                {
                                    Start();
                                    return;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }
                    });
                }
                #endregion
            }
            catch (Exception emx)
            {
            }
        }
Esempio n. 13
0
 public void Close()
 {
     _port.Close();
     _master.Dispose();
 }
Esempio n. 14
0
        public string parameterSeting(byte addr, UInt16 reg_addr, byte reg_lenth, String value, string type, SerialPort port)
        {
            string result = "Success";
            IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

            master.Transport.ReadTimeout  = 1000;
            master.Transport.WriteTimeout = 1000;
            if (!port.IsOpen)
            {
                try
                {
                    port.Open();
                }
                catch (InvalidOperationException)
                {
                    result = "Port was open";
                }
                catch (UnauthorizedAccessException)
                {
                    result = "Port was open";
                }
                catch (IOException)
                {
                    result = "Port was not found";
                }
            }
            if (result == "Success")
            {
                if ((type == "uint16") && (reg_lenth == 1))
                {
                    try
                    {
                        master.WriteSingleRegister(addr, reg_addr, Convert.ToUInt16(value));
                    }
                    catch (System.Exception ex)
                    {
                        result = ex.Message;
                    }
                    //catch (InvalidOperationException)
                    //{

                    //    result = "Port not Found";
                    //}
                    //catch (TimeoutException)
                    //{
                    //    result = "Time out";
                    //}
                    //catch (Modbus.SlaveException ex)
                    //{
                    //    result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    //}
                }
                if ((type == "uint32") && (reg_lenth == 2))
                {
                    try
                    {
                        UInt32   Value = Convert.ToUInt32(value);
                        ushort[] data  = { (ushort)Value, (ushort)(Value >> 16) };
                        master.WriteMultipleRegisters(addr, reg_addr, data);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
                if ((type == "float") && (reg_lenth == 2))
                {
                    try
                    {
                        float  Value      = float.Parse(value);
                        byte[] temp_bytes = BitConverter.GetBytes(Value);
                        UInt32 temp_int   = 0;
                        temp_int += (uint)temp_bytes[3] << 3 * 8;
                        temp_int += (uint)temp_bytes[2] << 2 * 8;
                        temp_int += (uint)temp_bytes[1] << 1 * 8;
                        temp_int += (uint)temp_bytes[0] << 0 * 8;
                        ushort[] data = { (ushort)temp_int, (ushort)(temp_int >> 16) };
                        master.WriteMultipleRegisters(addr, reg_addr, data);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
                if ((type == "char") && ((reg_lenth == 8 || (reg_lenth == 16))))  //通常为设置序列号
                {
                    try
                    {
                        ushort[] data = new ushort[value.Length / 2 + 1];
                        int      rest = value.Length % 2;

                        for (int i = 0, j = 0; i < value.Length / 2; i++)
                        {
                            data[i] = (ushort)(value[j + 1] << 8 | value[j]);
                            j      += 2;
                        }
                        if (rest == 0)
                        {
                            data[value.Length / 2] = 0;
                        }
                        else
                        {
                            data[value.Length / 2] = value[value.Length - 1];
                        }
                        master.WriteMultipleRegisters(addr, reg_addr, data);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
            }
            port.Close();
            master.Dispose();
            return(result);
        }
Esempio n. 15
0
        public string parameterSeting(byte addr, UInt16 reg_addr, byte reg_lenth, UInt32 value, string type, SerialPort port)
        {
            string result = "Success";
            IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

            master.Transport.ReadTimeout  = 1000;
            master.Transport.WriteTimeout = 1000;
            if (!port.IsOpen)
            {
                try
                {
                    port.Open();
                }
                catch (InvalidOperationException)
                {
                    result = "Port was open";
                }
                catch (UnauthorizedAccessException)
                {
                    result = "Port was open";
                }
                catch (IOException)
                {
                    result = "Port was not found";
                }
            }
            if (result == "Success")
            {
                if (type == "uint16")
                {
                    try
                    {
                        master.WriteSingleRegister(addr, reg_addr, (UInt16)value);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
                else if (type == "uint32")
                {
                    try
                    {
                        ushort[] data = { (ushort)value, (ushort)(value >> 16) };
                        master.WriteMultipleRegisters(addr, reg_addr, data);
                    }
                    catch (InvalidOperationException)
                    {
                        result = "Port not Found";
                    }
                    catch (TimeoutException)
                    {
                        result = "Time out";
                    }
                    catch (Modbus.SlaveException ex)
                    {
                        result = "unknown exception :" + ex.SlaveExceptionCode.ToString();
                    }
                }
            }

            port.Close();
            master.Dispose();
            //stopwatch.Start();
            //stopwatch.Stop();
            //System.Diagnostics.Debug.WriteLine("modbuswriteTime:" + stopwatch.ElapsedMilliseconds.ToString());
            //stopwatch.Reset();
            return(result);
        }