public void GetValues(ConnectionProperties connectionProperties)
        {
            modbusClient = connectionProperties.modbusClient;
            if (!modbusClient.Connected)
            {
                modbusClient.IPAddress = connectionProperties.ModbusTCPAddress;
                modbusClient.Port      = connectionProperties.Port;
                modbusClient.Connect();
            }
            foreach (FunctionProperties functionProperty in connectionProperties.FunctionPropertiesList)
            {
                switch (functionProperty.FunctionCodeRead)
                {
                case FunctionCodeRd.ReadCoils:
                    functionProperty.values = modbusClient.ReadCoils(functionProperty.StartingAdress, functionProperty.Quantity);
                    break;

                case FunctionCodeRd.ReadDiscreteInputs:
                    functionProperty.values = modbusClient.ReadDiscreteInputs(functionProperty.StartingAdress, functionProperty.Quantity);
                    break;

                case FunctionCodeRd.ReadHoldingRegisters:
                    functionProperty.values = modbusClient.ReadHoldingRegisters(functionProperty.StartingAdress, functionProperty.Quantity);
                    break;

                case FunctionCodeRd.ReadInputRegisters:
                    functionProperty.values = modbusClient.ReadInputRegisters(functionProperty.StartingAdress, functionProperty.Quantity);
                    break;

                default: break;
                }
            }
            if (valuesChanged != null)
            {
                valuesChanged(this);
            }
        }
Example #2
0
        public async Task RunningAsync(CancellationToken cancellationToken)
        {
            DateTime triggerTime = DateTime.MinValue;

            InitializeModbus(ref pvClient, pvmodbusConfig);
            InitializeModbus(ref essClient, essmodbusConfig);
            while (true)
            {
                //if (triggerTime > DateTime.Now)
                //    continue;
                //triggerTime = DateTime.Now.Add(modbusConfig.Interval);

                cancellationToken.ThrowIfCancellationRequested();
                try
                {
                    Task[] client_access_task = new Task[]
                    {
                        TryConnect(pvClient, cancellationToken),
                        TryConnect(essClient, cancellationToken)
                    };
                    Task.WaitAll(client_access_task);


                    int[] ess_read_values = essClient.ReadInputRegisters(28, 30);
                    int[] pv_read_values  = pvClient.ReadInputRegisters(28, 16);

                    //int[] trms = pvClient.ReadInputRegisters(538, 2);

                    //float trms_value = EasyModbus.ModbusClient.ConvertRegistersToFloat(new int[] { trms[0], trms[1] });
                    //logger.Info($"trms_value = {trms_value}");

                    float pcs_freq;
                    float pcs_actPwr;
                    float pcs_rctPwr;
                    float pcs_appPwr;
                    float pcs_act_forward_high;
                    float pcs_act_forward_low;

                    float pcs_act_reverse_high;
                    float pcs_act_reverse_low;

                    float pv_freq;
                    float pv_actPwr;
                    float pv_rctPwr;
                    float pv_appPwr;
                    float pv_act_forward_high;
                    float pv_act_forward_low;

                    ReadValues(ess_read_values, out pcs_freq, out pcs_actPwr, out pcs_rctPwr, out pcs_appPwr, out pcs_act_forward_high, out pcs_act_forward_low, out pcs_act_reverse_high, out pcs_act_reverse_low);
                    ReadValues(pv_read_values, out pv_freq, out pv_actPwr, out pv_rctPwr, out pv_appPwr, out pv_act_forward_high, out pv_act_forward_low);

                    double pv_accum = pv_act_forward_high + (pv_act_forward_low / 10000);

                    double ess_total_chg = pcs_act_forward_high + (pcs_act_forward_low / 10000);
                    double ess_total_dhg = pcs_act_reverse_high + (pcs_act_reverse_low / 10000);

                    Console.WriteLine("High: " + pv_act_forward_high + " log: " + pv_act_forward_low + " accum: " + pv_accum);

                    await InsertDbAsync(pcs_freq, pv_actPwr, pv_accum, pcs_actPwr, ess_total_chg, ess_total_dhg, DateTime.Now, cancellationToken);

                    //await PublishEvent(freq, actPwr, rctPwr, appPwr, act_forward_high, act_forward_low, DateTime.Now, cancellationToken);
                    await Task.Delay(essmodbusConfig.Interval, cancellationToken);
                }
                catch (Exception ex)
                {
                    logger.Error(ex, ex.Message);
                    essClient.Disconnect();
                    pvClient.Disconnect();
                }
            }
        }
