Пример #1
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        /// <exception cref="System.Exception">Invalid configuration : you have to set the TcpAddress/TcpPort settings for Modbus TCP or RtuSerialPort's setting for Modbus RTU !</exception>
        public override void OnStart()
        {
            // Create the Modbus client
            if (PackageHost.ContainsSetting("TcpAddress") && PackageHost.ContainsSetting("TcpPort"))
            {
                // Modbus TCP
                this.modbusClient = new ModbusClient(PackageHost.GetSettingValue("TcpAddress"), PackageHost.GetSettingValue <int>("TcpPort"));
            }
            else if (PackageHost.ContainsSetting("RtuSerialPort"))
            {
                // Modbus RTU
                this.modbusClient = new ModbusClient(PackageHost.GetSettingValue("RtuSerialPort"))
                {
                    Baudrate = PackageHost.GetSettingValue <int>("RtuBaudRate")
                };
            }
            else
            {
                // Invalid configuration !
                throw new Exception("Invalid configuration : you have to set the TcpAddress/TcpPort settings for Modbus TCP or RtuSerialPort's setting for Modbus RTU !");
            }

            // Load and register device definitions
            List <ModbusDeviceDefinition> modbusDevicesDefintions = LoadModbusDevicesDefinitions();

            // Load Modbus devices to request
            this.LoadDevices(modbusDevicesDefintions);

            // Client connection
            this.modbusClient.ConnectedChanged += ModbusClient_ConnectedChanged;
            this.modbusClient.Connect();

            // Start the backgroup task
            if (this.deviceStates.Count > 0)
            {
                Task.Factory.StartNew(async() =>
                {
                    int estimatedTotalReadingTime = (int)Math.Round((decimal)deviceStates.Sum(d => d.Definition.Properties.Count) / (decimal)AVG_REGISTER_READ_PER_SECOND);
                    while (PackageHost.IsRunning)
                    {
                        // For each device to poll
                        foreach (DeviceState device in this.deviceStates)
                        {
                            // Need to request ?
                            if (this.modbusClient.Connected && DateTime.Now.Subtract(device.LastUpdate).TotalSeconds >= device.Device.RequestInterval)
                            {
                                PackageHost.WriteLog(PackageHost.GetSettingValue <bool>("Verbose") ? LogLevel.Info : LogLevel.Debug, $"Requesting {device.Device}...");
                                try
                                {
                                    // Set the Slave ID
                                    modbusClient.UnitIdentifier = device.Device.SlaveID;
                                    // Create the result object
                                    dynamic result = new ExpandoObject();
                                    var resultDict = result as IDictionary <string, object>;
                                    // For each property for the device
                                    foreach (var property in device.Definition.Properties)
                                    {
                                        int attempt = 0;
                                        // Attempt the read the register
                                        while (this.modbusClient.Connected && ++attempt <= this.modbusClient.NumberOfRetries && !resultDict.ContainsKey(property.Name))
                                        {
                                            PackageHost.WriteLog(PackageHost.GetSettingValue <bool>("Verbose") ? LogLevel.Info : LogLevel.Debug, $"Reading {property.Name} ({property.Address})");
                                            try
                                            {
                                                // Read register from the modbus client
                                                int[] datas = null;
                                                lock (syncLock)
                                                {
                                                    datas = property.RegisterType == ModbusDeviceDefinition.RegisterType.Holding ?
                                                            modbusClient.ReadHoldingRegisters(Convert.ToInt32(property.Address, 16), property.Length) :
                                                            modbusClient.ReadInputRegisters(Convert.ToInt32(property.Address, 16), property.Length);
                                                }
                                                // Boolean type
                                                if (property.Type == ModbusDeviceDefinition.PropertyType.Boolean)
                                                {
                                                    resultDict[property.Name] = datas[0] == 1;
                                                }
                                                else
                                                {
                                                    // Raw value
                                                    int rawValue = datas.Length == 1 ? unchecked ((ushort)datas[0]) : ((unchecked ((ushort)datas[0]) << 16) + unchecked ((ushort)datas[1]));

                                                    // Apply the ratio and set the result
                                                    resultDict[property.Name] = (float)(rawValue * property.Ratio);
                                                    // Trucate Integer property
                                                    if (property.Type == ModbusDeviceDefinition.PropertyType.Int)
                                                    {
                                                        resultDict[property.Name] = (int)(float)resultDict[property.Name];
                                                    }
                                                }
                                                PackageHost.WriteLog(PackageHost.GetSettingValue <bool>("Verbose") ? LogLevel.Info : LogLevel.Debug, $"* {property.Name} ({property.Address}) = {resultDict[property.Name]}");
                                            }
                                            catch (IOException ex) when(ex.InnerException is SocketException socketError && socketError.SocketErrorCode == SocketError.TimedOut)
                                            {
                                                PackageHost.WriteLog(PackageHost.GetSettingValue <bool>("Verbose") ? LogLevel.Error : LogLevel.Debug, $"* {property.Name} ({property.Address}) = no response !");
                                                // First polling and no answer ?
                                                if (device.LastUpdate == DateTime.MinValue && resultDict.Count == 0)
                                                {
                                                    // Invalid slave Id ?
                                                    break;
                                                }
                                                // Otherwise, check the connection
                                                else if (this.modbusClient.IPAddress != null && !this.modbusClient.Available(PackageHost.GetSettingValue <int>("ConnectionTimeout")))
                                                {
                                                    PackageHost.WriteError("Connection timeout !");
                                                    this.modbusClient.Disconnect();
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                if (++attempt > this.modbusClient.NumberOfRetries)
                                                {
                                                    // Unable to read the register, log and set the default value
                                                    resultDict[property.Name] = Activator.CreateInstance(property.GetCLRType());
                                                    PackageHost.WriteLog(PackageHost.GetSettingValue <bool>("Verbose") ? LogLevel.Error : LogLevel.Debug, $"Unable to read the property {property.Name} ({property.Address}h) of {device.Device} : {ex.Message}");
                                                }
                                            }
                                        }
                                    }
                                    // Check result
                                    if (device.Definition.Properties.Count == resultDict.Count)
                                    {
                                        // Push the StateObject
                                        PackageHost.PushStateObject(device.Device.Name, result,
                                                                    type: $"Modbus.{device.Definition.Name}",
                                                                    lifetime: (estimatedTotalReadingTime + device.Device.RequestInterval) * 2,
                                                                    metadatas: new Dictionary <string, object>
                                        {
                                            ["SlaveID"] = device.Device.SlaveID
                                        });
                                        // Done !
                                        device.LastUpdate = DateTime.Now;
                                        PackageHost.WriteLog(PackageHost.GetSettingValue <bool>("Verbose") ? LogLevel.Info : LogLevel.Debug, $"{device.Device} is done!");
                                    }
                                    else if (resultDict.Count == 0 && device.LastUpdate == DateTime.MinValue)
                                    {
                                        // Exclude device!
                                        device.LastUpdate = DateTime.MaxValue;
                                        PackageHost.WriteWarn($"Unable to poll {device.Device}, no response. This device will be ignored !");
                                    }
                                    else
                                    {
                                        // Missing properties !
                                        PackageHost.WriteError($"Unable to retrieve all defined registers for the device {device.Device}. The StateObject will not be updated !");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    PackageHost.WriteError($"Error to request {device.Device} : {ex.Message}");
                                }
                            }
                            else if (!this.modbusClient.Connected)
                            {
                                try
                                {
                                    PackageHost.WriteInfo("Trying to reconnect ...");
                                    this.modbusClient.Connect();
                                }
                                catch (Exception ex)
                                {
                                    PackageHost.WriteError($"Unable to reconnect : {ex.Message}. Next retry in {this.reconnectionGraceTime} seconds.");
                                    await Task.Delay(this.reconnectionGraceTime * 1000);
                                    this.reconnectionGraceTime = (this.reconnectionGraceTime * 2) > PackageHost.GetSettingValue <int>("ReconnectionMaxInterval") ? PackageHost.GetSettingValue <int>("ReconnectionMaxInterval") : this.reconnectionGraceTime * 2;
                                }
                            }
                            await Task.Delay(500);
                        }
                        await Task.Delay(10);
                    }
                });
            }
        }