Beispiel #1
0
        private static bool TryReadSensor(
            Sensor sensor,
            out SensorReadings readings,
            out string errorMessage)
        {
            errorMessage = string.Empty;

            if (sensor.Initiated)
            {
                try
                {
                    if (sensor.Update())
                    {
                        readings = sensor.Readings;
                        return(true);
                    }
                }
                catch (Exception exception)
                {
                    errorMessage = exception.Message;
                }
            }

            readings = new SensorReadings();
            return(false);
        }
 public DeviceMessage()
 {
     id       = Guid.NewGuid().ToString();
     reading  = new DateTime();
     location = new Location();
     sensors  = new SensorReadings();
 }
        /// <summary>
        /// Tries to update the readings.
        /// Returns true if new readings are available, otherwise false.
        /// An exception is thrown if something goes wrong.
        /// </summary>
        public override bool Update()
        {
            var readings = new SensorReadings
            {
                Timestamp = DateTime.Now
            };

            byte status = I2CSupport.Read8Bits(_i2CDevice, HTS221Defines.STATUS, "Failed to read HTS221 status");

            if ((status & 0x02) == 0x02)
            {
                Int16 rawHumidity = (Int16)I2CSupport.Read16Bits(_i2CDevice, HTS221Defines.HUMIDITY_OUT_L + 0x80, ByteOrder.LittleEndian, "Failed to read HTS221 humidity");
                readings.Humidity      = _humidityConversionFunc(rawHumidity);
                readings.HumidityValid = true;
            }

            if ((status & 0x01) == 0x01)
            {
                Int16 rawTemperature = (Int16)I2CSupport.Read16Bits(_i2CDevice, HTS221Defines.TEMP_OUT_L + 0x80, ByteOrder.LittleEndian, "Failed to read HTS221 temperature");
                readings.Temperature      = _temperatureConversionFunc(rawTemperature);
                readings.TemperatureValid = true;
            }

            if (readings.HumidityValid || readings.TemperatureValid)
            {
                AssignNewReadings(readings);
                return(true);
            }

            return(false);
        }
        public SensorReadings ReadSensors()
        {
            if (_devices == null)
            {
                _devices = _handler.GetDevices <DS18B20>();
            }

            var secondsFromLastReading = (DateTime.Now - _previousReadingTime).TotalSeconds;

            if (secondsFromLastReading <= _devices.Count() * 2)
            {
                return(null);
            }

            _previousReadingTime = DateTime.Now;

            var result = new SensorReadings();

            result.ReadingTime = _previousReadingTime;

            foreach (var device in _devices)
            {
                var reading = new SensorReading();
                reading.SensorId = device.OneWireAddressString;
                reading.Reading  = device.GetTemperature();

                result.Readings.Add(reading);
            }

            return(result);
        }
        public async Task ReportReadings(SensorReadings readings)
        {
            var messageString = JsonConvert.SerializeObject(readings);
            var message       = new Message(Encoding.ASCII.GetBytes(messageString));

            await _deviceClient.SendEventAsync(message);
        }
        /// <summary>
        /// Tries to update the readings.
        /// Returns true if new readings are available, otherwise false.
        /// An exception is thrown if something goes wrong.
        /// </summary>
        public override bool Update()
        {
            byte status = I2CSupport.Read8Bits(_i2CDevice, LPS25HDefines.STATUS_REG, "Failed to read LPS25H status");

            var readings = new SensorReadings
            {
                Timestamp = DateTime.Now
            };

            if ((status & 0x02) == 0x02)
            {
                Int32 rawPressure = (Int32)I2CSupport.Read24Bits(_i2CDevice, LPS25HDefines.PRESS_OUT_XL + 0x80, ByteOrder.LittleEndian, "Failed to read LPS25H pressure");

                readings.Pressure      = rawPressure / 4096.0;
                readings.PressureValid = true;
            }

            if ((status & 0x01) == 0x01)
            {
                Int16 rawTemperature = (Int16)I2CSupport.Read16Bits(_i2CDevice, LPS25HDefines.TEMP_OUT_L + 0x80, ByteOrder.LittleEndian, "Failed to read LPS25H temperature");

                readings.Temperature      = rawTemperature / 480.0 + 42.5;
                readings.TemperatureValid = true;
            }

            if (readings.PressureValid || readings.TemperatureValid)
            {
                AssignNewReadings(readings);
                return(true);
            }

            return(false);
        }
        public static SensorReadings GetMapData()
        {
            Logger.Write($"Sending get map data command to port {Port.PortName}...");
            Port.DiscardInBuffer();
            Port.Write(Constants.SERIAL_START_CHAR + Constants.SERIAL_CMD_GET_MAP_DATA + Constants.SERIAL_STOP_CHAR);

            var readings = new SensorReadings();

            try
            {
                for (int i = 0; i < 5; i++)
                {
                    var response = ReadSerial(Port);
                    switch (response)
                    {
                    case Constants.SERIAL_CMDRSPN_GET_MAP_DATA_000_DEG:
                        ReadDoubleFromSerial(Port);
                        var data000Degree = ReadDoubleFromSerial(Port);
                        readings.Reading0 = data000Degree;
                        break;

                    case Constants.SERIAL_CMDRSPN_GET_MAP_DATA_045_DEG:
                        ReadDoubleFromSerial(Port);
                        var data045Degree = ReadDoubleFromSerial(Port);
                        readings.Reading45 = data045Degree;
                        break;

                    case Constants.SERIAL_CMDRSPN_GET_MAP_DATA_090_DEG:
                        ReadDoubleFromSerial(Port);
                        var data090Degree = ReadDoubleFromSerial(Port);
                        readings.Reading90 = data090Degree;
                        break;

                    case Constants.SERIAL_CMDRSPN_GET_MAP_DATA_135_DEG:
                        ReadDoubleFromSerial(Port);
                        var data135Degree = ReadDoubleFromSerial(Port);
                        readings.Reading135 = data135Degree;
                        break;

                    case Constants.SERIAL_CMDRSPN_GET_MAP_DATA_180_DEG:
                        ReadDoubleFromSerial(Port);
                        var data180Degree = ReadDoubleFromSerial(Port);
                        readings.Reading180 = data180Degree;
                        break;
                    }
                }
            }

            catch (TimeoutException)
            {
                return(readings);
            }

            return(readings);
        }
