Ejemplo n.º 1
0
        /// <summary>
        /// Acquisition thread
        ///		Awaits for trigger;
        ///		After configured period send appropriate command to MdbSim for each point type
        /// </summary>
        private void Acquisition_DoWork()
        {
            while (true)
            {
                try
                {
                    acquisitionTrigger.WaitOne();
                    DO_REG_sekunde++;

                    HR_INT_sekunde++;
                    if (DO_REG_sekunde == ConfigReader.Instance.GetAcquisitionInterval("DigOut"))
                    {
                        ModbusReadCommandParameters p = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, ConfigReader.Instance.GetStartAddress("DigOut"), ConfigReader.Instance.GetNumberOfRegisters("DigOut"));;
                        ModbusFunction fn             = FunctionFactory.CreateModbusFunction(p);
                        this.commandExecutor.EnqueueCommand(fn);
                        DO_REG_sekunde = 0;
                    }

                    if (HR_INT_sekunde == ConfigReader.Instance.GetAcquisitionInterval("AnaOut"))
                    {
                        ModbusReadCommandParameters p = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, ConfigReader.Instance.GetStartAddress("AnaOut"), ConfigReader.Instance.GetNumberOfRegisters("AnaOut"));;
                        ModbusFunction fn             = FunctionFactory.CreateModbusFunction(p);
                        this.commandExecutor.EnqueueCommand(fn);
                        HR_INT_sekunde = 0;
                    }
                }
                catch (Exception ex)
                {
                    string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                    stateUpdater.LogMessage(message);
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Method that is executed when write button is clicked on control window;
        /// Method should create write command parameters and provide it to FunctionFactory
        /// </summary>
        /// <param name="obj">Not used</param>
        private void WriteCommand_Execute(object obj)
        {
            try
            {
                ModbusWriteCommandParameters para = null;

                switch (type)
                {
                case PointType.DIGITAL_OUTPUT:
                    para = new ModbusWriteCommandParameters(6, (byte)ModbusFunctionCode.WRITE_SINGLE_COIL, address, commandedValue);
                    break;

                case PointType.ANALOG_OUTPUT:
                    para = new ModbusWriteCommandParameters(6, (byte)ModbusFunctionCode.WRITE_SINGLE_REGISTER, address, commandedValue);
                    break;

                default:
                    break;
                }


                ModbusFunction fn = FunctionFactory.CreateModbusFunction(para);
                this.commandExecutor.EnqueueCommand(fn);
            }
            catch (Exception ex)
            {
                string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                this.stateUpdater.LogMessage(message);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Method that is executed when read button is clicked on control window;
        /// Method should create read command parameters and provide it to FunctionFactory
        /// </summary>
        /// <param name="obj">Not used</param>
        private void ReadCommand_Execute(object obj)
        {
            try
            {
                ConfigReader reader = ConfigReader.Instance;

                ModbusReadCommandParameters mdb = null;

                if (Type == PointType.ANALOG_INPUT)
                {
                    mdb = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_INPUT_REGISTERS, Address, 1);
                }
                if (Type == PointType.DIGITAL_OUTPUT)
                {
                    mdb = new ModbusReadCommandParameters(6, (byte)Type, Address, 1);
                }
                if (Type == PointType.DIGITAL_INPUT)
                {
                    mdb = new ModbusReadCommandParameters(6, (byte)Type, Address, 1);
                }
                if (Type == PointType.ANALOG_OUTPUT)
                {
                    mdb = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, Address, 1);
                }

                ModbusFunction fn = FunctionFactory.CreateModbusFunction(mdb);
                this.commandExecutor.EnqueueCommand(fn);
            }
            catch (Exception ex)
            {
                string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                this.stateUpdater.LogMessage(message);
            }
        }
Ejemplo n.º 4
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            //Transaction Identifier + Protocol Identifier + Length + Unit Identifier + Function Code
            if (input.Capacity < 2 + 2 + 2 + 1 + 1)
            {
                return;
            }

            ModbusHeader   header       = new ModbusHeader(input);
            short          functionCode = input.ReadByte();
            ModbusFunction function     = null;

            if (Enum.IsDefined(typeof(ModbusCommand), functionCode))
            {
                var command = Enum.GetName(typeof(ModbusCommand), functionCode);

                function = (ModbusFunction)Activator.CreateInstance(Type.GetType(string.Format(typeName, isServerMode ? "Request" : "Response", command)));
            }


            if (functionCode >= maxFunctionCode)
            {
                function = new ExceptionFunction(functionCode);
            }
            else if (function == null)
            {
                function = new ExceptionFunction(functionCode, 0x01);
            }

            function.Decode(input);
            ModbusFrame frame = new ModbusFrame(header, function);

            output.Add(frame);
        }
Ejemplo n.º 5
0
        private void ReadCommand_Execute(object obj)
        {
            try
            {
                // TODO implement
                ModbusReadCommandParameters p = null;
                switch (type)
                {
                case PointType.DO_REG:
                    p = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, address, 1);
                    break;

                case PointType.DI_REG:
                    p = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_DISCRETE_INPUTS, address, 1);
                    break;

                case PointType.IN_REG:
                    p = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_INPUT_REGISTERS, address, 1);
                    break;
                }
                ModbusFunction fn = FunctionFactory.CreateModbusFunction(p);
                this.commandExecutor.ExecuteCommand(fn);
            }
            catch (Exception ex)
            {
                string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                this.stateUpdater.LogMessage(message);
            }
        }
Ejemplo n.º 6
0
        private void WriteCommand_Execute(object obj)
        {
            try
            {
                ModbusWriteCommandParameters p = null;

                switch (type)
                {
                case PointType.DO_REG:
                    p = new ModbusWriteCommandParameters(6, (byte)ModbusFunctionCode.WRITE_SINGLE_COIL, address, RawValue);
                    break;

                case PointType.HR_INT:
                    p = new ModbusWriteCommandParameters(6, (byte)ModbusFunctionCode.WRITE_SINGLE_REGISTER, address, RawValue);
                    break;

                default:
                    break;
                }



                // TODO implement
                ModbusFunction fn = FunctionFactory.CreateModbusFunction(p);
                this.commandExecutor.ExecuteCommand(fn);
            }
            catch (Exception ex)
            {
                string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                this.stateUpdater.LogMessage(message);
            }
        }
