Exemplo n.º 1
0
 protected virtual DeviceData internalParse(String rawText)
 {
     DeviceData deviceData = new DeviceData();
     String[] tokens = rawText.Split(new String[] { "<br>", "<hr>", " ", "<b>", "</b>" }, StringSplitOptions.None);
     for (int i = 0; i < tokens.Length; i++) {
         String token = tokens[i].Trim();
         if (token.Length > 0) {
             if (token.StartsWith("uRADMonitor", StringComparison.OrdinalIgnoreCase)) {
                 deviceData.DeviceInformation.DeviceID = tokens[i + 1];
                 i++;
             }
             else if (token.StartsWith("type", StringComparison.OrdinalIgnoreCase)) {
                 deviceData.DeviceInformation.DeviceModel = (DeviceModelType)int.Parse(token.Split(':')[1]);
             }
             else if (token.StartsWith("hw", StringComparison.OrdinalIgnoreCase)) {
                 deviceData.DeviceInformation.HardwareVersion = int.Parse(token.Split(':')[1]);
             }
             else if (token.StartsWith("sw", StringComparison.OrdinalIgnoreCase)) {
                 deviceData.DeviceInformation.FirmwareVersion = int.Parse(token.Split(':')[1]);
                 deviceData.DeviceInformation.Detector = tokens[i + 1];
                 i++;
             }
             else if (token.StartsWith("radiation", StringComparison.OrdinalIgnoreCase)) {
                 String radiation = token.Split(':')[1];
                 deviceData.Radiation = int.Parse(radiation.Substring(0, radiation.IndexOf("CPM", StringComparison.OrdinalIgnoreCase)));
                 if (tokens[i + 1].Contains("(")) {
                     String radiationAvg = tokens[++i];
                     deviceData.RadiationAverage = double.Parse(radiationAvg.Substring(1, radiationAvg.IndexOf("CPM", StringComparison.OrdinalIgnoreCase) - 1), NumberStyles.AllowDecimalPoint, numberFormatInfo);
                 }
             }
             else if (token.StartsWith("average", StringComparison.OrdinalIgnoreCase)) {
                 String radiationAvg = token.Split(':')[1];
                 deviceData.RadiationAverage = double.Parse(radiationAvg.Substring(0, radiationAvg.IndexOf("CPM", StringComparison.OrdinalIgnoreCase)), NumberStyles.AllowDecimalPoint, numberFormatInfo);
             }
             else if (token.StartsWith("temp", StringComparison.OrdinalIgnoreCase)) {
                 String temperature = token.Split(':')[1];
                 deviceData.Temperature = double.Parse(temperature.Substring(0, temperature.IndexOf("C", StringComparison.OrdinalIgnoreCase)), NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, numberFormatInfo);
             }
             else if (token.StartsWith("P", StringComparison.OrdinalIgnoreCase) && token.EndsWith("Pa", StringComparison.OrdinalIgnoreCase)) {
                 String pressure = token.Split(':')[1];
                 deviceData.Pressure = double.Parse(pressure.Substring(0, pressure.IndexOf("Pa", StringComparison.OrdinalIgnoreCase)), NumberStyles.AllowDecimalPoint, numberFormatInfo);
             }
             else if (token.StartsWith("vol", StringComparison.OrdinalIgnoreCase)) {
                 String voltage = token.Split(':')[1];
                 deviceData.Voltage = int.Parse(voltage.Substring(0, voltage.IndexOf("V", StringComparison.OrdinalIgnoreCase)));
                 if (tokens[i + 1].Contains("/")) {
                     deviceData.VoltagePercent = int.Parse(tokens[i + 1].TrimStart('(').TrimEnd(')').Split('/')[0].TrimEnd('%'));
                 }
                 else {
                     if (tokens[i + 1].StartsWith("duty")) {
                         deviceData.VoltagePercent = int.Parse(tokens[i + 1].Split(':')[1].TrimEnd('%'));
                     }
                     else {
                         deviceData.VoltagePercent = int.Parse(tokens[i + 1].TrimStart('(').TrimEnd(')').TrimEnd('%'));
                     }
                 }
                 i++;
             }
             else if (token.StartsWith("uptime", StringComparison.OrdinalIgnoreCase)) {
                 String uptime = token.Split(':')[1];
                 deviceData.Uptime = int.Parse(uptime.Substring(0, uptime.IndexOf("s", StringComparison.OrdinalIgnoreCase)));
             }
             else if (token.StartsWith("wdt", StringComparison.OrdinalIgnoreCase)) {
                 String wdt = token.Split(':')[1];
                 deviceData.WDT = int.Parse(wdt.Substring(0, wdt.IndexOf("s", StringComparison.OrdinalIgnoreCase)));
             }
             else if (token.StartsWith("ip", StringComparison.OrdinalIgnoreCase)) {
                 deviceData.IPAddress = token.Split(':')[1];
             }
             else if (token.StartsWith("server", StringComparison.OrdinalIgnoreCase)) {
                 deviceData.ServerIPAddress = token.Split(':')[1];
             }
             else if (token.StartsWith("eth", StringComparison.OrdinalIgnoreCase)) {
                 deviceData.IPAddress = token.Split(':')[1];
                 deviceData.ServerIPAddress = tokens[++i].TrimStart('(').TrimEnd(')');
             }
             else if (token.StartsWith("http", StringComparison.OrdinalIgnoreCase)) {
                 deviceData.ServerResponseCode = token.Split(':')[1];
             }
         }
     }
     return deviceData;
 }
 public DeviceDataFetcherEventArgs(DeviceData deviceData)
 {
     this.DeviceData = deviceData;
 }
 protected virtual void OnSuccess(DeviceData deviceData)
 {
     DeviceDataFetcherEventHandler handler = DeviceDataFetcherEventHandler;
     if (handler != null) {
         handler(this, new DeviceDataFetcherEventArgs(deviceData));
     }
 }