Example #3
0
        private void ProcessData(object param)
        {
            while (!shouldStop)
            {
                ReadOrder readOrder = (ReadOrder)param;
                lock (lockProcessData)
                {
                    if (readOrder.FunctionCode == FunctionCode.ReadCoils)
                    {
                        bool[] value = modbusClient.ReadCoils(readOrder.StartingAddress, readOrder.Quantity);
                        for (int i = 0; i < value.Length; i++)
                        {
                            if (readOrder.oldvalue[i] == null)
                            {
                                mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                            }
                            else if ((bool)readOrder.oldvalue[i] != value[i])
                            {
                                mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                            }
                            readOrder.oldvalue[i] = value[i];
                        }
                    }
                    if (readOrder.FunctionCode == FunctionCode.ReadDiscreteInputs)
                    {
                        bool[] value = modbusClient.ReadDiscreteInputs(readOrder.StartingAddress, readOrder.Quantity);
                        for (int i = 0; i < value.Length; i++)
                        {
                            if (readOrder.oldvalue[i] == null)
                            {
                                mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                            }
                            else if ((bool)readOrder.oldvalue[i] != value[i])
                            {
                                mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                            }
                            readOrder.oldvalue[i] = value[i];
                        }
                    }
                    if (readOrder.FunctionCode == FunctionCode.ReadHoldingRegisters)
                    {
                        int[] value = modbusClient.ReadHoldingRegisters(readOrder.StartingAddress, readOrder.Quantity);
                        for (int i = 0; i < value.Length; i++)
                        {
                            if (readOrder.oldvalue[i] == null)
                            {
                                mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                            }
                            else if ((int)readOrder.oldvalue[i] != value[i])
                            {
                                mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                            }
                            readOrder.oldvalue[i] = value[i];
                        }
                    }

                    if (readOrder.FunctionCode == FunctionCode.ReadInputRegisters)
                    {
                        int[] value = modbusClient.ReadInputRegisters(readOrder.StartingAddress, readOrder.Quantity);
                        for (int i = 0; i < value.Length; i++)
                        {
                            if (readOrder.oldvalue[i] == null)
                            {
                                mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                            }
                            else if ((int)readOrder.oldvalue[i] != value[i])
                            {
                                mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                            }
                            readOrder.oldvalue[i] = value[i];
                        }
                    }
                }
                System.Threading.Thread.Sleep(readOrder.CylceTime);
            }
        }