Beispiel #8
0
        private void FillCache(Dictionary <string, List <SensorReadingDto> > cache)
        {
            foreach (var key in SensorReadingCacheKeys)
            {
                if (!cache.ContainsKey(key))
                {
                    cache.Add(key, new List <SensorReadingDto>());
                }

                cache[key].AddRange(SensorReadings.Where(sr => $"{sr.Hardware.Name}.{sr.Sensor.Name}" == key));
            }
        }
        public double Calculate(SensorReadings readings, Measurement measurement)
        {
            if (measurement == null)
            {
                throw new ArgumentNullException(nameof(measurement));
            }

            if (measurement.FreezingPoint == null)
            {
                return(-1.0);
            }

            if (measurement.CoolingRate == null)
            {
                return(-1.0);
            }

            var ambientSensorId = measurement.SensorRoles
                                  .FirstOrDefault(r => r.RoleName == _ambientSensorId)
                                  .Sensor
                                  .Id;
            var liquidSensorId = measurement.SensorRoles
                                 .FirstOrDefault(r => r.RoleName == _liquidSensorId)
                                 .Sensor
                                 .Id;

            var ambientTemp = readings.GetSensorReading(ambientSensorId);

            if (ambientTemp == null)
            {
                return(-1.0);
            }

            var liquidTemp = readings.GetSensorReading(liquidSensorId);

            if (liquidTemp == null)
            {
                return(-1.0);
            }

            var estimate = GetCoolingEstimate(liquidTemp.Value,
                                              ambientTemp.Value,
                                              measurement.FreezingPoint.Value,
                                              measurement.CoolingRate.Value);

            if (double.IsNaN(estimate) || double.IsInfinity(estimate))
            {
                estimate = -1;
            }

            return(Math.Ceiling(estimate));
        }