Exemplo n.º 4
0
        public DeviceData ReadData()
        {
            if (!started) {
                throw new Exception("Device is not started.");
            }

            DeviceData deviceData = new DeviceData();
            deviceData.DeviceInformation.DeviceID = this.DeviceId;
            deviceData.DeviceInformation.Detector = this.DetectorName;
            deviceData.DeviceInformation.FirmwareVersion = this.FirmwareVersion;
            deviceData.DeviceInformation.HardwareVersion = this.HardwareVersion;
            deviceData.DeviceInformation.DeviceModel = this.Model;

            int secondsElapsedFromStartTime = (int)DateTime.Now.Subtract(this.startTime.Value).TotalSeconds;

            //  0s ...  59s  1st reading
            // 60s ... 119s  2nd reading
            // .........................
            // ............  Nth reading
            int index = (secondsElapsedFromStartTime / 60) % this.readings.Count;

            DeviceReadings deviceReadings = this.readings[index];

            deviceData.Temperature = deviceReadings.Temperature;
            deviceData.Radiation = deviceReadings.Radiation;
            deviceData.RadiationAverage = deviceReadings.RadiationAverage;
            deviceData.Pressure = deviceReadings.Pressure;
            deviceData.Voltage = deviceReadings.Voltage;
            deviceData.VoltagePercent = deviceReadings.VoltagePercent;
            deviceData.Uptime = secondsElapsedFromStartTime;
            deviceData.WDT = secondsElapsedFromStartTime % 60;
            deviceData.ServerResponseCode = this.ServerResponseCode.Code.ToString();
            deviceData.IPAddress = this.IPAddress;
            deviceData.ServerIPAddress = this.ServerIPAddress;

            return deviceData;
        }