Example #4
0
        private void ProcessData(object param)
        {
            while (!shouldStop)
            {
                try
                {
                    if (!mqttClient.IsConnected)
                    {
                        mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None);
                        string clientID = Guid.NewGuid().ToString();
                        if (MqttUserName == null || MqttPassword == null)
                        {
                            mqttClient.Connect(clientID);
                        }
                        else
                        {
                            mqttClient.Connect(clientID, MqttUserName, MqttPassword);
                        }
                    }
                }
                catch (Exception exc)
                {
                    if (!this.AutomaticReconnect)
                    {
                        throw exc;
                    }
                }
                ReadOrder readOrder = (ReadOrder)param;
                lock (lockProcessData)
                {
                    try
                    {
                        if (readOrder.FunctionCode == FunctionCode.ReadCoils)
                        {
                            bool[] value = modbusClient.ReadCoils(readOrder.StartingAddress, readOrder.Quantity);
                            for (int i = 0; i < value.Length; i++)
                            {
                                if (readOrder.oldvalue[i] == null)
                                {
                                    mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                }
                                else if ((bool)readOrder.oldvalue[i] != value[i])
                                {
                                    mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                }
                                readOrder.oldvalue[i] = value[i];
                            }
                        }
                        if (readOrder.FunctionCode == FunctionCode.ReadDiscreteInputs)
                        {
                            bool[] value = modbusClient.ReadDiscreteInputs(readOrder.StartingAddress, readOrder.Quantity);
                            for (int i = 0; i < value.Length; i++)
                            {
                                if (readOrder.oldvalue[i] == null)
                                {
                                    mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                }
                                else if ((bool)readOrder.oldvalue[i] != value[i])
                                {
                                    mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                }
                                readOrder.oldvalue[i] = value[i];
                            }
                        }
                        if (readOrder.FunctionCode == FunctionCode.ReadHoldingRegisters)
                        {
                            int[] value = modbusClient.ReadHoldingRegisters(readOrder.StartingAddress, readOrder.Quantity);
                            for (int i = 0; i < value.Length; i++)
                            {
                                float scale = readOrder.Scale != null ? (readOrder.Scale[i] == 0) ? 1 : readOrder.Scale[i] : 1;
                                if (readOrder.oldvalue[i] == null)
                                {
                                    mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale) + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                    readOrder.oldvalue[i] = value[i];
                                }
                                else if (((int)readOrder.oldvalue[i] != value[i]) && (readOrder.Hysteresis != null ? ((value[i] < (int)readOrder.oldvalue[i] - (int)readOrder.Hysteresis[i]) | (value[i] > (int)readOrder.oldvalue[i] + (int)readOrder.Hysteresis[i])) : true))
                                {
                                    mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                    readOrder.oldvalue[i] = value[i];
                                }
                            }
                        }

                        if (readOrder.FunctionCode == FunctionCode.ReadInputRegisters)
                        {
                            int[] value = modbusClient.ReadInputRegisters(readOrder.StartingAddress, readOrder.Quantity);
                            for (int i = 0; i < value.Length; i++)
                            {
                                float scale = readOrder.Scale != null ? (readOrder.Scale[i] == 0) ? 1 : readOrder.Scale[i] : 1;
                                if (readOrder.oldvalue[i] == null)
                                {
                                    mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                    readOrder.oldvalue[i] = value[i];
                                }
                                else if (((int)readOrder.oldvalue[i] != value[i]) && (readOrder.Hysteresis != null ? ((value[i] < (int)readOrder.oldvalue[i] - (int)readOrder.Hysteresis[i]) | (value[i] > (int)readOrder.oldvalue[i] + (int)readOrder.Hysteresis[i])) : true))
                                {
                                    mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                    readOrder.oldvalue[i] = value[i];
                                }
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        modbusClient.Disconnect();
                        Thread.Sleep(2000);
                        if (!AutomaticReconnect)
                        {
                            throw exc;
                        }
                        if (!modbusClient.Connected)
                        {
                            try
                            {
                                modbusClient.Connect();
                            }
                            catch (Exception) { }
                        }
                    }
                }
                System.Threading.Thread.Sleep(readOrder.CylceTime);
            }
        }