Beispiel #10
0
        public double Calculate(SensorReadings readings, Measurement measurement)
        {
            if (measurement.CoolingRate == null)
            {
                return(-100);
            }

            var ambientSensorId = measurement.SensorRoles
                                  .FirstOrDefault(r => r.RoleName == _ambientSensorId)
                                  .Sensor
                                  .Id;
            var liquidSensorId = measurement.SensorRoles
                                 .FirstOrDefault(r => r.RoleName == _liquidSensorId)
                                 .Sensor
                                 .Id;

            var ambientTemp = readings.GetSensorReading(ambientSensorId);

            if (ambientTemp == null)
            {
                return(-100);
            }

            var liquidTemp = readings.GetSensorReading(liquidSensorId);

            if (liquidTemp == null)
            {
                return(-100);
            }

            var oldestTime = GetOldestSameAmbientTemperature(ambientTemp.Value, measurement.Id);

            if (oldestTime == null)
            {
                return(-100);
            }

            var time = readings.ReadingTime - oldestTime.Value;
            var temp = GetTheoreticalTemperature(time.TotalMinutes,
                                                 liquidTemp.Value,
                                                 ambientTemp.Value,
                                                 measurement.CoolingRate.Value);

            if (double.IsNaN(temp) || double.IsInfinity(temp))
            {
                return(-100);
            }

            return(temp);
        }
Beispiel #11
0
        public IActionResult AddSensorReading(string serialNumber, SensorReadings sensorReading)
        {
            var device = _deviceService.GetBySerial(serialNumber);

            if (device == null)
            {
                return(NotFound());
            }

            device.SensorReadings = device.SensorReadings.Concat(new List <SensorReadings> {
                sensorReading
            }).OrderBy(reading => reading.ReadingDateTime);

            _deviceService.Update(device.Id, device);

            return(CreatedAtRoute("GetDevice", new { id = device.Id.ToString() }, device));
        }
 private SensorReadings UpdateSensorsTrendAndLastTemp(SensorReadings listOfRooms, SensorReadings sensorReadings)
 {
     foreach (var s in listOfRooms.Temperatures)
     {
         //update room temperature trends and values
         foreach (var n in sensorReadings.Temperatures)
         {
             if (s.RoomName == n.RoomName)
             {
                 s.isHeatingRequired = (s.TemperatureSET - n.Temperature) > 0;
                 s.isTrendIncreases  = (n.Temperature - s.Temperature) > 0;
                 s.LastTemperature   = s.Temperature;
                 s.Temperature       = n.Temperature;
                 break;
             }
         }
     }
     return(listOfRooms);
 }
        public double Calculate(SensorReadings readings, Measurement measurement)
        {
            if (measurement == null)
            {
                return(-1000);
            }

            if (!measurement.OriginalGravity.HasValue && !measurement.OriginalGravity.HasValue)
            {
                return(-1000);
            }

            var og = measurement.OriginalGravity.Value;
            var fg = measurement.FinalGravity.Value;

            if (measurement.AlcoholByVolume == null)
            {
                var alcVol = Math.Round(GetAlcVol(og, fg), 1);
                if (!double.IsNaN(alcVol) && !double.IsInfinity(alcVol))
                {
                    measurement.AlcoholByVolume = alcVol;
                }
            }
            if (measurement.AlcoholByWeight == null)
            {
                var abw = Math.Round(AbvToAbw(GetAlcVol(og, fg)), 1);
                if (!double.IsNaN(abw) && !double.IsInfinity(abw))
                {
                    measurement.AlcoholByWeight = abw;
                }
            }
            if (measurement.FreezingPoint == null)
            {
                var fp = Math.Ceiling(GetFreezingPoint(og, fg));
                if (!double.IsNaN(fp) && !double.IsInfinity(fp))
                {
                    measurement.FreezingPoint = fp;
                }
            }

            return(-1000);
        }
Beispiel #14
0
        /// <summary>
        /// Tries to update the readings.
        /// Returns true if new readings are available, otherwise false.
        /// An exception is thrown if something goes wrong.
        /// </summary>
        public override bool Update()
        {
            byte status = I2CSupport.Read8Bits(_accelGyroI2CDevice, LSM9DS1Defines.STATUS, "Failed to read LSM9DS1 status");

            if ((status & 0x03) != 0x03)
            {
                // Data not yet available
                return(false);
            }

            byte[] gyroData = I2CSupport.ReadBytes(_accelGyroI2CDevice, 0x80 + LSM9DS1Defines.OUT_X_L_G, 6, "Failed to read LSM9DS1 gyro data");

            byte[] accelData = I2CSupport.ReadBytes(_accelGyroI2CDevice, 0x80 + LSM9DS1Defines.OUT_X_L_XL, 6, "Failed to read LSM9DS1 accel data");

            byte[] magData = I2CSupport.ReadBytes(_magI2CDevice, 0x80 + LSM9DS1Defines.MAG_OUT_X_L, 6, "Failed to read LSM9DS1 compass data");


            var readings = new SensorReadings
            {
                Timestamp          = DateTime.Now,
                Gyro               = MathSupport.ConvertToVector(gyroData, _gyroScale, ByteOrder.LittleEndian),
                GyroValid          = true,
                Acceleration       = MathSupport.ConvertToVector(accelData, _accelerationScale, ByteOrder.LittleEndian),
                AccelerationValid  = true,
                MagneticField      = MathSupport.ConvertToVector(magData, _magneticFieldScale, ByteOrder.LittleEndian),
                MagneticFieldValid = true
            };

            // Sort out gyro axes and correct for bias
            readings.Gyro.Z = -readings.Gyro.Z;

            // Sort out accel data;
            readings.Acceleration.X = -readings.Acceleration.X;
            readings.Acceleration.Y = -readings.Acceleration.Y;

            // Sort out mag axes
            readings.MagneticField.X = -readings.MagneticField.X;
            readings.MagneticField.Z = -readings.MagneticField.Z;

            AssignNewReadings(readings);
            return(true);
        }