Exemplo n.º 5
0
        private void updateDeviceData(DeviceData deviceData)
        {
            // Do not update data if user disables polling before first update.
            if (!this.settings.IsPollingEnabled) {
                return;
            }

            DateTime now = DateTime.UtcNow;
            DateTime dataReadingsTimeStamp = now.AddSeconds(-(deviceData.WDT % 60));

            this.updateDeviceInformation(deviceData.DeviceInformation);

            try {
                if (this.settings.IsLoggingEnabled && this.settings.IsDataLoggingEnabled) {
                    if (!this.lastDataReadingTimestamp.HasValue || (this.lastDataReadingTimestamp.HasValue && now.Subtract(this.lastDataReadingTimestamp.Value).TotalSeconds >= 60)) {
                        this.lastDataReadingTimestamp = dataReadingsTimeStamp;
                        if (this.settings.DataLoggingToSeparateFile) {
                            LoggerManager.GetInstance().GetLogger(Program.DataLoggerName).Write(JsonConvert.SerializeObject(deviceData));
                        }
                        else {
                            LoggerManager.GetInstance().GetLogger(Program.LoggerName).Write(JsonConvert.SerializeObject(deviceData));
                        }
                    }
                }
            }
            catch (Exception loggingException) {
                Debug.WriteLine(loggingException.ToString());
            }

            // Use normalized name only for conversions.
            String radiationDetectorName = RadiationDetector.Normalize(deviceData.DeviceInformation.Detector);
            if (this.settings.RadiationUnitType == Core.RadiationUnitType.Cpm) {
                this.viewOnlyTextBoxRadiation.Text = String.Format("{0} cpm", deviceData.Radiation);
                this.viewOnlyTextBoxRadiationAverage.Text = String.Format("{0} cpm", deviceData.RadiationAverage);
            }
            else {
                if (RadiationDetector.IsKnown(radiationDetectorName)) {
                    RadiationDetector radiationDetector = RadiationDetector.GetByName(radiationDetectorName);
                    if (this.settings.RadiationUnitType == Core.RadiationUnitType.uSvH) {
                        this.viewOnlyTextBoxRadiation.Text = String.Format("{0} µSv/h", MathX.Truncate(Radiation.CpmToMicroSvPerHour(deviceData.Radiation, radiationDetector.Factor), 4));
                        this.viewOnlyTextBoxRadiationAverage.Text = String.Format("{0} µSv/h", MathX.Truncate(Radiation.CpmToMicroSvPerHour((double)deviceData.RadiationAverage, radiationDetector.Factor), 4));
                    }
                    else if (this.settings.RadiationUnitType == Core.RadiationUnitType.uRemH) {
                        this.viewOnlyTextBoxRadiation.Text = String.Format("{0} µrem/h", MathX.Truncate(Radiation.CpmToMicroRemPerHour(deviceData.Radiation, radiationDetector.Factor), 2));
                        this.viewOnlyTextBoxRadiationAverage.Text = String.Format("{0} µrem/h", MathX.Truncate(Radiation.CpmToMicroRemPerHour((double)deviceData.RadiationAverage, radiationDetector.Factor), 2));
                    }
                    else {
                        // If conversion to other radiation unit type is not implemented fallback silently to cpm.
                        this.settings.RadiationUnitType = Core.RadiationUnitType.Cpm;
                        this.settings.Commit();
                        this.viewOnlyTextBoxRadiation.Text = String.Format("{0} cpm", deviceData.Radiation);
                        this.viewOnlyTextBoxRadiationAverage.Text = String.Format("{0} cpm", deviceData.RadiationAverage);
                    }
                }
                else {
                    // If detector is not known fallback silently to cpm.
                    this.settings.RadiationUnitType = Core.RadiationUnitType.Cpm;
                    this.settings.Commit();
                    this.viewOnlyTextBoxRadiation.Text = String.Format("{0} cpm", deviceData.Radiation);
                    this.viewOnlyTextBoxRadiationAverage.Text = String.Format("{0} cpm", deviceData.RadiationAverage);
                }
            }

            if (this.settings.TemperatureUnitType == Core.TemperatureUnitType.Celsius) {
                this.viewOnlyTextBoxTemperature.Text = String.Format("{0} °C", deviceData.Temperature);
            }
            else if (this.settings.TemperatureUnitType == Core.TemperatureUnitType.Fahrenheit) {
                this.viewOnlyTextBoxTemperature.Text = String.Format("{0} °F", Temperature.CelsiusToFahrenheit(deviceData.Temperature));
            }
            else {
                // If conversion to other temperature unit type is not implemented fallback silently to default (Celsius).
                this.settings.TemperatureUnitType = Core.TemperatureUnitType.Celsius;
                this.settings.Commit();
                this.viewOnlyTextBoxTemperature.Text = String.Format("{0} °C", deviceData.Temperature);
            }
            if (deviceData.Pressure.HasValue) {
                this.labelPressure.Enabled = true;
                this.pressureToolStripMenuItem.Enabled = true;
                if (this.settings.PressureUnitType == Core.PressureUnitType.Pa) {
                    this.viewOnlyTextBoxPressure.Text = String.Format("{0} Pa", deviceData.Pressure.Value);
                }
                else if (this.settings.PressureUnitType == Core.PressureUnitType.kPa) {
                    this.viewOnlyTextBoxPressure.Text = String.Format("{0} kPa", Pressure.PascalToKiloPascal(deviceData.Pressure.Value));
                }
                else {
                    // If conversion to other pressure unit type is not implemented fallback silently to default (Pascal).
                    this.settings.PressureUnitType = Core.PressureUnitType.Pa;
                    this.settings.Commit();
                    this.viewOnlyTextBoxPressure.Text = String.Format("{0} Pa", deviceData.Pressure.Value);
                }
            }
            else {
                this.labelPressure.Enabled = false;
                this.pressureToolStripMenuItem.Enabled = false;
                this.viewOnlyTextBoxPressure.Text = String.Empty;
            }

            // Update Settings.
            bool commitSettings = false;
            if (this.settings.HasPressureSensor != deviceData.Pressure.HasValue) {
                this.settings.HasPressureSensor = deviceData.Pressure.HasValue;
                commitSettings = true;
            }
            if (!(radiationDetectorName).Equals(this.settings.DetectorName)) {
                this.settings.DetectorName = radiationDetectorName;
                // If the detector is known and the radiation notification value was not set fallback to default values.
                if (this.settings.DetectorName != null &&
                        RadiationDetector.IsKnown(this.settings.DetectorName) &&
                        this.settings.RadiationNotificationUnitType == RadiationUnitType.Cpm &&
                        this.settings.RadiationNotificationValue == 0) {
                    this.settings.RadiationNotificationValue = DefaultSettings.RadiationNotificationValue;
                    this.settings.RadiationNotificationUnitType = DefaultSettings.RadiationNotificationUnitType;
                }
                commitSettings = true;
            }
            if (commitSettings) {
                this.settings.Commit();
            }

            this.viewOnlyTextBoxVoltage.Text = String.Format("{0} V ({1}%)", deviceData.Voltage, deviceData.VoltagePercent);
            this.viewOnlyTextBoxWDT.Text = String.Format("{0} s", deviceData.WDT);
            this.updateDeviceStatus(String.Format("Device received {0} from server.", (HttpStatus.GetReason(int.Parse(deviceData.ServerResponseCode)) != null) ? String.Format("{0} ({1})", deviceData.ServerResponseCode, HttpStatus.GetReason(int.Parse(deviceData.ServerResponseCode))) : deviceData.ServerResponseCode));

            // Update ToolTip text for notification area icon.
            StringBuilder notifyIconText = new StringBuilder(String.Format("Radiation: {0}, Average: {1}\nTemperature: {2}", this.viewOnlyTextBoxRadiation.Text, this.viewOnlyTextBoxRadiationAverage.Text, this.viewOnlyTextBoxTemperature.Text));
            if (settings.HasPressureSensor) {
                notifyIconText.Append(String.Format(", Pressure: {0}", this.viewOnlyTextBoxPressure.Text));
            }
            this.updateNotifyIconText(notifyIconText.ToString());

            this.updateDeviceUptime(deviceData.Uptime);

            if (deviceData.ServerResponseCode != HttpStatus.OK.Code.ToString()) {
                this.logger.Write(String.Format("Device received {0} from server (WDT={1})", deviceData.ServerResponseCode, deviceData.WDT));
                this.notifyIcon.Icon = (System.Drawing.Icon)global::uRADMonitorX.Properties.Resources.RadiationWithError;
                if (deviceData.WDT > 59) {
                    this.updateNotifyIconText("Device cannot send data to server...");
                }
                else {
                    // TODO: Ask Radu about this strange behavior (deviceData.ServerResponseCode == 0 && (WDT == 59 || WDT == 60)).
                }
            }
            else {
                this.notifyIcon.Icon = (System.Drawing.Icon)global::uRADMonitorX.Properties.Resources.RadiationIcon;
            }

            if (this.settings.AreNotificationsEnabled) {
                double currentTemperature = deviceData.Temperature;
                String currentTemperatureUnit = "C";

                if (this.settings.TemperatureNotificationUnitType == TemperatureUnitType.Fahrenheit) {
                    currentTemperature = Temperature.CelsiusToFahrenheit(deviceData.Temperature);
                    currentTemperatureUnit = "F";
                }

                double currentRadiation = deviceData.Radiation;
                String currentRadiationUnit = EnumHelper.GetEnumDescription<RadiationUnitType>(RadiationUnitType.Cpm);
                if (RadiationDetector.IsKnown(radiationDetectorName)) {
                    RadiationDetector radiationDetector = RadiationDetector.GetByName(radiationDetectorName);
                    if (this.settings.RadiationNotificationUnitType == RadiationUnitType.uSvH) {
                        currentRadiation = Radiation.CpmToMicroSvPerHour(currentRadiation, radiationDetector.Factor);
                    }
                    else if (this.settings.RadiationNotificationUnitType == RadiationUnitType.uRemH) {
                        currentRadiation = Radiation.CpmToMicroRemPerHour(currentRadiation, radiationDetector.Factor);
                    }
                    currentRadiationUnit = EnumHelper.GetEnumDescription<RadiationUnitType>(this.settings.RadiationNotificationUnitType);
                }
                else {
                    if (this.settings.RadiationNotificationUnitType != RadiationUnitType.Cpm) {
                        currentRadiation = 0; // Disable radiation notification if radiation value cannot be converted to uSv/h or uRem/h.
                    }
                }

                bool showBalloon = false;
                String balloonTitle = String.Empty;
                String balloonMessage = String.Empty;
                if (currentTemperature >= this.settings.HighTemperatureNotificationValue) {
                    balloonTitle = "High Temperature";
                    balloonMessage = String.Format("Temperature: {0} °{1}", currentTemperature, currentTemperatureUnit);
                    showBalloon = true;
                }
                if (this.settings.RadiationNotificationValue != 0 && currentRadiation >= this.settings.RadiationNotificationValue) {
                    if (balloonTitle.Length > 0) {
                        balloonTitle += "/";
                    }
                    if (balloonMessage.Length > 0) {
                        balloonMessage += "\n";
                    }
                    balloonTitle += "Radiation";
                    balloonMessage += String.Format("Radiation: {0} {1}", currentRadiation, currentRadiationUnit);
                    showBalloon = true;
                }
                if (showBalloon) {
                    balloonTitle += " Alert";

                    // Add the date and time when the event occurs to notification message. This is useful because
                    // Windows queues notifications when user is away from computer (e.g.: screen is locked).
                    // LINK: https://msdn.microsoft.com/en-us/library/windows/desktop/ee330740%28v=vs.85%29.aspx
                    balloonMessage += String.Format("\nEvent occurred at {0}.", now.ToLocalTime().ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.CurrentCulture));

                    // Do not show multiple notifications for the same readings. Usually when polling interval is lower than the device refresh period (60 seconds).
                    if (!notifyIconBalloonLastShownAt.HasValue || (this.notifyIconBalloonLastShownAt.HasValue && now.Subtract(this.notifyIconBalloonLastShownAt.Value).TotalSeconds >= 60)) {
                        this.notifyIcon.ShowBalloonTip(10000, balloonTitle, balloonMessage, ToolTipIcon.Info);
                        this.notifyIconBalloonLastShownAt = dataReadingsTimeStamp;
                    }
                }
            }
        }