Example #5
0
        void inputRegToGUI()
        {
            if (textBox1.InvokeRequired)
            {
                inputRegToGUIDelegate d = new inputRegToGUIDelegate(inputRegToGUI);
                this.Invoke(d, new object[] { });
            }
            else
            {
                try
                {
                    /* --- Fetch server response --- */
                    int[] serverResponse = modbusClient.ReadInputRegisters(INPUT_REG_START - 1, INPUT_REG_NUM_REGS);

                    /* --- Voltages battery 0 to 3 --- */
                    string[] log_data = new string[10];

                    log_data[0]   = ConversionUtils.trueBatVoltsFromADC(ConversionUtils.adcValueFromScaled((ushort)serverResponse[0])).ToString();
                    textBox1.Text = log_data[0];
                    log_data[1]   = ConversionUtils.trueBatVoltsFromADC(ConversionUtils.adcValueFromScaled((ushort)serverResponse[1])).ToString();
                    textBox2.Text = log_data[1];
                    log_data[2]   = ConversionUtils.trueBatVoltsFromADC(ConversionUtils.adcValueFromScaled((ushort)serverResponse[2])).ToString();
                    textBox3.Text = log_data[2];
                    log_data[3]   = ConversionUtils.trueBatVoltsFromADC(ConversionUtils.adcValueFromScaled((ushort)serverResponse[3])).ToString();
                    textBox4.Text = log_data[3];
                    /* --- Voltage solar --- */
                    log_data[4]   = ConversionUtils.trueSolarVoltsFromADC(ConversionUtils.adcValueFromScaled((ushort)serverResponse[4])).ToString();
                    textBox5.Text = log_data[4];
                    /* --- Current solar --- */
                    log_data[5] = ConversionUtils.trueCurrentFromADC(ConversionUtils.adcValueFromScaled((ushort)serverResponse[5]),
                                                                     ConversionUtils.RS_PV_CHARGE, ConversionUtils.RL_PV_CHARGE).ToString();
                    textBox6.Text = log_data[5];
                    /* --- Current charging --- */
                    log_data[6] = ConversionUtils.trueCurrentFromADC(ConversionUtils.adcValueFromScaled((ushort)serverResponse[6]),
                                                                     ConversionUtils.RS_PV_CHARGE, ConversionUtils.RL_PV_CHARGE).ToString();
                    textBox7.Text = log_data[6];
                    /* --- Current load --- */
                    log_data[7] = ConversionUtils.trueCurrentFromADC(ConversionUtils.adcValueFromScaled((ushort)serverResponse[7]),
                                                                     ConversionUtils.RS_LOAD, ConversionUtils.RL_LOAD).ToString();
                    textBox8.Text = log_data[7];
                    /* --- Active and charging states --- */
                    setActiveChkbx((int)serverResponse[8]);
                    log_data[8] = ((int)serverResponse[8]).ToString();
                    Debug.WriteLine("Active battery: " + ((int)serverResponse[8]).ToString());
                    setChargeChkbx((int)serverResponse[9]);
                    Debug.WriteLine("Charging battery: " + ((int)serverResponse[9]).ToString());
                    log_data[9] = ((int)serverResponse[9]).ToString();

                    /* Maybe also calculate the power consume of the system. */

                    /* Write to system log */
                    DataLogging.WriteDataToLog(log_data);

                    Debug.Write("Wrote data to log file\n");

                    int[] holdingServerRsp = modbusClient.ReadHoldingRegisters(HOLDING_REG_START - 1, HOLDING_REG_NUM_REGS);
                    updateCurrentSettings(holdingServerRsp);

                    if ((ushort)holdingServerRsp[8] == 1)
                    {
                        throw new EmergencyStopException();
                    }
                }
                catch (EmergencyStopException esexc)
                {
                    if (CYCLIC_READ)
                    {
                        CYCLIC_READ             = false;
                        btnCyclicRead.Text      = "Start Cyclic Read";
                        btnCyclicRead.BackColor = Color.Plum;
                        btnRead1.Enabled        = true;
                    }

                    alertEmergencyStop();
                }
                catch (Exception exc)
                {
                    Debug.WriteLine("Exception Reading values from Server.");

                    // Print error message
                    txtComErrors.Text = "No response from server. Sure you're connected?";

                    txtConnectState.Text      = "MODBUS not connected";
                    txtConnectState.BackColor = Color.Red;

                    if (CYCLIC_READ)
                    {
                        CYCLIC_READ             = false;
                        btnCyclicRead.Text      = "Start Cyclic Read";
                        btnCyclicRead.BackColor = Color.Plum;
                        btnRead1.Enabled        = true;
                    }
                }
            }
        }