Ejemplo n.º 7
0
 public void EnqueueCommand(ModbusFunction commandToExecute)
 {
     if (this.connectionState == ConnectionState.CONNECTED)
     {
         this.commandQueue.Enqueue(commandToExecute);
         this.processConnection.Set();
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Acquisition thread
        ///		Awaits for trigger;
        ///		After configured period send appropriate command to MdbSim for each point type
        ///
        ///		Kao uslov za while petlju korititi acquisitionStopSignal da bi se akvizicioni thread ugasio kada se aplikacija ugasi
        /// </summary>
        private void Acquisition_DoWork()
        {
            ConfigReader cr  = ConfigReader.Instance;
            int          cnt = 0;

            int DigOut = cr.GetAcquisitionInterval("DigOut");
            int DigIn  = cr.GetAcquisitionInterval("DigIn");
            int AnaOut = cr.GetAcquisitionInterval("AnaOut");
            int AnaIn  = cr.GetAcquisitionInterval("AnaIn");

            ModbusReadCommandParameters mrcp = null;
            ModbusFunction fn = null;

            while (true)
            {
                if (cnt % DigOut == 0)
                {
                    mrcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, cr.GetStartAddress("DigOut"), cr.GetNumberOfRegisters("DigOut"));
                    fn   = FunctionFactory.CreateModbusFunction(mrcp);
                    this.commandExecutor.EnqueueCommand(fn);
                }

                if (cnt % DigIn == 0)
                {
                    mrcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_DISCRETE_INPUTS, cr.GetStartAddress("DigIn"), cr.GetNumberOfRegisters("DigIn"));
                    fn   = FunctionFactory.CreateModbusFunction(mrcp);
                    this.commandExecutor.EnqueueCommand(fn);
                }

                if (cnt % AnaOut == 0)
                {
                    mrcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, cr.GetStartAddress("AnaOut"), cr.GetNumberOfRegisters("AnaOut"));
                    fn   = FunctionFactory.CreateModbusFunction(mrcp);
                    this.commandExecutor.EnqueueCommand(fn);
                }

                if (cnt % AnaIn == 0)
                {
                    mrcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_INPUT_REGISTERS, cr.GetStartAddress("AnaIn"), cr.GetNumberOfRegisters("AnaIn"));
                    fn   = FunctionFactory.CreateModbusFunction(mrcp);
                    this.commandExecutor.EnqueueCommand(fn);
                }

                try
                {
                    acquisitionTrigger.WaitOne();
                    cnt++;
                }
                catch (Exception ex)
                {
                    string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                    stateUpdater.LogMessage(message);
                }
            }
        }
Ejemplo n.º 9
0
        private void Acquisition_DoWork()
        {
            int cnt = 0;

            ConfigReader cr    = ConfigReader.Instance;
            int          DOCnt = cr.GetAcquisitionIntervalForPointType(PointType.DIGITAL_OUTPUT);
            int          DICnt = cr.GetAcquisitionIntervalForPointType(PointType.DIGITAL_INPUT);
            int          AICnt = cr.GetAcquisitionIntervalForPointType(PointType.ANALOG_INPUT);
            int          AOCnt = cr.GetAcquisitionIntervalForPointType(PointType.ANALOG_OUTPUT);



            while (true)
            {
                //// TODO implement
                if (cnt % DOCnt == 0)
                {
                    // TODO implement
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, cr.GetStartAddressForPointType(PointType.DIGITAL_OUTPUT), cr.GetNumberOfRegistersForPointType(PointType.DIGITAL_OUTPUT));
                    ModbusFunction fn = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(fn);
                }
                if (cnt % DICnt == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_DISCRETE_INPUTS, cr.GetStartAddressForPointType(PointType.DIGITAL_INPUT), cr.GetNumberOfRegistersForPointType(PointType.DIGITAL_INPUT));
                    ModbusFunction fn = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(fn);
                }
                if (cnt % AOCnt == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, cr.GetStartAddressForPointType(PointType.ANALOG_OUTPUT), cr.GetNumberOfRegistersForPointType(PointType.ANALOG_OUTPUT));
                    ModbusFunction fn = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(fn);
                }
                if (cnt % AICnt == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_INPUT_REGISTERS, cr.GetStartAddressForPointType(PointType.ANALOG_INPUT), cr.GetNumberOfRegistersForPointType(PointType.ANALOG_INPUT));
                    ModbusFunction fn = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(fn);
                }

                try
                {
                    acquisitionTrigger.WaitOne();
                    cnt++;
                }
                catch (Exception ex)
                {
                    string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                    stateUpdater.LogMessage(message);
                }
            }
        }
Ejemplo n.º 10
0
 public void ExecuteCommand(ModbusFunction commandToExecute)
 {
     if (this.currentCommand != null)
     {
         this.stateUpdater.HandleCommandInProgress(currentCommand);
     }
     else
     {
         this.currentCommand = commandToExecute;
         this.processConnection.Set();
     }
 }
Ejemplo n.º 11
0
 private void ReadCommand_Execute(object obj)
 {
     try
     {
         ModbusReadCommandParameters parameters = new ModbusReadCommandParameters(6, (byte)Type, this.Address, 1);
         ModbusFunction fn = FunctionFactory.CreateModbusFunction(this.Type, CommandType.READ, parameters);
         this.commandExecutor.ExecuteCommand(fn);
     }
     catch (Exception ex)
     {
         this.stateUpdater.LogMessage(ex.Message);
     }
 }
