From f4f1c3c7849f8be60c3c9df6ffdf82146d5a6729 Mon Sep 17 00:00:00 2001 From: Chris Kaczor Date: Fri, 16 Jan 2015 18:44:29 -0500 Subject: [PATCH] More cleanup --- Data/{Device.cs => DeviceData.cs} | 2 +- Data/{Reading.cs => ReadingData.cs} | 2 +- Data/{Setting.cs => SettingData.cs} | 2 +- Data/WeatherArchiveData.cs | 2 +- Data/WeatherData.cs | 4 +- Devices/DeviceBase.cs | 187 +++++------------ Devices/HumidityDevice.cs | 37 ++-- Devices/PressureDevice.cs | 303 +++++++++++++--------------- Devices/RainDevice.cs | 38 ++-- Devices/TemperatureDevice.cs | 23 +-- Devices/WindDirectionDevice.cs | 40 +--- Devices/WindSpeedDevice.cs | 29 +-- Properties/AssemblyInfo.cs | 32 +-- Session.cs | 18 +- SignalR/WeatherHub.cs | 14 +- Values/Value.cs | 2 +- WeatherService.csproj | 6 +- 17 files changed, 277 insertions(+), 464 deletions(-) rename Data/{Device.cs => DeviceData.cs} (93%) rename Data/{Reading.cs => ReadingData.cs} (92%) rename Data/{Setting.cs => SettingData.cs} (92%) diff --git a/Data/Device.cs b/Data/DeviceData.cs similarity index 93% rename from Data/Device.cs rename to Data/DeviceData.cs index 590dea5..a9f27ef 100644 --- a/Data/Device.cs +++ b/Data/DeviceData.cs @@ -4,7 +4,7 @@ using System.ComponentModel.DataAnnotations.Schema; namespace WeatherService.Data { [Table("Device")] - public class Device + public class DeviceData { public int Id { get; set; } diff --git a/Data/Reading.cs b/Data/ReadingData.cs similarity index 92% rename from Data/Reading.cs rename to Data/ReadingData.cs index a9ed9fd..020965b 100644 --- a/Data/Reading.cs +++ b/Data/ReadingData.cs @@ -4,7 +4,7 @@ using System.ComponentModel.DataAnnotations.Schema; namespace WeatherService.Data { [Table("Reading")] - public class Reading + public class ReadingData { public int Id { get; set; } diff --git a/Data/Setting.cs b/Data/SettingData.cs similarity index 92% rename from Data/Setting.cs rename to Data/SettingData.cs index 8d60865..4634e03 100644 --- a/Data/Setting.cs +++ b/Data/SettingData.cs @@ -4,7 +4,7 @@ using System.ComponentModel.DataAnnotations.Schema; namespace WeatherService.Data { [Table("Setting")] - public class Setting + public class SettingData { [Key] [StringLength(500)] diff --git a/Data/WeatherArchiveData.cs b/Data/WeatherArchiveData.cs index 4842cb4..9b75d78 100644 --- a/Data/WeatherArchiveData.cs +++ b/Data/WeatherArchiveData.cs @@ -39,7 +39,7 @@ namespace WeatherService.Data DatabaseExists[year] = true; } - public virtual DbSet Readings { get; set; } + public virtual DbSet Readings { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { diff --git a/Data/WeatherData.cs b/Data/WeatherData.cs index 8e0fd54..064e49e 100644 --- a/Data/WeatherData.cs +++ b/Data/WeatherData.cs @@ -9,8 +9,8 @@ namespace WeatherService.Data { } - public virtual DbSet Devices { get; set; } - public virtual DbSet Settings { get; set; } + public virtual DbSet Devices { get; set; } + public virtual DbSet Settings { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { diff --git a/Devices/DeviceBase.cs b/Devices/DeviceBase.cs index f964a27..c662ace 100644 --- a/Devices/DeviceBase.cs +++ b/Devices/DeviceBase.cs @@ -1,15 +1,13 @@ +using OneWireAPI; using System; +using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; -using OneWireAPI; -using System.Collections.Generic; using WeatherService.Data; using WeatherService.Values; namespace WeatherService.Devices { - #region Enumerations - [DataContract] public enum DeviceType { @@ -35,8 +33,6 @@ namespace WeatherService.Devices Rain } - #endregion - [DataContract] [KnownType(typeof(HumidityDevice))] [KnownType(typeof(PressureDevice))] @@ -46,56 +42,64 @@ namespace WeatherService.Devices [KnownType(typeof(WindSpeedDevice))] public class DeviceBase { - #region Member variables + protected Session Session; - protected int _deviceId; // Device ID - protected string _deviceAddress; // Device key - protected Session _session; // The root session - protected owDevice _device; // The one wire device - protected DateTime _lastRead = DateTime.MinValue; // When was the last refresh? - protected int _refreshFrequency; // How often should we refresh? - protected Dictionary _valueList; // List of values - protected string _displayName; // Device display name - protected DeviceType _deviceType; // Type of device - protected long _operationCount; // Number of operations - protected long _errorCount; // Number of errors + protected internal Device OneWireDevice { get; protected set; } - #endregion + [DataMember] + public int Id { get; set; } - #region Constructor + [DataMember] + public string Address { get; set; } - public DeviceBase(Session session, owDevice device, DeviceType deviceType) + [DataMember] + public string DisplayName { get; set; } + + [DataMember] + public DateTime LastRead { get; set; } + + [DataMember] + public long Operations { get; set; } + + [DataMember] + public long Errors { get; set; } + + [DataMember] + public DeviceType Type { get; set; } + + [DataMember] + public int RefreshFrequency { get; set; } + + [DataMember] + public Dictionary Values { get; protected set; } + + public DeviceBase(Session session, Device device, DeviceType deviceType) { + LastRead = DateTime.MinValue; + // Initialize the value list - _valueList = new Dictionary(); + Values = new Dictionary(); // Store properties of the device - _deviceAddress = device.Id.Name; - _deviceType = deviceType; - _session = session; - _device = device; + Address = device.Id.Name; + Type = deviceType; + Session = session; + OneWireDevice = device; // Default the display name - _displayName = device.Id.Name; + DisplayName = device.Id.Name; // Default the read interval - if (Type == DeviceType.WindDirection || Type == DeviceType.WindSpeed) - _refreshFrequency = 1; - else - _refreshFrequency = 120; + RefreshFrequency = (Type == DeviceType.WindDirection || Type == DeviceType.WindSpeed) ? 1 : 120; // Load device data - bool bLoad = Load(); + var load = Load(); // If we couldn't load data then save the default data - if (!bLoad) + if (!load) Save(); } - #endregion - - #region Save and load - internal bool Load() { try @@ -103,15 +107,15 @@ namespace WeatherService.Devices using (var weatherData = new WeatherData()) { // Get the device data from the database - var deviceData = weatherData.Devices.FirstOrDefault(d => d.Address == _deviceAddress); + var deviceData = weatherData.Devices.FirstOrDefault(d => d.Address == Address); if (deviceData == null) return false; // Load the device data - _deviceId = deviceData.Id; - _displayName = deviceData.Name; - _refreshFrequency = deviceData.ReadInterval; + Id = deviceData.Id; + DisplayName = deviceData.Name; + RefreshFrequency = deviceData.ReadInterval; } return true; @@ -127,14 +131,14 @@ namespace WeatherService.Devices using (var weatherData = new WeatherData()) { // Get the device data from the database - var deviceData = weatherData.Devices.FirstOrDefault(d => d.Address == _deviceAddress); + var deviceData = weatherData.Devices.FirstOrDefault(d => d.Address == Address); if (deviceData == null) return false; // Save device data - deviceData.Name = _displayName; - deviceData.ReadInterval = _refreshFrequency; + deviceData.Name = DisplayName; + deviceData.ReadInterval = RefreshFrequency; weatherData.SaveChanges(); } @@ -142,13 +146,9 @@ namespace WeatherService.Devices return true; } - #endregion - - #region Internal cache refresh logic - internal bool DoCacheRefresh() { - switch (_refreshFrequency) + switch (RefreshFrequency) { case -1: // Do not refresh this device @@ -161,7 +161,7 @@ namespace WeatherService.Devices return true; default: - if (_lastRead == DateTime.MinValue) + if (LastRead == DateTime.MinValue) { // If we have never refreshed before then do it now RefreshCache(); @@ -170,10 +170,10 @@ namespace WeatherService.Devices } // Get the time since the last refresh - TimeSpan oTimeSpan = DateTime.Now - _lastRead; + var timeSpan = DateTime.Now - LastRead; // If it has been long enough then refresh the cache - if (oTimeSpan.TotalSeconds >= _refreshFrequency) + if (timeSpan.TotalSeconds >= RefreshFrequency) { RefreshCache(); @@ -187,95 +187,18 @@ namespace WeatherService.Devices internal virtual void RefreshCache() { // Store the current time - _lastRead = DateTime.Now; - } - - #endregion - - #region Public properties - - [DataMember] - public int Id - { - get { return _deviceId; } - set { _deviceId = value; } - } - - [DataMember] - public string Address - { - get { return _deviceAddress; } - set { _deviceAddress = value; } - } - - [DataMember] - public string DisplayName - { - get { return _displayName; } - set { _displayName = value; } - } - - internal owDevice OneWireDevice - { - get { return _device; } - } - - [DataMember] - public DateTime LastRead - { - get { return _lastRead; } - set { _lastRead = value; } - } - - [DataMember] - public long Operations - { - get { return _operationCount; } - set { _operationCount = value; } - } - - [DataMember] - public long Errors - { - get { return _errorCount; } - set { _errorCount = value; } - } - - [DataMember] - public DeviceType Type - { - get { return _deviceType; } - set { _deviceType = value; } - } - - [DataMember] - public int RefreshFrequency - { - get { return _refreshFrequency; } - set { _refreshFrequency = value; } - } - - [DataMember] - public Dictionary Values - { - get { return _valueList; } + LastRead = DateTime.Now; } [DataMember] public List SupportedValues { - get { return _valueList.Keys.ToList(); } + get { return Values.Keys.ToList(); } } - #endregion - - #region Public methods - public Value GetValue(WeatherValueType valueType) { - return _valueList[valueType]; + return Values[valueType]; } - - #endregion } } \ No newline at end of file diff --git a/Devices/HumidityDevice.cs b/Devices/HumidityDevice.cs index 1f408c9..ace73f4 100644 --- a/Devices/HumidityDevice.cs +++ b/Devices/HumidityDevice.cs @@ -1,5 +1,5 @@ -using System.Runtime.Serialization; using OneWireAPI; +using System.Runtime.Serialization; using WeatherService.Values; namespace WeatherService.Devices @@ -7,28 +7,19 @@ namespace WeatherService.Devices [DataContract] public class HumidityDevice : DeviceBase { - #region Member variables - private readonly Value _temperatureValue; private readonly Value _humidityValue; - #endregion - - #region Constructor - - public HumidityDevice(Session session, owDevice device) : base(session, device, DeviceType.Humidity) + public HumidityDevice(Session session, Device device) + : base(session, device, DeviceType.Humidity) { _temperatureValue = new Value(WeatherValueType.Temperature, this); _humidityValue = new Value(WeatherValueType.Humidity, this); - _valueList.Add(WeatherValueType.Temperature, _temperatureValue); - _valueList.Add(WeatherValueType.Humidity, _humidityValue); + Values.Add(WeatherValueType.Temperature, _temperatureValue); + Values.Add(WeatherValueType.Humidity, _humidityValue); } - #endregion - - #region Internal methods - internal override void RefreshCache() { _temperatureValue.SetValue(ReadTemperature()); @@ -40,33 +31,31 @@ namespace WeatherService.Devices internal double ReadTemperature() { // Cast the device to its specific type - owDeviceFamily26 oDevice = (owDeviceFamily26) _device; + var device = (DeviceFamily26) OneWireDevice; // Return the temperature from the device - return oDevice.GetTemperature(); + return device.GetTemperature(); } internal double ReadHumidity() { // Cast the device to its specific type - owDeviceFamily26 oDevice = (owDeviceFamily26) _device; + var device = (DeviceFamily26) OneWireDevice; // Get the supply voltage - double dSupplyVoltage = oDevice.GetSupplyVoltage(); + var supplyVoltage = device.GetSupplyVoltage(); // Get the output voltage - double dOutputVoltage = oDevice.GetOutputVoltage(); + var outputVoltage = device.GetOutputVoltage(); // Get the temperature - double dTemperature = oDevice.GetTemperature(); + var temperature = device.GetTemperature(); // Calculate the humidity - double dHumidity = (((dOutputVoltage / dSupplyVoltage) - 0.16F) / 0.0062F) / (1.0546F - 0.00216F * dTemperature); + var humidity = (((outputVoltage / supplyVoltage) - 0.16F) / 0.0062F) / (1.0546F - 0.00216F * temperature); // Return the result - return dHumidity; + return humidity; } - - #endregion } } \ No newline at end of file diff --git a/Devices/PressureDevice.cs b/Devices/PressureDevice.cs index 2b92cac..647c3e2 100644 --- a/Devices/PressureDevice.cs +++ b/Devices/PressureDevice.cs @@ -1,7 +1,7 @@ +using OneWireAPI; using System; using System.Collections.Generic; using System.Runtime.Serialization; -using OneWireAPI; using WeatherService.Values; namespace WeatherService.Devices @@ -9,32 +9,26 @@ namespace WeatherService.Devices [DataContract] public class PressureDevice : DeviceBase { - #region Constants - - private readonly byte[] _resetSequence = new byte[] { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0 }; // Binary sequence to reset the device - private readonly byte[] _readWord1Sequence = new byte[] { 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0 }; // Binary sequence to read word 1 - private readonly byte[] _readWord2Sequence = new byte[] { 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0 }; // Binary sequence to read word 2 - private readonly byte[] _readWord3Sequence = new byte[] { 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0 }; // Binary sequence to read word 3 - private readonly byte[] _readWord4Sequence = new byte[] { 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0 }; // Binary sequence to read word 4 - private readonly byte[] _readPressureSequence = new byte[] { 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0 }; // Binary sequence to read pressure - private readonly byte[] _readTemperatureSequence = new byte[] { 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0 }; // Binary sequence to read temperature + private readonly byte[] _resetSequence = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0 }; // Binary sequence to reset the device + private readonly byte[] _readWord1Sequence = { 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0 }; // Binary sequence to read word 1 + private readonly byte[] _readWord2Sequence = { 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0 }; // Binary sequence to read word 2 + private readonly byte[] _readWord3Sequence = { 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0 }; // Binary sequence to read word 3 + private readonly byte[] _readWord4Sequence = { 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0 }; // Binary sequence to read word 4 + private readonly byte[] _readPressureSequence = { 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0 }; // Binary sequence to read pressure + private readonly byte[] _readTemperatureSequence = { 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0 }; // Binary sequence to read temperature private const byte ChannelAccessCommand = 0xF5; private const byte ConfigRead = 0xEC; private const byte ConfigWrite = 0x8C; private const byte ConfigPulseRead = 0xC8; - #endregion - - #region Member variables - - private readonly owDeviceFamily12 _writeDevice; // Device for writing to the pressure sensor - private readonly owDeviceFamily12 _readDevice; // Device for reading from the pressure sensor + private readonly DeviceFamily12 _writeDevice; // Device for writing to the pressure sensor + private readonly DeviceFamily12 _readDevice; // Device for reading from the pressure sensor private readonly Value _temperatureValue; // Last temperature (degrees C) private readonly Value _pressureValue; // Last pressure (mbar) private bool _readCalibration; // Have we read the calibration constants? - + private int _calibration1; // Calibration constant private int _calibration2; // Calibration constant private int _calibration3; // Calibration constant @@ -42,93 +36,86 @@ namespace WeatherService.Devices private int _calibration5; // Calibration constant private int _calibration6; // Calibration constant - #endregion - - #region Constructor - - public PressureDevice(Session session, owDevice firstDevice, owDevice secondDevice) : base(session, firstDevice, DeviceType.Pressure) + public PressureDevice(Session session, Device firstDevice, Device secondDevice) + : base(session, firstDevice, DeviceType.Pressure) { // Get both devices - owDeviceFamily12 oDevice1 = (owDeviceFamily12) firstDevice; - owDeviceFamily12 oDevice2 = (owDeviceFamily12) secondDevice; + var device1 = (DeviceFamily12) firstDevice; + var device2 = (DeviceFamily12) secondDevice; // Get the state of both devices - byte[] baState1 = oDevice1.ReadDevice(); - byte[] baState2 = oDevice2.ReadDevice(); + var state1 = device1.ReadDevice(); + var state2 = device2.ReadDevice(); // If both devices have the same power state then this isn't a proper pressure device - if (oDevice1.IsPowered(baState1) == oDevice2.IsPowered(baState2)) + if (device1.IsPowered(state1) == device2.IsPowered(state2)) { // Throw an exception throw new Exception("Invalid TAI8570"); } // The powered device is the write device - sort this out and remember which is which - if (oDevice1.IsPowered(baState1)) + if (device1.IsPowered(state1)) { - _writeDevice = oDevice1; - _readDevice = oDevice2; + _writeDevice = device1; + _readDevice = device2; } else { - _writeDevice = oDevice2; - _readDevice = oDevice1; + _writeDevice = device2; + _readDevice = device1; } _temperatureValue = new Value(WeatherValueType.Temperature, this); _pressureValue = new Value(WeatherValueType.Pressure, this); - _valueList.Add(WeatherValueType.Temperature, _temperatureValue); - _valueList.Add(WeatherValueType.Pressure, _pressureValue); + Values.Add(WeatherValueType.Temperature, _temperatureValue); + Values.Add(WeatherValueType.Pressure, _pressureValue); } - #endregion - - #region PIO methods - private void PrepPioForWrite() { - byte[] baState = _writeDevice.ReadDevice(); - _writeDevice.SetLatchState(0, true, baState); - _writeDevice.SetLatchState(1, false, baState); - _writeDevice.WriteDevice(baState); + var state = _writeDevice.ReadDevice(); + _writeDevice.SetLatchState(0, true, state); + _writeDevice.SetLatchState(1, false, state); + _writeDevice.WriteDevice(state); - baState = _readDevice.ReadDevice(); - _readDevice.SetLatchState(0, false, baState); - _readDevice.SetLatchState(1, false, baState); - _readDevice.WriteDevice(baState); + state = _readDevice.ReadDevice(); + _readDevice.SetLatchState(0, false, state); + _readDevice.SetLatchState(1, false, state); + _readDevice.WriteDevice(state); } private void PrepPioForRead() { - byte[] baState = _readDevice.ReadDevice(); - _readDevice.SetLatchState(0, false, baState); - _readDevice.SetLatchState(1, false, baState); - _readDevice.WriteDevice(baState); + var state = _readDevice.ReadDevice(); + _readDevice.SetLatchState(0, false, state); + _readDevice.SetLatchState(1, false, state); + _readDevice.WriteDevice(state); - baState = _writeDevice.ReadDevice(); - _writeDevice.SetLatchState(0, false, baState); - _writeDevice.SetLatchState(1, false, baState); - _writeDevice.WriteDevice(baState); + state = _writeDevice.ReadDevice(); + _writeDevice.SetLatchState(0, false, state); + _writeDevice.SetLatchState(1, false, state); + _writeDevice.WriteDevice(state); } private bool OpenPio(int pio) { - byte[] baWriteState = _writeDevice.ReadDevice(); - byte[] baReadState = _readDevice.ReadDevice(); + var writeState = _writeDevice.ReadDevice(); + var readDevice = _readDevice.ReadDevice(); - _writeDevice.SetLatchState(pio, false, baWriteState); - _readDevice.SetLatchState(pio, false, baReadState); + _writeDevice.SetLatchState(pio, false, writeState); + _readDevice.SetLatchState(pio, false, readDevice); - _writeDevice.WriteDevice(baWriteState); - _writeDevice.WriteDevice(baReadState); + _writeDevice.WriteDevice(writeState); + _writeDevice.WriteDevice(readDevice); - baWriteState = _writeDevice.ReadDevice(); - baReadState = _readDevice.ReadDevice(); + writeState = _writeDevice.ReadDevice(); + readDevice = _readDevice.ReadDevice(); - bool bResult = (_writeDevice.GetLevel(pio, baWriteState) && _readDevice.GetLevel(pio, baReadState)); + var result = (_writeDevice.GetLevel(pio, writeState) && _readDevice.GetLevel(pio, readDevice)); - return bResult; + return result; } private bool OpenPioA() @@ -141,98 +128,90 @@ namespace WeatherService.Devices return OpenPio(1); } - #endregion - - #region Private methods - private bool SetupForWrite() { - byte[] data = new byte[3]; // Data buffer to send over the network + var data = new byte[3]; // Data buffer to send over the network short dataCount = 0; // How many bytes of data to send PrepPioForWrite(); - owAdapter.Select(_writeDevice.Id); + Adapter.Select(_writeDevice.Id); data[dataCount++] = ChannelAccessCommand; data[dataCount++] = ConfigWrite; data[dataCount++] = 0xFF; - owAdapter.SendBlock(data, dataCount); + Adapter.SendBlock(data, dataCount); - owAdapter.ReadByte(); + Adapter.ReadByte(); return true; } private bool SetupForRead() { - byte[] data = new byte[3]; // Data buffer to send over the network + var data = new byte[3]; // Data buffer to send over the network short dataCount = 0; // How many bytes of data to send PrepPioForRead(); - owAdapter.Select(_readDevice.Id); + Adapter.Select(_readDevice.Id); data[dataCount++] = ChannelAccessCommand; data[dataCount++] = ConfigRead; data[dataCount++] = 0xFF; - owAdapter.SendBlock(data, dataCount); + Adapter.SendBlock(data, dataCount); - owAdapter.ReadByte(); + Adapter.ReadByte(); return true; } private bool SetupForPulseRead() { - byte[] data = new byte[3]; // Data buffer to send over the network + var data = new byte[3]; // Data buffer to send over the network short dataCount = 0; // How many bytes of data to send PrepPioForWrite(); - owAdapter.Select(_readDevice.Id); + Adapter.Select(_readDevice.Id); data[dataCount++] = ChannelAccessCommand; data[dataCount++] = ConfigPulseRead; data[dataCount++] = 0xFF; - owAdapter.SendBlock(data, dataCount); + Adapter.SendBlock(data, dataCount); - owAdapter.ReadByte(); + Adapter.ReadByte(); return true; } private bool WriteBitSequence(IEnumerable sequence) { - bool result = false; + if (!SetupForWrite()) + return false; - if (SetupForWrite()) + foreach (var t in sequence) { - foreach (byte t in sequence) - { - SendBit(t != 0); - } - - SendBit(false); - - result = true; + SendBit(t != 0); } - return result; + SendBit(false); + + return true; } private byte[] ReadBitSequence(IEnumerable sequence) { - byte[] result = new byte[16]; + var result = new byte[16]; - if (WriteBitSequence(sequence)) - { - result = GetBits(16); - OpenPioB(); - } + if (!WriteBitSequence(sequence)) + return result; + + result = GetBits(16); + OpenPioB(); return result; } @@ -241,45 +220,45 @@ namespace WeatherService.Devices { if (value) { - owAdapter.SendBit(0); - owAdapter.SendBit(1); - owAdapter.SendBit(1); - owAdapter.SendBit(1); - owAdapter.SendBit(0); - owAdapter.SendBit(0); + Adapter.SendBit(0); + Adapter.SendBit(1); + Adapter.SendBit(1); + Adapter.SendBit(1); + Adapter.SendBit(0); + Adapter.SendBit(0); } else { - owAdapter.SendBit(0); - owAdapter.SendBit(0); - owAdapter.SendBit(1); - owAdapter.SendBit(0); - owAdapter.SendBit(0); - owAdapter.SendBit(0); + Adapter.SendBit(0); + Adapter.SendBit(0); + Adapter.SendBit(1); + Adapter.SendBit(0); + Adapter.SendBit(0); + Adapter.SendBit(0); } } private static bool ReadBit() { - owAdapter.ReadBit(); // Read PIO A #1 - owAdapter.ReadBit(); // Read PIO B #1 - owAdapter.ReadBit(); // Read PIO A #2 - owAdapter.ReadBit(); // Read PIO B #2 - owAdapter.ReadBit(); // Read PIO A #3 - owAdapter.ReadBit(); // Read PIO B #3 - owAdapter.ReadBit(); // Read PIO A #4 - short data = owAdapter.ReadBit(); + Adapter.ReadBit(); // Read PIO A #1 + Adapter.ReadBit(); // Read PIO B #1 + Adapter.ReadBit(); // Read PIO A #2 + Adapter.ReadBit(); // Read PIO B #2 + Adapter.ReadBit(); // Read PIO A #3 + Adapter.ReadBit(); // Read PIO B #3 + Adapter.ReadBit(); // Read PIO A #4 + var data = Adapter.ReadBit(); - bool result = (data == 1); + var result = (data == 1); - owAdapter.SendBit(0); // Write PIO A #1 - owAdapter.SendBit(1); // Write PIO B #1 - owAdapter.SendBit(0); // Write PIO A #2 - owAdapter.SendBit(1); // Write PIO B #2 - owAdapter.SendBit(1); // Write PIO A #3 - owAdapter.SendBit(1); // Write PIO B #3 - owAdapter.SendBit(1); // Write PIO A #4 - owAdapter.SendBit(1); // Write PIO B #4 + Adapter.SendBit(0); // Write PIO A #1 + Adapter.SendBit(1); // Write PIO B #1 + Adapter.SendBit(0); // Write PIO A #2 + Adapter.SendBit(1); // Write PIO B #2 + Adapter.SendBit(1); // Write PIO A #3 + Adapter.SendBit(1); // Write PIO B #3 + Adapter.SendBit(1); // Write PIO A #4 + Adapter.SendBit(1); // Write PIO B #4 return result; } @@ -291,16 +270,16 @@ namespace WeatherService.Devices private bool CheckConversionStatus() { - int i; + int index; - if (!SetupForPulseRead()) + if (!SetupForPulseRead()) return false; - for (i = 0; i < 100; i++) - if (owAdapter.SendBit(0) == 0) + for (index = 0; index < 100; index++) + if (Adapter.SendBit(0) == 0) break; - return (i < 100); + return (index < 100); } private bool ReadCalibrationConstants() @@ -309,13 +288,13 @@ namespace WeatherService.Devices if (!Reset()) return false; - byte[] word1 = ReadBitSequence(_readWord1Sequence); + var word1 = ReadBitSequence(_readWord1Sequence); - byte[] word2 = ReadBitSequence(_readWord2Sequence); + var word2 = ReadBitSequence(_readWord2Sequence); - byte[] word3 = ReadBitSequence(_readWord3Sequence); + var word3 = ReadBitSequence(_readWord3Sequence); - byte[] word4 = ReadBitSequence(_readWord4Sequence); + var word4 = ReadBitSequence(_readWord4Sequence); _calibration1 = _calibration2 = _calibration3 = _calibration4 = _calibration5 = _calibration6 = 0; @@ -383,17 +362,17 @@ namespace WeatherService.Devices private byte[] GetBits(byte bitCount) { - byte[] result = new byte[bitCount]; + var result = new byte[bitCount]; - if (SetupForRead()) + if (!SetupForRead()) + return result; + + for (var index = 0; index < bitCount; index++) { - for (int i = 0; i < bitCount; i++) - { - if (ReadBit()) - result[i] = 1; - else - result[i] = 0; - } + if (ReadBit()) + result[index] = 1; + else + result[index] = 0; } return result; @@ -401,30 +380,30 @@ namespace WeatherService.Devices private int ReadValue(IEnumerable sequence) { - int result = 0; + var result = 0; - if (!Reset()) + if (!Reset()) return 0; - if (!WriteBitSequence(sequence)) + if (!WriteBitSequence(sequence)) return 0; - if (!CheckConversionStatus()) + if (!CheckConversionStatus()) return 0; - if (!OpenPioA()) + if (!OpenPioA()) return 0; - byte[] data = GetBits(16); + var data = GetBits(16); - if (!OpenPioB()) + if (!OpenPioB()) return 0; - for (int i = 0; i < 16; i++) + for (var index = 0; index < 16; index++) { result = (result << 1); - if (data[i] == 1) + if (data[index] == 1) result = result + 1; } @@ -433,16 +412,16 @@ namespace WeatherService.Devices private bool ReadSensorData() { - int pressure = ReadValue(_readPressureSequence); - int temperature = ReadValue(_readTemperatureSequence); + var pressure = ReadValue(_readPressureSequence); + var temperature = ReadValue(_readTemperatureSequence); double calibrationTemperature = (8 * _calibration5) + 20224; - double temperatureDifference = temperature - calibrationTemperature; + var temperatureDifference = temperature - calibrationTemperature; _temperatureValue.SetValue(20 + ((temperatureDifference * (_calibration6 + 50)) / 10240)); - double offset = _calibration2 * 4 + (((_calibration4 - 512) * temperatureDifference) / 4096); - double sensitivity = _calibration1 + ((_calibration3 * temperatureDifference) / 1024) + 24576; - double actualPressure = ((sensitivity * (pressure - 7168)) / 16384) - offset; + var offset = _calibration2 * 4 + (((_calibration4 - 512) * temperatureDifference) / 4096); + var sensitivity = _calibration1 + ((_calibration3 * temperatureDifference) / 1024) + 24576; + var actualPressure = ((sensitivity * (pressure - 7168)) / 16384) - offset; _pressureValue.SetValue((actualPressure / 32) + 250); @@ -463,10 +442,6 @@ namespace WeatherService.Devices throw new Exception("Error reading Pressure and Temperature values"); } - #endregion - - #region Internal methods - internal override void RefreshCache() { ReadDevice(); @@ -474,8 +449,6 @@ namespace WeatherService.Devices base.RefreshCache(); } - #endregion - #region Elevation code (not used yet) //private double m_dElevation = 0.0; // Height above sea level (meters) diff --git a/Devices/RainDevice.cs b/Devices/RainDevice.cs index b818104..79be7b5 100644 --- a/Devices/RainDevice.cs +++ b/Devices/RainDevice.cs @@ -1,5 +1,5 @@ -using System.Runtime.Serialization; using OneWireAPI; +using System.Runtime.Serialization; using WeatherService.Values; namespace WeatherService.Devices @@ -7,8 +7,6 @@ namespace WeatherService.Devices [DataContract] public class RainDevice : DeviceBase { - #region Member variables - private readonly Value _recentValue; private readonly uint _clearedCount; // Counter at least clear @@ -17,34 +15,26 @@ namespace WeatherService.Devices private uint _startupCount; // Counter at startup private bool _initialized; - #endregion - - #region Constructor - - public RainDevice(Session session, owDevice device) + public RainDevice(Session session, Device device) : base(session, device, DeviceType.Rain) { // TODO - Read the count as of the last counter clearing _clearedCount = 150; // Get a reference to the device - owDeviceFamily1D counter = (owDeviceFamily1D) _device; + var counter = (DeviceFamily1D) OneWireDevice; // Get the current counter _lastCount = counter.GetCounter(15); // Setup the rain value _recentValue = new Value(WeatherValueType.Rain, this); - _valueList.Add(WeatherValueType.Rain, _recentValue); + Values.Add(WeatherValueType.Rain, _recentValue); } - #endregion - - #region Internal methods - internal override void RefreshCache() { - double recentRain = ReadRecentRainfall(); + var recentRain = ReadRecentRainfall(); _recentValue.SetValue(recentRain); @@ -54,7 +44,7 @@ namespace WeatherService.Devices internal double ReadSessionRainfall() { // Get a reference to the device - owDeviceFamily1D counter = (owDeviceFamily1D) _device; + var counter = (DeviceFamily1D) OneWireDevice; // If we haven't initialized then do it now if (!_initialized) @@ -66,7 +56,7 @@ namespace WeatherService.Devices } // Get the current counter - uint currentCount = counter.GetCounter(15); + var currentCount = counter.GetCounter(15); // Get the amount of rain since the last check return (currentCount - _startupCount) * 0.2; @@ -75,27 +65,27 @@ namespace WeatherService.Devices internal double ReadRecentRainfall() { // Get a reference to the device - owDeviceFamily1D counter = (owDeviceFamily1D) _device; + var counter = (DeviceFamily1D) OneWireDevice; // Get the current counter - uint currentCount = counter.GetCounter(15); + var currentCount = counter.GetCounter(15); // Get the amount of rain since the last check - double rainValue = (currentCount - _lastCount) * 0.2; + var rainValue = (currentCount - _lastCount) * 0.2; // Store the last counter _lastCount = currentCount; - + return rainValue; } internal double ReadTotalRainfall() { // Get a reference to the device - owDeviceFamily1D counter = (owDeviceFamily1D) _device; + var counter = (DeviceFamily1D) OneWireDevice; // Get the current counter - uint currentCount = counter.GetCounter(15); + var currentCount = counter.GetCounter(15); // Get the amount of rain since the last check double rainValue = (currentCount - _clearedCount) * 0.2F; @@ -105,7 +95,5 @@ namespace WeatherService.Devices return rainValue; } - - #endregion } } \ No newline at end of file diff --git a/Devices/TemperatureDevice.cs b/Devices/TemperatureDevice.cs index 77bbf1e..8b490e6 100644 --- a/Devices/TemperatureDevice.cs +++ b/Devices/TemperatureDevice.cs @@ -1,5 +1,5 @@ -using System.Runtime.Serialization; using OneWireAPI; +using System.Runtime.Serialization; using WeatherService.Values; namespace WeatherService.Devices @@ -7,26 +7,17 @@ namespace WeatherService.Devices [DataContract] public class TemperatureDevice : DeviceBase { - #region Member variables - - private readonly Value _temperatureValue; // Cached temperature + private readonly Value _temperatureValue; - #endregion - - #region Constructor - - public TemperatureDevice(Session session, owDevice device) : base(session, device, DeviceType.Temperature) + public TemperatureDevice(Session session, Device device) + : base(session, device, DeviceType.Temperature) { // Create the new value object _temperatureValue = new Value(WeatherValueType.Temperature, this); - _valueList.Add(WeatherValueType.Temperature, _temperatureValue); + Values.Add(WeatherValueType.Temperature, _temperatureValue); } - #endregion - - #region Internal methods - internal override void RefreshCache() { // Read the current temperature @@ -38,12 +29,10 @@ namespace WeatherService.Devices internal double ReadTemperature() { // Cast the device to its specific type - owDeviceFamily10 temperatureDevice = (owDeviceFamily10) _device; + var temperatureDevice = (DeviceFamily10) OneWireDevice; // Return the temperature from the device return temperatureDevice.GetTemperature(); } - - #endregion } } \ No newline at end of file diff --git a/Devices/WindDirectionDevice.cs b/Devices/WindDirectionDevice.cs index 0adb492..7e15e94 100644 --- a/Devices/WindDirectionDevice.cs +++ b/Devices/WindDirectionDevice.cs @@ -1,17 +1,15 @@ -using System.Runtime.Serialization; using OneWireAPI; +using System.Runtime.Serialization; using WeatherService.Values; namespace WeatherService.Devices { - #region Enumerations - [DataContract] public enum WindDirection { [EnumMember] North, - + [EnumMember] NorthNorthEast, @@ -61,13 +59,9 @@ namespace WeatherService.Devices Unknown = -1 } - #endregion - [DataContract] public class WindDirectionDevice : DeviceBase { - #region Constants - private const double WindowOffset = 0.7; private readonly double[,] _lookupTable = { {4.66, 4.66, 2.38, 4.66}, // 0 @@ -87,44 +81,32 @@ namespace WeatherService.Devices {4.66, 4.66, 4.66, 2.38}, // 14 {4.66, 4.66, 3.18, 3.18} }; // 15 - #endregion - - #region Member variables - private readonly Value _directionValue; // Cached direction value private bool _initialized; // Has the device been initialized - #endregion - - #region Constructor - - public WindDirectionDevice(Session session, owDevice device) + public WindDirectionDevice(Session session, Device device) : base(session, device, DeviceType.WindDirection) { // Create the value _directionValue = new Value(WeatherValueType.WindDirection, this); - _valueList.Add(WeatherValueType.WindDirection, _directionValue); + Values.Add(WeatherValueType.WindDirection, _directionValue); } - #endregion - - #region Internal methods - internal override void RefreshCache() { - _directionValue.SetValue((double)ReadDirection()); + _directionValue.SetValue((double) ReadDirection()); base.RefreshCache(); } internal WindDirection ReadDirection() { - int direction = -1; // Decoded direction + var direction = -1; // Decoded direction // Cast the device as the specific device - owDeviceFamily20 voltage = (owDeviceFamily20)_device; + var voltage = (DeviceFamily20) OneWireDevice; // If we haven't initialized the device we need to do it now if (!_initialized) @@ -137,10 +119,10 @@ namespace WeatherService.Devices } // Get the array of voltages from the device - double[] voltages = voltage.GetVoltages(); + var voltages = voltage.GetVoltages(); // Loop over the lookup table to find the direction that maps to the voltages - for (int i = 0; i < 16; i++) + for (var i = 0; i < 16; i++) { if (((voltages[0] <= _lookupTable[i, 0] + WindowOffset) && (voltages[0] >= _lookupTable[i, 0] - WindowOffset)) && ((voltages[1] <= _lookupTable[i, 1] + WindowOffset) && (voltages[1] >= _lookupTable[i, 1] - WindowOffset)) && @@ -153,9 +135,7 @@ namespace WeatherService.Devices } // Return the direction - return (WindDirection)direction; + return (WindDirection) direction; } - - #endregion } } \ No newline at end of file diff --git a/Devices/WindSpeedDevice.cs b/Devices/WindSpeedDevice.cs index de6da89..b042d19 100644 --- a/Devices/WindSpeedDevice.cs +++ b/Devices/WindSpeedDevice.cs @@ -1,6 +1,6 @@ +using OneWireAPI; using System.Diagnostics; using System.Runtime.Serialization; -using OneWireAPI; using WeatherService.Values; namespace WeatherService.Devices @@ -8,28 +8,19 @@ namespace WeatherService.Devices [DataContract] public class WindSpeedDevice : DeviceBase { - #region Member variables - private readonly Value _speedValue; // Cached speed value private long _lastTicks; // Last time we checked the counter private uint _lastCount; // The count at the last check - #endregion - - #region Constructor - - public WindSpeedDevice(Session session, owDevice device) : base(session, device, DeviceType.WindSpeed) + public WindSpeedDevice(Session session, Device device) + : base(session, device, DeviceType.WindSpeed) { _speedValue = new Value(WeatherValueType.WindSpeed, this); - _valueList.Add(WeatherValueType.WindSpeed, _speedValue); + Values.Add(WeatherValueType.WindSpeed, _speedValue); } - #endregion - - #region Internal methods - internal override void RefreshCache() { _speedValue.SetValue(ReadSpeed()); @@ -40,7 +31,7 @@ namespace WeatherService.Devices internal double ReadSpeed() { // Get a reference to the device - owDeviceFamily1D counterDevice = (owDeviceFamily1D) _device; + var counterDevice = (DeviceFamily1D) OneWireDevice; // Special case if we have never read before if (_lastTicks == 0) @@ -54,14 +45,14 @@ namespace WeatherService.Devices } // Get the current counter and time - uint currentCount = counterDevice.GetCounter(15); - long currentTicks = Stopwatch.GetTimestamp(); + var currentCount = counterDevice.GetCounter(15); + var currentTicks = Stopwatch.GetTimestamp(); // Get the time difference in seconds - double timeDifference = (double) (currentTicks - _lastTicks) / Stopwatch.Frequency; + var timeDifference = (double) (currentTicks - _lastTicks) / Stopwatch.Frequency; // Figure out how many revolutions per second in the last interval - double revolutionsPerSecond = ((currentCount - _lastCount) / timeDifference) / 2D; + var revolutionsPerSecond = ((currentCount - _lastCount) / timeDifference) / 2D; // Store the current time and counter _lastTicks = currentTicks; @@ -70,7 +61,5 @@ namespace WeatherService.Devices // Convert the revolutions per second to wind speed return (revolutionsPerSecond * 2.453F); } - - #endregion } } \ No newline at end of file diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs index 69020ae..3be5b01 100644 --- a/Properties/AssemblyInfo.cs +++ b/Properties/AssemblyInfo.cs @@ -1,36 +1,12 @@ using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("WeatherService")] +[assembly: AssemblyTitle("Weather Reporting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("WeatherService")] -[assembly: AssemblyCopyright("Copyright © 2012")] +[assembly: AssemblyProduct("Weather Reporting")] +[assembly: AssemblyCopyright("Copyright © Chris Kaczor 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("4d795cba-d705-4c00-8306-423403876429")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion("1.0.*")] diff --git a/Session.cs b/Session.cs index 5edd64a..25654de 100644 --- a/Session.cs +++ b/Session.cs @@ -44,7 +44,7 @@ namespace WeatherService Devices = new List(); // Create a new session - OneWireSession = new owSession(); + OneWireSession = new OneWireAPI.Session(); } #endregion @@ -75,7 +75,7 @@ namespace WeatherService device.Operations++; } } - catch (owException exception) + catch (OneWireException exception) { DeviceErrors++; device.Errors++; @@ -104,7 +104,7 @@ namespace WeatherService } } - private void AddWeatherDevice(owDevice device) + private void AddWeatherDevice(Device device) { // TODO - Handle device mapping for multiple devices that use the same family code @@ -113,10 +113,10 @@ namespace WeatherService case 0x12: TMEX.FileEntry fileEntry = new TMEX.FileEntry(); // Entry to describe a file byte[] fileData = new byte[8]; // File data - owIdentifier deviceID; // Identifier for the other device + Identifier deviceID; // Identifier for the other device // Select this device - owAdapter.Select(device.Id); + Adapter.Select(device.Id); // Setup to try to open the pressure sensor file fileEntry.Name = System.Text.Encoding.ASCII.GetBytes("8570"); @@ -135,10 +135,10 @@ namespace WeatherService TMEX.TMCloseFile(OneWireSession.SessionHandle, OneWireSession.StateBuffer, fileHandle); // Create an ID so we can get the string name - deviceID = new owIdentifier(fileData); + deviceID = new Identifier(fileData); // Find the other device - owDevice otherDevice = (owDevice) OneWireSession.Network.Devices[deviceID.Name]; + Device otherDevice = (Device) OneWireSession.Network.Devices[deviceID.Name]; // Create a new pressure device and it to the the list Devices.Add(new PressureDevice(this, device, otherDevice)); @@ -217,7 +217,7 @@ namespace WeatherService //FireInitialized(); } - private void HandleDeviceAdded(owDevice device) + private void HandleDeviceAdded(Device device) { AddWeatherDevice(device); } @@ -270,7 +270,7 @@ namespace WeatherService public long DeviceErrors { get; private set; } - internal owSession OneWireSession { get; private set; } + internal OneWireAPI.Session OneWireSession { get; private set; } #endregion } diff --git a/SignalR/WeatherHub.cs b/SignalR/WeatherHub.cs index 76d795f..714ef0e 100644 --- a/SignalR/WeatherHub.cs +++ b/SignalR/WeatherHub.cs @@ -1,13 +1,19 @@ -using Microsoft.AspNet.SignalR; -using Microsoft.AspNet.SignalR.Hubs; +using System.Collections.Generic; +using Microsoft.AspNet.SignalR; +using WeatherService.Devices; +using WeatherService.Remote; namespace WeatherService.SignalR { public class WeatherHub : Hub { - public void Send(string message) + public List GetDevices() { - Clients.Others.addMessage(message); + var devices = WeatherServiceCommon.GetDevices(); + + //var json = JsonConvert.SerializeObject(devices); + + return devices; } } } diff --git a/Values/Value.cs b/Values/Value.cs index b66c230..504653f 100644 --- a/Values/Value.cs +++ b/Values/Value.cs @@ -243,7 +243,7 @@ namespace WeatherService.Values // Save the reading using (var weatherArchiveData = new WeatherArchiveData(timeStamp.Year)) { - var reading = new Data.Reading + var reading = new Data.ReadingData { DeviceId = _ownerDevice.Id, Type = (int) ValueType, diff --git a/WeatherService.csproj b/WeatherService.csproj index 3b21c60..a4849fd 100644 --- a/WeatherService.csproj +++ b/WeatherService.csproj @@ -121,9 +121,9 @@ - - - + + +