Beispiel #15
0
        public double Calculate(SensorReadings readings, Measurement measurement)
        {
            LoadObservation();

            var station = _observation.Stations
                          .Where(x => x.Name.ToLower() == _city.ToLower())
                          .FirstOrDefault();

            if (station == null)
            {
                return(-1000);
            }

            if (!station.AirTemperature.HasValue)
            {
                return(-1000);
            }

            return(station.AirTemperature.Value);
        }
        public SensorReadings ReadSensors()
        {
            if (_devices == null)
            {
                _devices = _handler.GetDevices <DS18B20>();
            }

            var result = new SensorReadings();

            result.ReadingTime = DateTime.Now;

            foreach (var device in _devices)
            {
                var reading = new SensorReading();
                reading.SensorId = device.OneWireAddressString;
                reading.Reading  = device.GetTemperature();

                result.Readings.Add(reading);
            }

            return(result);
        }
        public async Task ReportReadings(SensorReadings readings)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("DeviceKey", DeviceKey);

                var url  = ServiceAddress + "report";
                var body = JsonConvert.SerializeObject(readings);
                _logger.Info("Web reporting client: " + body);
                var content = new StringContent(body, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(url, content);

                body = "";

                if (response.Content != null)
                {
                    body = await response.Content.ReadAsStringAsync();
                }

                _logger.Info("Web reporting client: " + response.StatusCode + " " + body);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Use keyboard to control hand models if enabled. This is done by generating
        /// fake Frame.
        /// </summary>
        /// <param name="fakeHand"></param>
        private void KeyboardControl(out Hand fakeHand)
        {
            float deltaBend  = -Input.GetAxis("Vertical");
            float deltaSplit = Input.GetAxis("Horizontal");
            float speed      = 0.005f;

            if (Input.GetKey(KeyCode.Alpha1))
            {
                _keyboardControlledThumbRotate += speed;
            }
            else if (Input.GetKey(KeyCode.Alpha2))
            {
                _keyboardControlledThumbRotate -= speed;
            }

            if (Input.GetKey(KeyCode.Alpha4))
            {
                _keyboardControlledThumbSplit += speed;
            }
            else if (Input.GetKey(KeyCode.Alpha5))
            {
                _keyboardControlledThumbSplit -= speed;
            }

            if (Input.GetKey(KeyCode.Alpha7))
            {
                if (_keyboardControlledFingerBend.Count > 0)
                {
                    _keyboardControlledFingerBend[0] += speed;
                }
            }
            else if (Input.GetKey(KeyCode.Alpha8))
            {
                if (_keyboardControlledFingerBend.Count > 0)
                {
                    _keyboardControlledFingerBend[0] -= speed;
                }
            }

            _keyboardControlledThumbRotate = Mathf.Clamp01(_keyboardControlledThumbRotate);
            _keyboardControlledThumbSplit  = Mathf.Clamp01(_keyboardControlledThumbSplit);
            int n = _keyboardControlledFingerBend.Count;

            for (int i = 0; i < n; i++)
            {
                if (i > 0)
                {
                    _keyboardControlledFingerBend[i] += deltaBend * speed;
                }
                _keyboardControlledFingerBend[i] =
                    Mathf.Clamp01(_keyboardControlledFingerBend[i]);
            }
            _keyboardControlledFingerSplit += deltaSplit * speed;
            _keyboardControlledFingerSplit  = Mathf.Clamp01(_keyboardControlledFingerSplit);
            Libdexmo.Model.Joint fakeJointMCP;
            Libdexmo.Model.Joint fakeJointMCPThumb;
            Libdexmo.Model.Joint fakeJointPIPThumb;
            Libdexmo.Model.Joint fakeJointDIPThumb;
            Libdexmo.Model.Joint fakeJointMCPIndex;
            Libdexmo.Model.Joint fakeJointPIPIndex;
            Libdexmo.Model.Joint fakeJointDIPIndex;
            fakeJointMCPThumb =
                new Libdexmo.Model.Joint(JointType.MCP, 0, _keyboardControlledThumbSplit, _keyboardControlledThumbRotate);
            fakeJointPIPThumb =
                new Libdexmo.Model.Joint(JointType.MCP, 0, 0, _keyboardControlledFingerBend[0]);
            fakeJointDIPThumb =
                new Libdexmo.Model.Joint(JointType.MCP, 0, 0, _keyboardControlledFingerBend[0]);
            Libdexmo.Model.Joint[] fakeJointsThumb =
                new Libdexmo.Model.Joint[3] {
                fakeJointMCPThumb, fakeJointPIPThumb, fakeJointDIPThumb
            };
            Finger[] fakeFingerData = new Finger[5];
            for (int i = 0; i < 5; i++)
            {
                if (i == 0)
                {
                    fakeFingerData[0] = new Finger(FingerType.Thumb, fakeJointsThumb, null);
                }
                else
                {
                    Joint[] fakeJoints = new Joint[3];
                    for (int j = 0; j < 3; j++)
                    {
                        fakeJoints[j] = new Joint((JointType)i, 0,
                                                  _keyboardControlledFingerSplit, _keyboardControlledFingerBend[i]);
                    }
                    fakeFingerData[i] = new Finger((FingerType)i, fakeJoints, null);
                }
            }
            SensorReadings fakeSensorReadings = new SensorReadings(null, null, null, null);

            fakeHand = new Hand(123, _keyboardControlRight, fakeFingerData, fakeSensorReadings);
        }
		/// <summary>
		/// Tries to update the readings.
		/// Returns true if new readings are available, otherwise false.
		/// An exception is thrown if something goes wrong.
		/// </summary>
		public override bool Update()
		{
			byte status = I2CSupport.Read8Bits(_accelGyroI2CDevice, LSM9DS1Defines.STATUS, "Failed to read LSM9DS1 status");

			if ((status & 0x03) != 0x03)
			{
				// Data not yet available
				return false;
			}

			byte[] gyroData = I2CSupport.ReadBytes(_accelGyroI2CDevice, 0x80 + LSM9DS1Defines.OUT_X_L_G, 6, "Failed to read LSM9DS1 gyro data");

			byte[] accelData = I2CSupport.ReadBytes(_accelGyroI2CDevice, 0x80 + LSM9DS1Defines.OUT_X_L_XL, 6, "Failed to read LSM9DS1 accel data");

			byte[] magData = I2CSupport.ReadBytes(_magI2CDevice, 0x80 + LSM9DS1Defines.MAG_OUT_X_L, 6, "Failed to read LSM9DS1 compass data");

			var readings = new SensorReadings
			{
				Timestamp = DateTime.Now,
				Gyro = MathSupport.ConvertToVector(gyroData, _gyroScale, ByteOrder.LittleEndian),
				GyroValid = true,
				Acceleration = MathSupport.ConvertToVector(accelData, _accelerationScale, ByteOrder.LittleEndian),
				AccelerationValid = true,
				MagneticField = MathSupport.ConvertToVector(magData, _magneticFieldScale, ByteOrder.LittleEndian),
				MagneticFieldValid = true
			};

			// Sort out gyro axes and correct for bias
			readings.Gyro.Z = -readings.Gyro.Z;

			// Sort out accel data;
			readings.Acceleration.X = -readings.Acceleration.X;
			readings.Acceleration.Y = -readings.Acceleration.Y;

			// Sort out mag axes
			readings.MagneticField.X = -readings.MagneticField.X;
			readings.MagneticField.Z = -readings.MagneticField.Z;

			AssignNewReadings(readings);
			return true;
		}
		/// <summary>
		/// Tries to update the readings.
		/// Returns true if new readings are available, otherwise false.
		/// An exception is thrown if something goes wrong.
		/// </summary>
		public override bool Update()
		{
			var readings = new SensorReadings
			{
				Timestamp = DateTime.Now
			};

			byte status = I2CSupport.Read8Bits(_i2CDevice, HTS221Defines.STATUS, "Failed to read HTS221 status");

			if ((status & 0x02) == 0x02)
			{
				Int16 rawHumidity = (Int16)I2CSupport.Read16Bits(_i2CDevice, HTS221Defines.HUMIDITY_OUT_L + 0x80, ByteOrder.LittleEndian, "Failed to read HTS221 humidity");
				readings.Humidity = _humidityConversionFunc(rawHumidity);
				readings.HumidityValid = true;
			}

			if ((status & 0x01) == 0x01)
			{
				Int16 rawTemperature = (Int16)I2CSupport.Read16Bits(_i2CDevice, HTS221Defines.TEMP_OUT_L + 0x80, ByteOrder.LittleEndian, "Failed to read HTS221 temperature");
				readings.Temperature = _temperatureConversionFunc(rawTemperature);
				readings.TemperatureValid = true;
			}

			if (readings.HumidityValid || readings.TemperatureValid)
			{
				AssignNewReadings(readings);
				return true;
			}

			return false;
		}
Beispiel #21
0
 public double Calculate(SensorReadings readings, Measurement measurement)
 {
     return(readings.Readings.Average(r => r.Reading));
 }
        /// <summary>
        /// When an ascii reading is reveived this function is called from logbook.cs and processes it
        /// </summary>
        /// <param name="dataBytes"></param>
        protected void processASCIIReading(byte[] dataBytes)
        {
            if (asciiReadingDBConnection == null)
             {
            asciiReadingDBConnection = database;
             }

             readASCIIFailCount = 0;
             ResetReadASCIITimer();

             DateTime receivedTime = DateTime.UtcNow;
             string[] channel = new string[4];
             try
             {
            channel = Logbook.SplitChannels(dataBytes);
             }
             catch (Exception ex)
             {
            log.LogException(ex, "processASCIIReading SplitChannels");
             }

             DateTime localTime = receivedTime.ToLocalTime();
             string dataText = String.Format("Reading: {4}-{5:d2}-{6:d2} {7:d2}:{8:d2}:{9:d2} [{0}] [{1}] [{2}] [{3}]",
             channel[0].Trim(), channel[1].Trim(), channel[2].Trim(), channel[3].Trim(),
             localTime.Year, localTime.Month, localTime.Day, localTime.Hour, localTime.Minute, localTime.Second);

             log.Append("processASCIIReading", dataText);
             //UpdateLatestDataLabel(dataText);

             double[] value = new double[4];
             try
             {
            for (int i = 0; i < 4; i++)
            {
               try
               {
                  value[i] = Logbook.ReadingToValue(channel[i], CurrentSensors[i]);
                  current_readings[i] = value[i];
               }
               catch (FormatException ex)
               {
                  log.LogException(ex, String.Format("processASCIIReading[{0}]", i));
                  current_readings[i] = 0;
               }

            }
            //if ((sensorGraph != null) && (sensorDefinitions[sensorToGraph].ID != 255))
            //{
            //   sensorGraph.Plot(receivedTime, value[sensorToGraph]);
            //   sensorGraph.ToNow();
            //}
            sensorReadingTime = receivedTime;
             }
             catch (Exception ex)
             {
            log.LogException(ex, "processASCIIReading sensorGraph");
             }

             SensorReadingsData dataToSend = null;
             double[] std_devs = null;
             try
             {
            SensorReadings readings = new SensorReadings(CurrentServerData.id, current_readings[0],
               current_readings[1], current_readings[2], current_readings[3], receivedTime);
            DatabaseHelper.saveSensorReadings(readings, asciiReadingDBConnection);
             }
             catch (Exception ex)
             {
            log.LogException(ex, "processASCIIReading saveSensorReadings");
             }

             //UpdateOverallStats(asciiReadingDBConnewction);

             //std_devs = DatabaseHelper.getStdDev(CurrentServerData.id, overall_means, (int)overall_stats[12], asciiReadingDBConnection);
             //dataToSend = new SensorReadingsData(CurrentServerData.id, value[0], value[1], value[2], value[3], receivedTime, overall_means, std_devs);
             //if ((runningMode == RunningModes.Manual) || (runningMode == RunningModes.Started))
             //{
            //sendSensorReadings(dataToSend);
             //}

             //double[] significances = new double[4];
             //for (int stat_count = 0; stat_count < 4; stat_count++)
             //{
             //   significances[stat_count] = Stats.Significance(overall_means[stat_count], std_devs[stat_count], value[stat_count]);
             //   Debug.WriteLine(String.Format("processASCIIReading Reading[{0}]: {1}, Significance[{0}]: {2}", stat_count, value[stat_count], significances[stat_count]));
             //}
             //QuestionMessage question = QuestionHelper.CreateCurrentReadingQuestion(overall_stats, dataToSend, significances, sensorDefinitions);
             //if (question != null)
             //{
             //   question.id = Guid.NewGuid();
             //   question.Time = receivedTime;
             //   question.Server = current_server_id;
             //   question.Author = ServerName;
             //   log.Append("processASCIIReading ", String.Format("Question {0} '{1}'", question.id, question.Text));
             //   try
             //   {
             //      DatabaseHelper.SaveQuestionMessage(question, asciiReadingDBConnection);
             //   }
             //   catch (Exception ex)
             //   {
             //      log.LogException(ex, "processASCIIReading SaveQuestion");
             //   }
             //   sendQuestion(question);
             //}

             //if (this.InvokeRequired)
             //{
             //   object[] invokeParams = new object[4];
             //   for (int i = 0; i < 4; i++)
             //   {
             //      invokeParams[i] = std_devs[i];
             //   }
             //   this.Invoke(statsDisplayUpdate, invokeParams);
             //}
             //else
             //{
             //   UpdateStatsDisplay(std_devs[0], std_devs[1], std_devs[2], std_devs[3]);
             //}
        }
		/// <summary>
		/// Tries to update the readings.
		/// Returns true if new readings are available, otherwise false.
		/// An exception is thrown if something goes wrong.
		/// </summary>
		public override bool Update()
		{
            bool newReadings = false;

			byte status = I2CSupport.Read8Bits(_i2CDevice, LPS25HDefines.STATUS_REG, "Failed to read LPS25H status");

			var readings = new SensorReadings
			{
				Timestamp = DateTime.Now
			};

			if ((status & 0x02) == 0x02)
			{
				Int32 rawPressure = (Int32)I2CSupport.Read24Bits(_i2CDevice, LPS25HDefines.PRESS_OUT_XL + 0x80, ByteOrder.LittleEndian, "Failed to read LPS25H pressure");

				_pressure = rawPressure / 4096.0;
				_pressureValid = true;
                newReadings = true;
			}

			if ((status & 0x01) == 0x01)
			{
				Int16 rawTemperature = (Int16)I2CSupport.Read16Bits(_i2CDevice, LPS25HDefines.TEMP_OUT_L + 0x80, ByteOrder.LittleEndian, "Failed to read LPS25H temperature");

				_temperature = rawTemperature / 480.0 + 42.5;
				_temperatureValid = true;
                newReadings = true;
			}

			if (newReadings)
			{
                readings.Pressure = _pressure;
                readings.PressureValid = _pressureValid;
                readings.Temperature = _temperature;
                readings.TemperatureValid = _temperatureValid;
                AssignNewReadings(readings);
				return true;
			}

			return false;
		}
Beispiel #24
0
 public DeviceMessage()
 {
     CreatedOn = new DateTime();
     sensors   = new SensorReadings();
 }
 public DeviceMessage()
 {
     reading  = new DateTime();
     location = new Location();
     sensors  = new SensorReadings();
 }
        public async void ReadTemperature()
        {
            var _receiveData   = new ReceiveData();
            var _sensorsClient = new RinsenOneWireClient();
            var _sendListData  = new SendDataAzure();
            var Methods        = new METHOD();
            //currentSumOfTempDeltas is some bigger number than the delta (0,5) is used to determine temperature changes
            double SumOfTemperatureDeltas = 10;

            //initiate the list with the temps and names
            ListOfAllSensors = await _sensorsClient.ReadSensors();

            //fill out LastTemperatures and initial Temperature trend which is initially always TRUE
            ListOfAllSensors = UpdateSensorsTrendAndLastTemp(ListOfAllSensors, ListOfAllSensors);

            var filename = Methods.GetFilePath(CONSTANT.FILENAME_ROOM_TEMPERATURES);

            if (File.Exists(filename))
            {
                var dataFromFile = await Methods.OpenExistingFile(filename);

                List <SensorReading> SetRoomTemps = JsonSerializer.Deserialize <List <SensorReading> >(dataFromFile);
                SetTemperatures(SetRoomTemps);
            }
            while (true)
            {
                //get a new sensor readings and then update
                SensorReadings sensorReadings = await _sensorsClient.ReadSensors();

                ListOfAllSensors = UpdateSensorsTrendAndLastTemp(ListOfAllSensors, sensorReadings);

                //summing all the room temperature changes together add new deltas until it bigger that 4 degrees
                SumOfTemperatureDeltas += ListOfAllSensors.Temperatures.Where(x => x.isRoom).Sum(x => Math.Abs(x.Temperature - x.LastTemperature));

                //manage Livingroom heating actuator
                if (ListOfAllSensors.Temperatures.FirstOrDefault(x => x.RoomName == LIVING).isHeatingRequired)
                {
                    Pins.PinWrite(Pins.livingRoomHeatControlOut, PinValue.High);
                }
                else
                {
                    Pins.PinWrite(Pins.livingRoomHeatControlOut, PinValue.Low);
                }

                //manage Office heating actuator
                if (ListOfAllSensors.Temperatures.FirstOrDefault(x => x.RoomName == OFFICE).isHeatingRequired)
                {
                    Pins.PinWrite(Pins.homeOfficeHeatControlOut, PinValue.High);
                }
                else
                {
                    Pins.PinWrite(Pins.homeOfficeHeatControlOut, PinValue.Low);
                }

                //manage Piano heating actuator
                bool isPianoHeatingOn = ListOfAllSensors.Temperatures.FirstOrDefault(x => x.RoomName == PIANO).isHeatingRequired;
                await Shelly.SetShellySwitch(isPianoHeatingOn, Shelly.PianoHeating, nameof(Shelly.PianoHeating));

                //manage Bedroom heating actuator
                bool isBedroomHeatingOn = ListOfAllSensors.Temperatures.FirstOrDefault(x => x.RoomName == BEDROOM).isHeatingRequired;
                await Shelly.SetShellySwitch(isBedroomHeatingOn, Shelly.BedroomHeating, nameof(Shelly.BedroomHeating));

                //manage sauna temperature
                if (ListOfAllSensors.Temperatures.FirstOrDefault(x => x.RoomName == SAUNA).isHeatingRequired&& TelemetryDataClass.isSaunaOn)
                {
                    Pins.PinWrite(Pins.saunaHeatOutPin, PinValue.Low);
                }
                else
                {
                    Pins.PinWrite(Pins.saunaHeatOutPin, PinValue.High);
                }
                //if sauna extremely hot, then turn off
                if (ListOfAllSensors.Temperatures.FirstOrDefault(x => x.RoomName == SAUNA).Temperature > CONSTANT.EXTREME_SAUNA_TEMP)
                {
                    _receiveData.ProcessCommand(CommandNames.TURN_OFF_SAUNA);
                }

                //if all rooms has achieved their target temperature then turn system off
                if (ListOfAllSensors.Temperatures.Where(x => x.isRoom).All(x => !x.isHeatingRequired))
                {
                    _receiveData.ProcessCommand(CommandNames.REDUCE_TEMP_COMMAND);
                }

                //if all room temperatures together has changed more that 3 degrees then send it out to database
                if (Math.Abs(SumOfTemperatureDeltas) > 4)
                {
                    TelemetryDataClass.SourceInfo = $"Room temp changed {SumOfTemperatureDeltas:0.0}";
                    var monitorData = new
                    {
                        DeviceID    = "RoomTemperatures",
                        UtcOffset   = METHOD.DateTimeTZ().Offset.Hours,
                        DateAndTime = METHOD.DateTimeTZ().DateTime,
                        time        = METHOD.DateTimeTZ().ToString("HH:mm"),
                        TelemetryDataClass.SourceInfo,
                        ListOfAllSensors.Temperatures
                    };
                    await _sendListData.PipeMessage(monitorData, Program.IoTHubModuleClient, TelemetryDataClass.SourceInfo, "output");

                    SumOfTemperatureDeltas = 0;            //resetting to start summing up again
                }
                await Task.Delay(TimeSpan.FromMinutes(1)); //check temperatures every minute
            }
        }