Ejemplo n.º 1
0
        public async Task <TelemetryPoint> GetDataAsync()
        {
            string  iotHubDeviceId = AppSettings.iotHubDeviceId;
            decimal temperature;

            float[] analogInput;
            bool[]  digitalInput;

            try
            {
                if (!modbusClientAlive)
                {
                    modbusClient = new ModbusClient(
                        AppSettings.modbusHost,
                        AppSettings.modbusPort);
                    modbusClient.Init();
                    modbusClientAlive = true;
                }

                analogInput = await modbusClient.ReadRegistersFloatsAsync(
                    AppSettings.temperatureInputOffset,
                    AppSettings.temperatureInputCount,
                    AppSettings.unitIdentifier);

                temperature = decimal.Round(
                    (decimal)analogInput[0], 3); // 3 decimals

                digitalInput = await modbusClient.ReadInputStatusAsync(
                    AppSettings.digitalInputOffset, // 10001 + offset
                    AppSettings.digitalInputCount,
                    AppSettings.unitIdentifier);
            }
            catch (Exception ex)
            {
                Misc.LogException($"Exception while calling ReadRegistersAsync(): {ex.Message}\n" +
                                  $"Stack Trace --\n{ex.StackTrace}");
                modbusClientAlive = false;

                return(null);
            }

            TelemetryPoint sensorData = new TelemetryPoint()
            {
                iotHubDeviceId = iotHubDeviceId,
                temperature    = temperature,
                digitalInput   = digitalInput
            };

            return(sensorData);
        }