Ejemplo n.º 12
0
 private void WriteCommand_Execute(object obj)
 {
     try
     {
         // TODO implement
         ModbusFunction fn = FunctionFactory.CreateModbusFunction(this.Type, CommandType.WRITE, null);
         this.commandExecutor.ExecuteCommand(fn);
     }
     catch (Exception ex)
     {
         this.stateUpdater.LogMessage(ex.Message);
     }
 }
Ejemplo n.º 13
0
        public T CallModbusFunctionSync <T>(ModbusFunction function) where T : ModbusFunction
        {
            var transactionIdentifier = CallModbusFunction(function);

            var handler = (ModbusResponseHandler)Channel.Pipeline.Get(handlerName);

            if (handler == null)
            {
                throw new Exception("Not connected!");
            }

            return((T)handler.GetResponse(transactionIdentifier).Function);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Method that is executed when read button is clicked on control window;
 /// Method should create read command parameters and provide it to FunctionFactory
 /// </summary>
 /// <param name="obj">Not used</param>
 private void ReadCommand_Execute(object obj)
 {
     try
     {
         ModbusFunction fn = FunctionFactory.CreateModbusFunction(null);
         this.commandExecutor.EnqueueCommand(fn);
     }
     catch (Exception ex)
     {
         string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
         this.stateUpdater.LogMessage(message);
     }
 }
Ejemplo n.º 15
0
 private void WriteCommand_Execute(object obj)
 {
     try
     {
         ModbusFunction fn = FunctionFactory.CreateModbusFunction(new ModbusWriteCommandParameters(6, (Byte)ModbusFunctionCode.WRITE_SINGLE_COIL, address, rawValue));
         this.commandExecutor.ExecuteCommand(fn);
     }
     catch (Exception ex)
     {
         string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
         this.stateUpdater.LogMessage(message);
     }
 }
Ejemplo n.º 16
0
        public ushort CallModbusFunction(ModbusFunction function)
        {
            if (ConnectionState.Connected != connectionState || Channel == null)
            {
                throw new Exception("Not connected!");
            }

            SetTransactionIdentifier();

            ModbusHeader header = new ModbusHeader(transactionIdentifier, UnitIdentifier);
            ModbusFrame  frame  = new ModbusFrame(header, function);

            Channel.WriteAndFlushAsync(frame);

            return(transactionIdentifier);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Acquisition thread
        ///		Awaits for trigger;
        ///		After configured period send appropriate command to MdbSim for each point type
        /// </summary>
        private void Acquisition_DoWork()
        {
            int cnt = 0;

            ConfigReader cr = ConfigReader.Instance;

            int DOCnt = cr.GetAcquisitionInterval("DigOut");
            int AOCnt = cr.GetAcquisitionInterval("AnaOut");

            while (true)
            {
                if (cnt % DOCnt == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, cr.GetStartAddress("DigOut"), cr.GetNumberOfRegisters("DigOut"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }

                if (cnt % AOCnt == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, cr.GetStartAddress("AnaOut"), cr.GetNumberOfRegisters("AnaOut"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }



                //ModbusWriteCommandParameters mwcp1 = new ModbusWriteCommandParameters(6, (byte)ModbusFunctionCode.WRITE_SINGLE_COIL, cr.GetStartAddress("DigOut"), cr.GetNumberOfRegisters("DigOut"));
                //ModbusFunction mf1 = FunctionFactory.CreateModbusFunction(mwcp1);
                //this.commandExecutor.EnqueueCommand(mf1);

                //ModbusWriteCommandParameters mwcp2 = new ModbusWriteCommandParameters(6, (byte)ModbusFunctionCode.WRITE_SINGLE_REGISTER, cr.GetStartAddress("AnaOut"), cr.GetNumberOfRegisters("AnaOut"));
                //ModbusFunction mf2 = FunctionFactory.CreateModbusFunction(mwcp2);
                //this.commandExecutor.EnqueueCommand(mf2);

                try
                {
                    acquisitionTrigger.WaitOne();
                    cnt++;
                }
                catch (Exception ex)
                {
                    string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                    stateUpdater.LogMessage(message);
                }
            }
        }
        public ModbusFunction Execute(ModbusFunction function)
        {
            if (function is ReadCoilsRequest)
            {
                var request = (ReadCoilsRequest)function;
                return(ReadCoils(request));
            }
            else if (function is ReadDiscreteInputsRequest)
            {
                var request = (ReadDiscreteInputsRequest)function;
                return(ReadDiscreteInputs(request));
            }
            else if (function is ReadHoldingRegistersRequest)
            {
                var request = (ReadHoldingRegistersRequest)function;
                return(ReadHoldingRegisters(request));
            }
            else if (function is ReadInputRegistersRequest)
            {
                var request = (ReadInputRegistersRequest)function;
                return(ReadInputRegisters(request));
            }
            else if (function is WriteSingleCoilRequest)
            {
                var request = (WriteSingleCoilRequest)function;
                return(WriteSingleCoil(request));
            }
            else if (function is WriteSingleRegisterRequest)
            {
                var request = (WriteSingleRegisterRequest)function;
                return(WriteSingleRegister(request));
            }
            else if (function is WriteMultipleCoilsRequest)
            {
                var request = (WriteMultipleCoilsRequest)function;
                return(WriteMultipleCoils(request));
            }
            else if (function is WriteMultipleRegistersRequest)
            {
                var request = (WriteMultipleRegistersRequest)function;
                return(WriteMultipleRegisters(request));
            }

            throw new Exception("Function Not Support");
        }
Ejemplo n.º 19
0
        public void InitCtrl()
        {
            ModbusFunction functions = new ModbusFunction();
            ModbusData     DataType  = new ModbusData();

            cbo_functioncode.Items.Clear();
            for (int i = 0; i < functions.Functions.Count; i++)
            {
                cbo_functioncode.Items.Add(functions.Functions[i]);
            }
            cbo_functioncode.SelectedIndexChanged += Cbo_functioncode_SelectedIndexChanged;
            cbo_StoreType.Items.Clear();
            cbo_StoreType.SelectedIndexChanged += Cbo_StoreType_SelectedIndexChanged;
            for (int i = 0; i < DataType.DataTypes.Count; i++)
            {
                cbo_StoreType.Items.Add(DataType.DataTypes[i]);
            }
            cbo_StoreType.SelectedIndex = 0;
            cbo_datatype.SelectedIndex  = 0;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Method that is executed when read button is clicked on control window;
        /// Method should create read command parameters and provide it to FunctionFactory
        /// </summary>
        /// <param name="obj">Not used</param>
        private void ReadCommand_Execute(object obj)
        {
            try
            {
                ModbusReadCommandParameters para = null;

                switch (type)
                {
                case PointType.DIGITAL_OUTPUT:
                    para = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, address, 1);
                    break;

                case PointType.DIGITAL_INPUT:
                    para = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_DISCRETE_INPUTS, address, 1);
                    break;

                case PointType.ANALOG_INPUT:
                    para = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_INPUT_REGISTERS, address, 1);
                    break;

                case PointType.ANALOG_OUTPUT:
                    para = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, address, 1);
                    break;

                default:
                    break;
                }

                ModbusFunction fn = FunctionFactory.CreateModbusFunction(para);
                this.commandExecutor.EnqueueCommand(fn);
            }
            catch (Exception ex)
            {
                string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                this.stateUpdater.LogMessage(message);
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Method that is executed when write button is clicked on control window;
 /// Method should create write command parameters and provide it to FunctionFactory
 /// </summary>
 /// <param name="obj">Not used</param>
 private void WriteCommand_Execute(object obj)
 {
     try
     {
         ModbusWriteCommandParameters mwp = null;
         if (type == PointType.DIGITAL_OUTPUT)
         {
             mwp = new ModbusWriteCommandParameters(6, (byte)ModbusFunctionCode.WRITE_SINGLE_COIL, address, rawValue);
             ModbusFunction fn = FunctionFactory.CreateModbusFunction(mwp);
             this.commandExecutor.EnqueueCommand(fn);
         }
         else if (type == PointType.ANALOG_OUTPUT)
         {
             mwp = new ModbusWriteCommandParameters(6, (byte)ModbusFunctionCode.WRITE_SINGLE_REGISTER, address, rawValue);
             ModbusFunction fn = FunctionFactory.CreateModbusFunction(mwp);
             this.commandExecutor.EnqueueCommand(fn);
         }
     }
     catch (Exception ex)
     {
         string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
         this.stateUpdater.LogMessage(message);
     }
 }
Ejemplo n.º 22
0
        void Run(object obj)
        {
            var server = obj as Socket;

            if (server != null)
            {
                #region SocketConnected
                SocketConnected?.Invoke(this, new SocketEventArgs(server));
                #endregion

                List <byte> lstResponse = new List <byte>();
                var         prev        = DateTime.Now;
                var         chr         = new Chattering()
                {
                    ChatteringTime = DisconnectCheckTime
                };

                bool IsThStart = true;

                chr.StateChanged += (o, s) => { if (!s.Value)
                                                {
                                                    IsThStart = false;
                                                }
                };
                while (IsThStart)
                {
                    try
                    {
                        #region DataRead
                        if (server.Available > 0)
                        {
                            try
                            {
                                int n = server.Receive(baResponse);
                                for (int i = 0; i < n; i++)
                                {
                                    lstResponse.Add(baResponse[i]);
                                }
                                prev = DateTime.Now;
                            }
                            catch (TimeoutException) { }
                        }
                        #endregion

                        #region Modbus Parse
                        if (lstResponse.Count >= 10)
                        {
                            int            Slave        = lstResponse[6];
                            ModbusFunction Function     = (ModbusFunction)lstResponse[7];
                            int            StartAddress = (lstResponse[8] << 8) | lstResponse[9];

                            switch (Function)
                            {
                            case ModbusFunction.BITREAD_F1:
                            case ModbusFunction.BITREAD_F2:
                                #region BitRead
                                if (lstResponse.Count == 12)
                                {
                                    int Length = (lstResponse[10] << 8) | lstResponse[11];

                                    if (BitReadRequest != null)
                                    {
                                        var args = new BitReadRequestArgs(lstResponse.ToArray());
                                        BitReadRequest?.Invoke(this, args);

                                        if (args.Success && args.ResponseData != null && args.ResponseData.Length == args.Length)
                                        {
                                            #region MakeData
                                            List <byte> Datas = new List <byte>();
                                            int         nlen  = args.ResponseData.Length / 8;
                                            nlen += (args.ResponseData.Length % 8 == 0) ? 0 : 1;
                                            for (int i = 0; i < nlen; i++)
                                            {
                                                byte val = 0;
                                                for (int j = (i * 8), nTemp = 0; j < args.ResponseData.Length && j < (i * 8) + 8; j++, nTemp++)
                                                {
                                                    if (args.ResponseData[j])
                                                    {
                                                        val |= Convert.ToByte(Math.Pow(2, nTemp));
                                                    }
                                                }
                                                Datas.Add(val);
                                            }
                                            #endregion
                                            #region Write
                                            List <byte> ret = new List <byte>();
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add((byte)(((nlen + 3) & 0xFF00) >> 8));
                                            ret.Add((byte)(((nlen + 3) & 0x00FF)));
                                            ret.Add((byte)Slave);
                                            ret.Add((byte)Function);
                                            ret.Add((byte)Datas.Count);
                                            ret.AddRange(Datas.ToArray());

                                            byte[] send = ret.ToArray();
                                            server.Send(send);
                                            #endregion
                                        }
                                    }
                                    lstResponse.Clear();
                                }
                                #endregion
                                break;

                            case ModbusFunction.WORDREAD_F3:
                            case ModbusFunction.WORDREAD_F4:
                                #region WordRead
                                if (lstResponse.Count == 12)
                                {
                                    int Length = (lstResponse[10] << 8) | lstResponse[11];

                                    if (WordReadRequest != null)
                                    {
                                        var args = new WordReadRequestArgs(lstResponse.ToArray());
                                        WordReadRequest?.Invoke(this, args);

                                        if (args.Success && args.ResponseData != null && args.ResponseData.Length == args.Length)
                                        {
                                            #region MakeData
                                            List <byte> Datas = new List <byte>();
                                            for (int i = 0; i < args.ResponseData.Length; i++)
                                            {
                                                Datas.Add((byte)((args.ResponseData[i] & 0xFF00) >> 8));
                                                Datas.Add((byte)((args.ResponseData[i] & 0x00FF)));
                                            }
                                            #endregion
                                            #region Write
                                            int         nlen = Length * 2;
                                            List <byte> ret  = new List <byte>();
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add((byte)(((nlen + 3) & 0xFF00) >> 8));
                                            ret.Add((byte)(((nlen + 3) & 0x00FF)));
                                            ret.Add((byte)Slave);
                                            ret.Add((byte)Function);
                                            ret.Add((byte)Datas.Count);
                                            ret.AddRange(Datas.ToArray());

                                            byte[] send = ret.ToArray();
                                            server.Send(send);
                                            #endregion
                                        }
                                    }
                                    lstResponse.Clear();
                                }
                                #endregion
                                break;

                            case ModbusFunction.BITWRITE_F5:
                                #region BitWrite
                                if (lstResponse.Count == 12)
                                {
                                    int WriteValue = (lstResponse[10] << 8) | lstResponse[11];
                                    if (BitWriteRequest != null)
                                    {
                                        var args = new BitWriteRequestArgs(lstResponse.ToArray());
                                        BitWriteRequest?.Invoke(this, args);

                                        if (args.Success)
                                        {
                                            #region Write
                                            int         nv  = args.WriteValue ? 0xFF00 : 0;
                                            List <byte> ret = new List <byte>();
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(6);
                                            ret.Add((byte)Slave);
                                            ret.Add((byte)Function);
                                            ret.Add((byte)((StartAddress & 0xFF00) >> 8));
                                            ret.Add((byte)((StartAddress & 0x00FF)));
                                            ret.Add((byte)((nv & 0xFF00) >> 8));
                                            ret.Add((byte)((nv & 0x00FF)));

                                            byte[] send = ret.ToArray();
                                            server.Send(send);
                                            #endregion
                                        }
                                    }
                                    lstResponse.Clear();
                                }
                                #endregion
                                break;

                            case ModbusFunction.WORDWRITE_F6:
                                #region WordWrite
                                if (lstResponse.Count == 12)
                                {
                                    int WriteValue = (lstResponse[10] << 8) | lstResponse[11];

                                    if (WordWriteRequest != null)
                                    {
                                        var args = new WordWriteRequestArgs(lstResponse.ToArray());
                                        WordWriteRequest?.Invoke(this, args);

                                        if (args.Success)
                                        {
                                            #region Write
                                            List <byte> ret = new List <byte>();
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(6);
                                            ret.Add((byte)args.Slave);
                                            ret.Add((byte)args.Function);
                                            ret.Add((byte)((args.StartAddress & 0xFF00) >> 8));
                                            ret.Add((byte)((args.StartAddress & 0x00FF)));
                                            ret.Add((byte)((args.WriteValue & 0xFF00) >> 8));
                                            ret.Add((byte)((args.WriteValue & 0x00FF)));

                                            byte[] send = ret.ToArray();
                                            server.Send(send);
                                            #endregion
                                        }
                                    }
                                    lstResponse.Clear();
                                }
                                #endregion
                                break;

                            case ModbusFunction.MULTIBITWRITE_F15:
                                #region MultiBitWrite
                                if (lstResponse.Count >= 13)
                                {
                                    int ByteCount = lstResponse[12];
                                    if (lstResponse.Count >= 13 + ByteCount)
                                    {
                                        var args = new MultiBitWriteRequestArgs(lstResponse.ToArray());
                                        if (MultiBitWriteRequest != null)
                                        {
                                            MultiBitWriteRequest?.Invoke(this, args);

                                            if (args.Success)
                                            {
                                                #region Write
                                                List <byte> ret = new List <byte>();
                                                ret.Add(0);
                                                ret.Add(0);
                                                ret.Add(0);
                                                ret.Add(0);
                                                ret.Add(0);
                                                ret.Add(6);
                                                ret.Add((byte)args.Slave);
                                                ret.Add((byte)args.Function);
                                                ret.Add((byte)((args.StartAddress & 0xFF00) >> 8));
                                                ret.Add((byte)((args.StartAddress & 0x00FF)));
                                                ret.Add((byte)((args.Length & 0xFF00) >> 8));
                                                ret.Add((byte)((args.Length & 0x00FF)));

                                                byte[] send = ret.ToArray();
                                                server.Send(send);
                                                #endregion
                                            }
                                        }
                                        lstResponse.Clear();
                                    }
                                }
                                #endregion
                                break;

                            case ModbusFunction.MULTIWORDWRITE_F16:
                                #region MultiWordWrite
                                if (lstResponse.Count >= 13)
                                {
                                    int ByteCount = lstResponse[12];
                                    if (lstResponse.Count >= 13 + ByteCount)
                                    {
                                        if (MultiWordWriteRequest != null)
                                        {
                                            var args = new MultiWordWriteRequestArgs(lstResponse.ToArray());
                                            MultiWordWriteRequest?.Invoke(this, args);

                                            if (args.Success)
                                            {
                                                #region Write
                                                List <byte> ret = new List <byte>();
                                                ret.Add(0);
                                                ret.Add(0);
                                                ret.Add(0);
                                                ret.Add(0);
                                                ret.Add(0);
                                                ret.Add(6);
                                                ret.Add((byte)args.Slave);
                                                ret.Add((byte)args.Function);
                                                ret.Add((byte)((args.StartAddress & 0xFF00) >> 8));
                                                ret.Add((byte)((args.StartAddress & 0x00FF)));
                                                ret.Add((byte)((args.Length & 0xFF00) >> 8));
                                                ret.Add((byte)((args.Length & 0x00FF)));

                                                byte[] send = ret.ToArray();
                                                server.Send(send);
                                                #endregion
                                            }
                                        }
                                        lstResponse.Clear();
                                    }
                                }
                                #endregion
                                break;

                            case ModbusFunction.WORDBITSET_F26:
                                #region WordBitSet
                                if (lstResponse.Count == 13)
                                {
                                    if (WordBitSetRequest != null)
                                    {
                                        var args = new WordBitSetRequestArgs(lstResponse.ToArray());
                                        WordBitSetRequest?.Invoke(this, args);

                                        if (args.Success)
                                        {
                                            #region Write
                                            int         nv  = args.WriteValue ? 0xFF00 : 0;
                                            List <byte> ret = new List <byte>();
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(0);
                                            ret.Add(6);
                                            ret.Add((byte)args.Slave);
                                            ret.Add((byte)args.Function);
                                            ret.Add((byte)((args.StartAddress & 0xFF00) >> 8));
                                            ret.Add((byte)((args.StartAddress & 0x00FF)));
                                            ret.Add((byte)((nv & 0xFF00) >> 8));
                                            ret.Add((byte)((nv & 0x00FF)));

                                            byte[] send = ret.ToArray();
                                            server.Send(send);
                                            #endregion
                                        }
                                    }
                                    lstResponse.Clear();
                                }
                                #endregion
                                break;
                            }
                        }
                        #endregion

                        #region Buffer Clear
                        if ((DateTime.Now - prev).TotalMilliseconds >= 50 && lstResponse.Count > 0)
                        {
                            lstResponse.Clear();
                        }
                        #endregion

                        chr.Set(NetworkTool.IsSocketConnected(server));
                    }
                    catch (SocketException ex)
                    {
                        if (ex.SocketErrorCode == SocketError.TimedOut)
                        {
                        }
                        else if (ex.SocketErrorCode == SocketError.ConnectionReset)
                        {
                        }
                        else if (ex.SocketErrorCode == SocketError.ConnectionAborted)
                        {
                            IsThStart = false;
                        }
                    }
                    catch { }
                    Thread.Sleep(10);
                }

                #region Socket Closed
                if (server.Connected)
                {
                    server.Close();
                }
                SocketDisconnected?.Invoke(this, new SocketEventArgs(server));
                #endregion
            }
        }
Ejemplo n.º 23
0
        static async Task RunClientAsync()
        {
            //InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => true, false));

            ModbusClient client = new ModbusClient(0x01, "127.0.0.1");

            try
            {
                await client.Connect();

                while (true)
                {
                    Console.WriteLine(@"
<------------------------------------------------------->
1: Read Coils; 2: Read Discrete Inputs; 
3: Read Holding Registers; 4: Read Input Registers; 
5: Write Single Coil; 6: Write Single Register; 
15: Write Multiple Coils; 16: Write Multiple Registers;
<------------------------------------------------------->");
                    var line = Console.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        break;
                    }

                    Console.WriteLine("<------------------------------------------------------->");
                    var command = Convert.ToInt32(line);

                    ModbusFunction response        = null;
                    ushort         startingAddress = 0x0000;
                    ushort         quantity        = 0x000A;
                    var            state           = true;
                    ushort         value           = 0x0001;

                    switch (command)
                    {
                    case 1:
                        response = client.ReadCoils(startingAddress, quantity);
                        var coils = (response as ReadCoilsResponse).Coils;
                        for (int i = 0; i < quantity; i++)
                        {
                            Console.WriteLine(coils[i]);
                        }
                        break;

                    case 2:
                        response = client.ReadDiscreteInputs(startingAddress, quantity);
                        var inputs = (response as ReadDiscreteInputsResponse).Inputs;
                        for (int i = 0; i < quantity; i++)
                        {
                            Console.WriteLine(inputs[i]);
                        }
                        break;

                    case 3:
                        response = client.ReadHoldingRegisters(startingAddress, quantity);
                        foreach (var register in (response as ReadHoldingRegistersResponse).Registers)
                        {
                            Console.WriteLine(register);
                        }
                        break;

                    case 4:
                        response = client.ReadInputRegisters(startingAddress, quantity);
                        foreach (var register in (response as ReadInputRegistersResponse).Registers)
                        {
                            Console.WriteLine(register);
                        }
                        break;

                    case 5:
                        response = client.WriteSingleCoil(startingAddress, state);
                        Console.WriteLine((response as WriteSingleCoilResponse).State == state ? "Successed" : "Failed");
                        break;

                    case 6:
                        response = client.WriteSingleRegister(startingAddress, value);
                        Console.WriteLine((response as WriteSingleRegisterResponse).Value == value ? "Successed" : "Failed");
                        break;

                    case 15:
                        var states = new bool[] { true, true, true, true, true, true, true, true, true, true };
                        response = client.WriteMultipleCoils(startingAddress, states);
                        Console.WriteLine((response as WriteMultipleCoilsResponse).Quantity == states.Length);
                        break;

                    case 16:
                        var registers = new ushort[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
                        response = client.WriteMultipleRegisters(startingAddress, registers);
                        Console.WriteLine((response as WriteMultipleRegistersResponse).Quantity == registers.Length);
                        break;
                    }
                }

                await client.Close();

                Console.ReadLine();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }
Ejemplo n.º 24
0
 public void HandleCommandInProgress(ModbusFunction currentCommand)
 {
     LogMessage($"A {currentCommand.GetType().Name} command is in progress!");
 }
Ejemplo n.º 25
0
 /// <summary>
 /// 생성자
 /// </summary>
 /// <param name="slaveAddress">슬레이브 주소</param>
 /// <param name="function">Function</param>
 /// <param name="address">데이터 주소</param>
 protected ModbusRequest(byte slaveAddress, ModbusFunction function, ushort address)
 {
     SlaveAddress = slaveAddress;
     Function     = function;
     Address      = address;
 }
Ejemplo n.º 26
0
 /// <summary>
 /// 생성자
 /// </summary>
 /// <param name="slaveAddress">슬레이브 주소</param>
 /// <param name="function">Function</param>
 /// <param name="address">데이터 주소</param>
 protected ModbusWriteRequest(byte slaveAddress, ModbusFunction function, ushort address) : base(slaveAddress, function, address)
 {
 }
Ejemplo n.º 27
0
 public void HandleCommandInProgress(ModbusFunction currentCommand)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Acquisition thread
        ///		Awaits for trigger;
        ///		After configured period send appropriate command to MdbSim for each point type
        ///
        ///		Kao uslov za while petlju korititi acquisitionStopSignal da bi se akvizicioni thread ugasio kada se aplikacija ugasi
        /// </summary>
        private void Acquisition_DoWork()
        {
            try
            {
                ConfigReader reader = ConfigReader.Instance;
                int          AO, AO1, AI, AI1, DO, DO1, DI, DI1;
                AO = AO1 = reader.GetAcquisitionInterval("AnaOut");
                AI = AI1 = reader.GetAcquisitionInterval("AnaIn");
                DO = DO1 = reader.GetAcquisitionInterval("DigOut");
                DI = DI1 = reader.GetAcquisitionInterval("DigIn");

                int cnt = 0;
                ModbusReadCommandParameters mbParams = null;
                ModbusFunction fn = null;

                while (acquisitionStopSignal)
                {
                    if (cnt % AO == 0)
                    {
                        mbParams = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, reader.GetStartAddress("AnaOut"), reader.GetNumberOfRegisters("AnaOut"));
                        fn       = FunctionFactory.CreateModbusFunction(mbParams);
                        commandExecutor.EnqueueCommand(fn);
                    }
                    if (cnt % AO1 == 0)
                    {
                        mbParams = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, reader.GetStartAddress("AnaOut1"), reader.GetNumberOfRegisters("AnaOut1"));
                        fn       = FunctionFactory.CreateModbusFunction(mbParams);
                        commandExecutor.EnqueueCommand(fn);
                    }
                    if (cnt % AI == 0)
                    {
                        mbParams = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_INPUT_REGISTERS, reader.GetStartAddress("AnaIn"), reader.GetNumberOfRegisters("AnaIn"));
                        fn       = FunctionFactory.CreateModbusFunction(mbParams);
                        commandExecutor.EnqueueCommand(fn);
                    }
                    if (cnt % AI1 == 0)
                    {
                        mbParams = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_INPUT_REGISTERS, reader.GetStartAddress("AnaIn1"), reader.GetNumberOfRegisters("AnaIn1"));
                        fn       = FunctionFactory.CreateModbusFunction(mbParams);
                        commandExecutor.EnqueueCommand(fn);
                    }
                    if (cnt % DO == 0)
                    {
                        mbParams = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, reader.GetStartAddress("DigOut"), reader.GetNumberOfRegisters("DigOut"));
                        fn       = FunctionFactory.CreateModbusFunction(mbParams);
                        commandExecutor.EnqueueCommand(fn);
                    }
                    if (cnt % DO1 == 0)
                    {
                        mbParams = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, reader.GetStartAddress("DigOut1"), reader.GetNumberOfRegisters("DigOut1"));
                        fn       = FunctionFactory.CreateModbusFunction(mbParams);
                        commandExecutor.EnqueueCommand(fn);
                    }
                    if (cnt % DI == 0)
                    {
                        mbParams = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_DISCRETE_INPUTS, reader.GetStartAddress("DigIn"), reader.GetNumberOfRegisters("DigIn"));
                        fn       = FunctionFactory.CreateModbusFunction(mbParams);
                        commandExecutor.EnqueueCommand(fn);
                    }
                    if (cnt % DI1 == 0)
                    {
                        mbParams = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_DISCRETE_INPUTS, reader.GetStartAddress("DigIn1"), reader.GetNumberOfRegisters("DigIn1"));
                        fn       = FunctionFactory.CreateModbusFunction(mbParams);
                        commandExecutor.EnqueueCommand(fn);
                    }

                    try
                    {
                        ++cnt;
                        acquisitionTrigger.WaitOne();
                    }
                    catch (Exception ex)
                    {
                        string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                        stateUpdater.LogMessage(message);
                    }
                } // end while
            }
            catch (Exception ex)
            {
                string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                stateUpdater.LogMessage(message);
            }
        }
Ejemplo n.º 29
0
        internal override ModbusRequest DeserializeRequest(RequestBuffer buffer)
        {
            ModbusRequest result = null;

            while (!buffer.Channel.IsDisposed)
            {
                if (errorBuffer.Count >= 256)
                {
                    RaiseUnrecognized(buffer.Channel, errorBuffer.ToArray());
                    errorBuffer.Clear();
                }

                while (buffer.Count < 8 && !buffer.Channel.IsDisposed)
                {
                    buffer.Read();
                }

                if (buffer.Channel.IsDisposed)
                {
                    break;
                }

                var slaveAddress  = buffer[0];
                int messageLength = 0;

                if (buffer.ModbusSlave.IsValidSlaveAddress(slaveAddress, buffer.Channel) &&
                    Enum.IsDefined(typeof(ModbusFunction), buffer[1]))
                {
                    ModbusFunction function      = (ModbusFunction)buffer[1];
                    var            address       = ToUInt16(buffer, 2);
                    var            valueOrLength = ToUInt16(buffer, 4);

                    switch (function)
                    {
                    case ModbusFunction.ReadCoils:
                    case ModbusFunction.ReadDiscreteInputs:
                    case ModbusFunction.ReadHoldingRegisters:
                    case ModbusFunction.ReadInputRegisters:
                    case ModbusFunction.WriteSingleCoil:
                    case ModbusFunction.WriteSingleHoldingRegister:
                        if (CalculateCrc(buffer.Take(6)).SequenceEqual(buffer.Skip(6).Take(2)))
                        {
                            messageLength = 8;
                            switch (function)
                            {
                            case ModbusFunction.ReadCoils:
                            case ModbusFunction.ReadDiscreteInputs:
                            case ModbusFunction.ReadHoldingRegisters:
                            case ModbusFunction.ReadInputRegisters:
                                result = new ModbusReadRequest(slaveAddress, (ModbusObjectType)(byte)function, address, valueOrLength);
                                break;

                            case ModbusFunction.WriteSingleCoil:
                                if (valueOrLength != 0xff00 && valueOrLength != 0)
                                {
                                    result = new ModbusWriteCoilRequest(slaveAddress, address);
                                }
                                else
                                {
                                    result = new ModbusWriteCoilRequest(slaveAddress, address, valueOrLength == 0xff00);
                                }
                                break;

                            case ModbusFunction.WriteSingleHoldingRegister:
                                result = new ModbusWriteHoldingRegisterRequest(slaveAddress, address, valueOrLength);
                                break;
                            }
                        }
                        break;

                    case ModbusFunction.WriteMultipleCoils:
                    case ModbusFunction.WriteMultipleHoldingRegisters:
                        if (buffer.Count < 7 && !buffer.Channel.IsDisposed)
                        {
                            buffer.Read();
                        }

                        if (buffer.Channel.IsDisposed)
                        {
                            break;
                        }

                        var byteLength = buffer[6];
                        messageLength = byteLength + 9;

                        if (function == ModbusFunction.WriteMultipleCoils && byteLength == Math.Ceiling(valueOrLength / 8d) ||
                            function == ModbusFunction.WriteMultipleHoldingRegisters && byteLength == valueOrLength * 2)
                        {
                            while (buffer.Count < messageLength && !buffer.Channel.IsDisposed)
                            {
                                buffer.Read();
                            }

                            if (buffer.Channel.IsDisposed)
                            {
                                break;
                            }

                            if (CalculateCrc(buffer.Take(byteLength + 7)).SequenceEqual(buffer.Skip(byteLength + 7).Take(2)))
                            {
                                switch (function)
                                {
                                case ModbusFunction.WriteMultipleCoils:
                                    result = new ModbusWriteCoilRequest(slaveAddress, address, buffer.Skip(7).Take(byteLength).SelectMany(b => ByteToBooleanArray(b)).Take(valueOrLength).ToArray());
                                    break;

                                case ModbusFunction.WriteMultipleHoldingRegisters:
                                    result = new ModbusWriteHoldingRegisterRequest(slaveAddress, address, buffer.Skip(7).Take(byteLength).ToArray());
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }

                if (result != null)
                {
                    if (errorBuffer.Count > 0)
                    {
                        RaiseUnrecognized(buffer.Channel, errorBuffer.ToArray());
                        errorBuffer.Clear();
                    }
                    return(result);
                }
                else
                {
                    errorBuffer.Add(buffer[0]);
                    buffer.RemoveAt(0);
                    continue;
                }
            }
            return(null);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Acquisition thread
        ///		Awaits for trigger;
        ///		After configured period send appropriate command to MdbSim for each point type
        /// </summary>
        private void Acquisition_DoWork()
        {
            int cnt = 0;

            ConfigReader cr = ConfigReader.Instance;

            int DOcnt1 = cr.GetAcquisitionInterval("DigOut1");
            int DOcnt2 = cr.GetAcquisitionInterval("DigOut2");

            int DIcnt1 = cr.GetAcquisitionInterval("DigIn1");
            int DIcnt2 = cr.GetAcquisitionInterval("DigIn2");

            int AOcnt1 = cr.GetAcquisitionInterval("AnaOut1");
            int AOcnt2 = cr.GetAcquisitionInterval("AnaOut2");

            int AIcnt1 = cr.GetAcquisitionInterval("AnaIn1");
            int AIcnt2 = cr.GetAcquisitionInterval("AnaIn2");

            while (true)
            {
                if (cnt % DOcnt1 == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, cr.GetStartAddress("DigOut1"), cr.GetNumberOfRegisters("DigOut1"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }
                if (cnt % DOcnt2 == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_COILS, cr.GetStartAddress("DigOut2"), cr.GetNumberOfRegisters("DigOut2"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }
                if (cnt % DIcnt1 == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_DISCRETE_INPUTS, cr.GetStartAddress("DigIn1"), cr.GetNumberOfRegisters("DigIn1"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }
                if (cnt % DIcnt2 == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_DISCRETE_INPUTS, cr.GetStartAddress("DigIn2"), cr.GetNumberOfRegisters("DigIn2"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }
                if (cnt % AOcnt1 == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, cr.GetStartAddress("AnaOut1"), cr.GetNumberOfRegisters("AnaOut1"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }
                if (cnt % AOcnt2 == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_HOLDING_REGISTERS, cr.GetStartAddress("AnaOut2"), cr.GetNumberOfRegisters("AnaOut2"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }
                if (cnt % AIcnt1 == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_INPUT_REGISTERS, cr.GetStartAddress("AnaIn1"), cr.GetNumberOfRegisters("AnaIn1"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }
                if (cnt % AIcnt2 == 0)
                {
                    ModbusReadCommandParameters mcp = new ModbusReadCommandParameters(6, (byte)ModbusFunctionCode.READ_INPUT_REGISTERS, cr.GetStartAddress("AnaIn2"), cr.GetNumberOfRegisters("AnaIn2"));
                    ModbusFunction mf = FunctionFactory.CreateModbusFunction(mcp);
                    this.commandExecutor.EnqueueCommand(mf);
                }

                try
                {
                    cnt++;
                    // TODO implement
                    acquisitionTrigger.WaitOne();
                }
                catch (Exception ex)
                {
                    string message = $"{ex.TargetSite.ReflectedType.Name}.{ex.TargetSite.Name}: {ex.Message}";
                    stateUpdater.LogMessage(message);
                }
            }
        }