Пример #1
0
        public override Evaluation GetEvaluation(double correctValue)
        {
            var allowedDeviation = correctValue / 100;
            var result           = Readings.Any(x => Math.Abs(x.Value - correctValue) > allowedDeviation) ? "discard" : "keep";

            return(new Evaluation(Name, result));
        }
Пример #2
0
        public void Read()
        {
            try
            {
                // Changes from idle to wait-for-trigger state.
                // May want to move to "Open". Unsure if state is changed back to idle upon scan completion.
                _v3497x.SCPI.INITiate.Command();

                // Sends trigger via bus source.
                _v3497x.SCPI.TRG.Command();

                // Transfers NVM readings to output buffer.
                _v3497x.SCPI.FETCh.QueryAllData(out string data);

                string[] dataSeparated = data.Split(',');

                // Remove previous readings.
                Readings.Clear();

                for (int i = 0; i < dataSeparated.Length; i += 2)
                {
                    // Parse sensor output from string into double and add to list of readings.
                    uint   key   = uint.Parse(dataSeparated[(i + 1)]) % 100;
                    double value = double.Parse(dataSeparated[i], System.Globalization.NumberStyles.Any);
                    Readings.Add(key, value);
                }
            }
            catch (Exception ex)
            {
                throw new DeviceCommandFailedException("Could not read from Keysight datalogger."
                                                       + Environment.NewLine + ex.Message);
            }
        }
Пример #3
0
        protected override void OnReceive(object message)
        {
            switch (message)
            {
            case RespondTemperature m when m.RequestId == TemperatureRequestCorrelactionId:
                if (m.Temperature.HasValue)
                {
                    var temperatureAvailable = new TemperatureAvailable(m.Temperature.Value);
                    RecordTemperatureReading(Context.Sender, temperatureAvailable);
                }
                else
                {
                    RecordTemperatureReading(Context.Sender, NoTemperatureAvailable.Instance);
                }
                break;

            case Terminated m:
                RecordTemperatureReading(Context.Sender, SensorNotAvailable.Instance);
                break;

            case TemperatureQueryCanceled m:
                foreach (var sensorActor in ActorRefToSensorId.Keys)
                {
                    Readings.Add(ActorRefToSensorId[sensorActor], SensorTimedOut.Instance);
                }
                Requester.Tell(new RespondFloorTemperatures(RequestId, Readings.ToImmutableDictionary()));
                Context.Stop(Self);
                break;

            default:
                Unhandled(message);
                break;
            }
        }
Пример #4
0
 public SensorPage()
 {
     InitializeComponent();
     sensorLoop = false;
     //VALIDANDO LOS SENSORES QUE APARECEN EN PANTALLA
     foreach (int id in sensor_valid)
     {
         string name = Readings.returnSensorNAME(id);
         if (name == "SPEED")
         {
             SPEED.IsVisible = true;
         }
         else if (name == "TEMPERATURE")
         {
             TEMPERATURE.IsVisible = true;
         }
         else if (name == "WEIGHT")
         {
             WEIGHT.IsVisible = true;
         }
         else if (name == "HEART")
         {
             HEART.IsVisible = true;
         }
         else if (name == "PROXIMITY")
         {
             PROXIMITY.IsVisible = true;
         }
         else if (name == "BATTERY")
         {
             BATTERY.IsVisible = true;
         }
     }
 }
Пример #5
0
        PollingLoop CreatePollingLoop()
        {
            Contract.Assert(AttachedDevice.HasValue);

            bool useMaxPollingInterval = (DeviceConstants.MaxPollingInterval == PollingInterval);
            var  request = useMaxPollingInterval ? DataRequest.Periodic : DataRequest.Frequent;

            var stream = DeviceManager.OpenDeviceStream(AttachedDevice.Value);

            var pollingLoop = new PollingLoop
                              (
                stream, request, PollingInterval,
                (timeStamp, bytes) =>
                DataSampleConverter.FromBytes
                (
                    bytes, timeStamp,
                    Use10BitVoltage,
                    useMaxPollingInterval
                ),
                EventsQueue
                              );

            pollingLoop.DataReceived += (s, args) => Readings.AddSample(args.Sample);
            pollingLoop.Disposed     += (s, args) => Stop();

            return(pollingLoop);
        }
Пример #6
0
        //[HttpPost]
        //public string AddReading(Readings model, string TankName)
        //{
        //    string command = "DECLARE @tankID int = (SELECT TOP(1) ID FROM Tank WHERE Active = 1 AND Name = '" + TankName + "')";
        //    command += ";INSERT INTO Reading (TankID, ReadTime) VALUES (@tankID, GETDATE());";
        //    command += "DECLARE @readingID int = @@IDENTITY;";
        //    foreach (Sensor s in model.sensors)
        //    {
        //        command += "INSERT INTO Sensor (SensorTypeID, ReadingValue, readingID) VALUES (";
        //        command += s.SensorTypeID.ToString() + ",";
        //        command += s.ReadingValue.ToString() + ",@readingID);";
        //    }

        //    SqlConnection conn = new SqlConnection(_static.dbconn);
        //    SqlCommand cmd = new SqlCommand(command, conn);
        //    try
        //    {
        //        conn.Open();
        //        var reader = cmd.ExecuteNonQuery();
        //    }
        //    catch (Exception ex) { return "Bad: " + ex.Message; }
        //    finally
        //    {
        //        conn.Close();
        //    }
        //    return "Good";
        //}
        public string AddReading(string json, string TankName)
        {
            string   decoded = HttpUtility.UrlDecode(json);
            Readings model   = JsonConvert.DeserializeObject <Readings>(decoded);
            string   command = "DECLARE @tankID int = (SELECT TOP(1) ID FROM Tank WHERE Active = 1 AND Name = '" + TankName + "')";

            command += ";INSERT INTO Reading (TankID, ReadTime) VALUES (@tankID, GETDATE());";
            command += "DECLARE @readingID int = @@IDENTITY;";
            foreach (Sensor s in model.sensors)
            {
                command += "INSERT INTO Sensor (SensorTypeID, ReadingValue, readingID) VALUES (";
                command += s.SensorTypeID.ToString() + ",";
                command += s.ReadingValue.ToString() + ",@readingID);";
            }

            SqlConnection conn = new SqlConnection(_static.dbconn);
            SqlCommand    cmd  = new SqlCommand(command, conn);

            try
            {
                conn.Open();
                var reader = cmd.ExecuteNonQuery();
            }
            catch (Exception ex) { return("Bad: " + ex.Message); }
            finally
            {
                conn.Close();
            }
            return("Good");
        }
Пример #7
0
        private async void UpdateSensors()
        {
            List <Readings> r;
            int             counter = 0;

            while (RestService.client != null && estado)
            {
                temperature = iluminity = humidity = uv = null;
                r           = await webService.rest.getReadingList(Readings.HUMIDITY);

                if (r != null && r.Count > 0)
                {
                    humidity = r.First();
                }

                r = await webService.rest.getReadingList(Readings.TEMPERATURE);

                if (r != null && r.Count > 0)
                {
                    temperature = r.First();
                }

                r = await webService.rest.getReadingList(Readings.ILUMINITY);

                if (r != null && r.Count > 0)
                {
                    iluminity = r.First();
                }

                r = await webService.rest.getReadingList(Readings.UV);

                if (r != null && r.Count > 0)
                {
                    uv = r.First();
                }

                if (temperature != null)
                {
                    label_Temperatura.Text = temperature.value + "  °C";
                }
                if (iluminity != null)
                {
                    label_Iluminacion.Text = iluminity.value + "  Lux";
                }
                if (humidity != null)
                {
                    label_Humedad.Text = humidity.value + "  %";
                }
                if (uv != null)
                {
                    label_Uv.Text = uv.value + "  UV";
                }

                counter++;

                Debug.WriteLine("Datos Actualizados");
                await Task.Delay(20000);
            }
        }
Пример #8
0
        private async Task ReadSensorAsync()
        {
            GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(async() =>
            {
                DateTime ReadingTime = DateTime.Now;

                //Get PhotoResistor
                byte[] readBuffer  = new byte[3]; /* Buffer to hold read data*/
                byte[] writeBuffer = new byte[3] {
                    StartByte, Channel0, 0x00
                };

                SpiADC.TransferFullDuplex(writeBuffer, readBuffer); /* Read data from the ADC                           */
                Light = convertToInt(readBuffer);                   /* Convert the returned bytes into an integer value */

                //Get Temperature
                readBuffer  = new byte[3]; /* Buffer to hold read data*/
                writeBuffer = new byte[3] {
                    StartByte, Channel1, 0x00
                };

                SpiADC.TransferFullDuplex(writeBuffer, readBuffer); /* Read data from the ADC                           */
                int adcTemp = convertToInt(readBuffer);             /* Convert the returned bytes into an integer value */
                                                                    // millivolts = value * (volts in millivolts / ADC steps)
                double millivolts = adcTemp * (3300.0 / 1024.0);
                Temperature       = (millivolts - 500) / 10.0;      //given equation from sensor documentation

                if (Temperature > AlertTemperature)
                {
                    string m       = string.Format("Temperature {0} exceeds Alert Temperature {1}", Temperature, AlertTemperature);
                    Alert alertMsg = new Alert {
                        AlertMsg = m
                    };

                    //turn on alert LED, only way to clear it is IoT Central Command)
                    ledAlertValue = GpioPinValue.High;
                    ledAlert.Write(ledAlertValue);
                    Alert = redBrush;
                }

                Reading reading = new Reading
                {
                    ReadingDateTime = ReadingTime,
                    Temperature     = Temperature,
                    Light           = Light,
                    Control         = ledControlValue == GpioPinValue.High ? true : false
                };

                //limit the amount of data we are charting
                while (Readings.Count > 60)
                {
                    Readings.RemoveAt(0);
                }

                Readings.Add(reading);
            });
        }
Пример #9
0
        public void CheckForSuddenDropOrRise(Readings reading, int patientId)
        {
            int    average = GetAverage(patientId);
            double delta   = double.Parse(reading.OxygenSaturation.ToString()) / double.Parse(average.ToString());

            if (delta > 0.90 || delta < 1.10)
            {
                Alert.SendAlert(average, delta, reading.OxygenSaturation);
            }
        }
Пример #10
0
        public string TestAddReading()
        {
            Readings r = new Readings();
            Sensor   s = new Sensor();

            s.ReadingValue = 1.0;
            s.SensorTypeID = 1;
            r.sensors      = new Sensor[] { s };
            return(JsonConvert.SerializeObject(r));
        }
Пример #11
0
        public string ActiveBranchAll(int ID)
        {
            List <Readings> output  = new List <Readings>();
            string          command = "SELECT * FROM Reading, Sensor, SensorType WHERE Reading.ID = Sensor.ReadingID AND Sensor.SensorTypeID = SensorType.ID AND Reading.TankID=" + ID.ToString();

            SqlConnection conn = new SqlConnection(_static.dbconn);
            SqlCommand    cmd  = new SqlCommand(command, conn);

            try
            {
                int           PrevReadID = 0;
                Readings      curr;
                List <Sensor> ls = new List <Sensor>();
                conn.Open();
                var reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    PrevReadID = Convert.ToInt32(reader["ReadingID"]);
                    curr       = new Readings()
                    {
                        TankID = Convert.ToInt32(reader["TankID"]),
                        time   = Convert.ToDateTime(reader["ReadTime"])
                    };
                    output.Add(curr);
                    do
                    {
                        if (Convert.ToInt32(reader["ReadingID"]) != PrevReadID)
                        {
                            PrevReadID   = Convert.ToInt32(reader["ReadingID"]);
                            curr.sensors = ls.ToArray();
                            ls           = new List <Sensor>();
                            curr         = new Readings()
                            {
                                TankID = Convert.ToInt32(reader["TankID"]),
                                time   = Convert.ToDateTime(reader["ReadTime"])
                            };
                            output.Add(curr);
                        }
                        ls.Add(new Sensor()
                        {
                            SensorTypeID = Convert.ToInt32(reader["SensorTypeID"]),
                            SensorName   = reader["Name"].ToString(),
                            ReadingValue = Convert.ToDouble(reader["readingValue"])
                        });
                    } while (reader.Read());
                    curr.sensors = ls.ToArray();
                }
            }
            catch (Exception ex) { return("Bad: " + ex.Message); }
            finally
            {
                conn.Close();
            }
            return(JsonConvert.SerializeObject(output));
        }
Пример #12
0
        public void Create(ReadingsViewModel Read)
        {
            var item = new Readings
            {
                Title   = Read.Title,
                Content = Read.Content,
            };

            db.Reads.Add(item);
            db.SaveChanges();
        }
Пример #13
0
        public Readings DiffrenceTo(Readings baseReadings)
        {
            var ret = new Readings()
                          {
                              Acc = new double[3] { this.Acc[0] - baseReadings.Acc[0], this.Acc[1] - baseReadings.Acc[1], this.Acc[2] - baseReadings.Acc[2], }, // this only makes sense if device is not rotated
                              Temp = this.Temp - baseReadings.Temp,
                              Gyro = new double[3] { this.Gyro[0] - baseReadings.Gyro[0], this.Gyro[1] - baseReadings.Gyro[1], this.Gyro[2] - baseReadings.Gyro[2], }
                          };

            return ret;
        }
Пример #14
0
        public IActionResult Post([FromBody] ReadingsViewModel model)
        {
            var defaultDate = new DateTime(0001, 01, 01, 00, 00, 00);

            try
            {
                if (ModelState.IsValid)
                {
                    if (model.Date == defaultDate)
                    {
                        model.Date = DateTime.Now.AddHours(3);
                    }

                    var newReading = new Readings()
                    {
                        // Going to be getting data ffrom database now.   values have already been caluculated.
                        //Temp1 = ConvertToFahrenheit(model.Temp1),
                        //Temp2 = ConvertToFahrenheit(model.Temp2),
                        //Temp3 = ConvertToFahrenheit(model.Temp3),
                        //Temp4 = ConvertToFahrenheit(model.Temp4),
                        //Hum1 = ConvertToHumidity(model.Hum1),
                        //Hum2 = ConvertToHumidity(model.Hum2),
                        //Hum3 = ConvertToHumidity(model.Hum3),
                        //Hum4 = ConvertToHumidity(model.Hum4)
                        Temp1 = model.Temp1,
                        Temp2 = model.Temp2,
                        Temp3 = model.Temp3,
                        Temp4 = model.Temp4,
                        Hum1  = model.Hum1,
                        Hum2  = model.Hum2,
                        Hum3  = model.Hum3,
                        Hum4  = model.Hum4,
                        Date  = model.Date
                    };
                    int x;
                    x = _repository.AddReading(newReading);  // yeah i know it's ugly.   I'll fix it next commit.

                    //if (_repository.SaveChanges() > 0)
                    if (x > 0)
                    {
                        return(Created($"/api/readings/{newReading.Id}", newReading));
                    }
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                // _logger.LogError($"Failed to save new Order {ex}");
            }
            return(BadRequest($"Failed to save new Order "));
        }
Пример #15
0
        public void ConReceived(string value)
        {
            string cadena = BTMessages.addMessage(value);
            string checksum;

            //SHA_2 sha = new SHA_2();
            for (int i = 0; i < 20; i++)
            {
                sensors[i] = 0;
            }

            if (cadena.Contains("7EAB"))
            {
                int    pos          = cadena.IndexOf("7EAB");
                int    cantSensores = 0;
                string tempCadena   = cadena.Remove(0, pos + 4);
                if (tempCadena.Length > 2)
                {
                    cantSensores = Convert.ToInt32(tempCadena.Substring(0, 2));                         // TryParse.Int32 (intentar)
                }
                if (tempCadena.Length >= 2 + 4 + 6 * cantSensores + 6 + 2)
                {
                    tempCadena = tempCadena.Remove(0, 2);             // Quitamos la longitud de la cadena
                    string datosBasicos = tempCadena.Substring(0, 4); // Leemos los datos del vehiculo (cinturon)
                    tempCadena = tempCadena.Remove(0, 4);             // Llegamos a los sensores
                    tempCadena = tempCadena.Substring(0, 6 * cantSensores + 6);

                    string datosSensores = tempCadena.Substring(0, tempCadena.Length - 6);
                    checksum = tempCadena.Substring(datosSensores.Length, 6);

                    //string hash = sha.encrypt(datosSensores).Substring(0, 6).ToUpper();
                    string hash = "16E196";
                    if (hash.Equals(checksum))
                    {
                        while (datosSensores.Length > 0)
                        {
                            int sensorID = Readings.returnSensorID(datosSensores.Substring(0, 3));
                            datosSensores = datosSensores.Remove(0, 3);
                            int primerValor = Convert.ToInt32(datosSensores.Substring(0, 2), 16); //cambiar a hexadecimal
                            datosSensores = datosSensores.Remove(0, 2);
                            int segundoValor = Convert.ToInt32(datosSensores.Substring(0, 1));
                            datosSensores     = datosSensores.Remove(0, 1);
                            sensors[sensorID] = 1.0 * primerValor + 1.0 * segundoValor / 10;
                        }
                        BTMessages.deleteMessage(pos + 4 + 2 + 4 + 6 * cantSensores + checksum.Length);
                        //BTMessages.print();
                        saveDatatoWeb(sensors);
                        Debug.WriteLine("$$$$$$$$$$$$$$$$ Datos enviados");
                    }
                }
            }
        }
Пример #16
0
        public ValuesController()
        {
            ForProjectEntities entities = new ForProjectEntities();



            foreach (AllCO2Facts f in entities.AllCO2Facts.ToList())
            {
                result_co2 = result_co2 + f.ToString();
            }

            foreach (AllHumidityFact f in entities.AllHumidityFacts.ToList())
            {
                result_humidity = result_humidity + f.ToString();
            }


            foreach (AllTemperatureFact f in entities.AllTemperatureFacts.ToList())
            {
                result_temperature = result_temperature + f.ToString();
            }



            int counter = 0;
            int x       = 0;



            var c_co2         = result_co2.Split(',');
            var c_humidty     = result_humidity.Split(',');
            var c_temperature = result_temperature.Split(',');


            for (int i = 0; i < c_co2.Length; i++)
            {
                Readings reading = new Readings();

                int.TryParse(c_co2[i], out x);
                reading.setCo2(x);

                int.TryParse(c_humidty[i], out x);
                reading.setHumidity(x);

                int.TryParse(c_temperature[i], out x);
                reading.setTemperature(x);



                readings.Add(reading);
            }
        }
Пример #17
0
        private void RecordTemperatureReading(IActorRef sensor, ITemperatureQueryReading temperatureReading)
        {
            var sensorId = ActorRefToSensorId[sensor];

            Context.Unwatch(sensor);
            ActorRefToSensorId.Remove(sensor);
            Readings.Add(sensorId, temperatureReading);
            if (ActorRefToSensorId.Count == 0)
            {
                Requester.Tell(new RespondFloorTemperatures(RequestId, Readings.ToImmutableDictionary()));
                Context.Stop(Self);
            }
        }
Пример #18
0
        /// <summary>
        /// Full start all the writings and readings from the process
        /// </summary>
        public void StartAll()
        {
            // Set all the flags
            Writings = true;
            Readings = Readings.Select(x => true).ToList();

            // Avoid start more than one process
            if (IsRunning)
                return;

            // Normal Start
            Start();
        }
Пример #19
0
        public void Accumulate(Readings toAdd)
        {
            this.Acc[0] += toAdd.Acc[0];
            this.Acc[1] += toAdd.Acc[1];
            this.Acc[2] += toAdd.Acc[2];

            //this.Temp += toAdd.Temp; //no point

            this.Temp = toAdd.Temp;

            this.Gyro[0] += toAdd.Gyro[0];
            this.Gyro[1] += toAdd.Gyro[1];
            this.Gyro[2] += toAdd.Gyro[2];
        }
Пример #20
0
        /// <summary>
        /// Stops the current process
        /// </summary>
        public void Stop()
        {   
            // Set control flag
            IsRunning = false;

            // Clear control flags
            Readings = Readings.Select(x => false).ToList();
            Writings = false;

            // Save the end time
            EndTime = DateTime.Now;

            // Fires onstop event
            OnStopRun?.Invoke(this);
        }
Пример #21
0
        /// <summary>
        /// Post one row to web server.   Will not include the date field.
        /// That means it will be inserted automaticall with a DateTimeNow
        /// </summary>
        /// <param name="tempHums"></param>
        /// <returns></returns>
        public static async Task PostOneRowToWebServer(Readings tempHums)
        {
            var json     = JsonConvert.SerializeObject(tempHums);
            var data     = new StringContent(json, Encoding.UTF8, "application/json");
            var client   = new HttpClient();
            var response = await client.PostAsync(apiPostUrl, data);

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("The readings were accepted by the server");
            }
            else
            {
                Console.WriteLine($"Was not able to post the reading at: {DateTime.Now}");
            }
        }
Пример #22
0
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                //creating a new object og readings
                Readings reads = new Readings()
                {
                    //Reading from WebServer
                    Date     = DateTime.Now,
                    Degrees  = Convert.ToDouble(WebCon.Read("T")) * 0.01,
                    Humidity = Convert.ToDouble(WebCon.Read("H")) * 0.01,
                    RID      = WebCon.Read("R")
                };
                //Printing our the new reading to our logfile
                WriteToFile($"made new reading\nDate : {reads.Date}\nDegrees : {reads.Degrees}\nHumidity : {reads.Humidity}\nRID : {reads.RID}");
                //add the current reading to a list
                readings.Add(reads);
            }
            catch (Exception ex)
            {
                //catch error
                WriteToFile($"Error connecting to sql Server\n\n{ex.Message}");
            }



            try
            {
                //WriteToFile(data.Connect());
                //Write to log, using Data.insert(our list of readings) returning if it failed or success
                WriteToFile(data.Insert(readings));
                //WriteToFile(data.Close());
            }
            catch (Exception ex)
            {
                //if it failed  write to file that  failed
                WriteToFile($"Error connecting to sql Server\n\n{ex.Message}");
            }
            finally
            {
                //Clearing list for a new reading
                readings.Clear();
            }

            //Making some space in log, to make it more readable
            WriteToFile("\n\n\n\n\n");
        }
        public override Task <Readings> GetWeatherReadings(WeatherRequest request, ServerCallContext context)
        {
            var readings = new WeatherResponse[]
            {
                GetWeatherData(),
                GetWeatherData(),
                GetWeatherData(),
                GetWeatherData(),
                GetWeatherData(),
            };

            var returnValue = new Readings();

            returnValue.TheReadings.Add(readings);

            return(Task.FromResult(returnValue));
        }
Пример #24
0
        public void ReturnViewForChart()
        {
            var reading = new Readings()
            {
                Id    = 3,
                Temp1 = 85.5M,
                Temp2 = 85.4M,
                Temp3 = 85.3M,
                Temp4 = 85.5M,
                Hum1  = 45.5M,
                Hum2  = 45.6M,
                Hum3  = 45.3M,
                Hum4  = 45.3M,
                Date  = new DateTime(2020, 01, 12)
            };

            var result = _sut.Chart();
        }
        private async Task RefreshDevices()
        {
            IsLoading = true;

            var registeredDevices = (await metersDatabase.GetMetersAsync()).ToList();

            var results = registeredDevices.Select(d => DownloadDeviceDataAsync(d)).ToArray();
            await Task.WhenAll(results);

            Readings.Clear();

            results
            .SelectMany(p => p.Result)
            .ToList()
            .ForEach(i => Readings.Add(i));

            IsLoading = false;
        }
Пример #26
0
 public ActionResult Index(int?ID)
 {
     ViewBag.ID            = ID ?? 0;
     ViewBag.RecentReading = null;
     if (ID != null)
     {
         //dear employers, this does not accurately represent my abilities
         //Dear God, I'm sorry.
         string   x             = new TankController().GetLastReading(ID ?? 0);
         Readings j             = JsonConvert.DeserializeObject <Readings>(x);
         double[] RecentReading = new double[5];
         foreach (Sensor s in j.sensors)
         {
             RecentReading[s.SensorTypeID - 1] = s.ReadingValue;
         }
         ViewBag.RecentReading = RecentReading;
     }
     return(View());
 }
Пример #27
0
        public static void Get_Current_Month(ReadingCell.ReadingUnitType unit)
        {
            Temperature_Readings = new List <DataPoint>();
            Humidity_Readings    = new List <DataPoint>();
            SetPoint_Readings    = new List <DataPoint>();

            int index = Current_Month;

            if (Current_Month == Total_Months)
            {
                index--;
            }

            DateTime start = Month_Start_Days[index];
            DateTime end   = start.AddMonths(1);

            foreach (ReadingCell cell in Readings.Where(x => x.Occurence >= start && x.Occurence <= end))
            {
                Temperature_Readings.Add(new DataPoint
                                         (

                                             DateTimeAxis.ToDouble(cell.Occurence),
                                             cell.Get_Temperature(unit)

                                         ));

                Humidity_Readings.Add(new DataPoint
                                      (

                                          DateTimeAxis.ToDouble(cell.Occurence),
                                          cell.Humidity

                                      ));

                SetPoint_Readings.Add(new DataPoint
                                      (

                                          DateTimeAxis.ToDouble(cell.Occurence),
                                          cell.Set_Point

                                      ));
            }
        }
Пример #28
0
        public PagedResult <KeyValuePair <DateTime, IList <ReadingViewModel> > > GetReadingsPaged(ReadingsQuery query)
        {
            var datesPaged = Readings.Where(r => r.Measurement.Id == query.MeasurementId &&
                                            (query.FromTime == null || r.ReadingTime >= query.FromTime) &&
                                            (query.ToTime == null || r.ReadingTime <= query.ToTime) &&
                                            (query.NewerThan == null || r.ReadingTime > query.NewerThan))
                             .OrderByIf(r => r.ReadingTime, () => query.Ascending)
                             .Select(r => r.ReadingTime)
                             .Distinct()
                             .GetPaged(query.Page, query.PageSize);
            var dates = datesPaged.Results;

            // Make sure readings get SensorRole and Calculator loaded automatically
            // It's practically caching them for grouping query
            var measurement = Measurements.Include(m => m.SensorRoles)
                              .Include(m => m.Calculators)
                              .FirstOrDefault(m => m.Id == query.MeasurementId);

            var grouped = Readings.Where(r =>
                                         (r.Measurement.Id == query.MeasurementId) &&
                                         (dates == null || dates.Contains(r.ReadingTime))
                                         )
                          .OrderByIf(r => r.ReadingTime, () => query.Ascending)
                          .ToList()
                          .AsQueryable()
                          .ProjectTo <ReadingViewModel>()
                          .GroupBy(r => r.ReadingTime)
                          .Select(g => new KeyValuePair <DateTime, IList <ReadingViewModel> > (
                                      g.Key,
                                      g.OrderBy(r => r.Name).ToList()
                                      ))
                          .ToList();

            var result = new PagedResult <KeyValuePair <DateTime, IList <ReadingViewModel> > >();

            result.CurrentPage = datesPaged.CurrentPage;
            result.PageCount   = datesPaged.PageCount;
            result.PageSize    = datesPaged.PageSize;
            result.RowCount    = datesPaged.RowCount;
            result.Results     = grouped;

            return(result);
        }
Пример #29
0
        public ActionResult AddReadings(int OxygenSaturation_input, int Pulse_input, int PatientID)
        {
            int        userid = int.Parse(Session["ID"].ToString());
            Device     d      = DB.Device.FirstOrDefault(p => p.PatientID == userid);
            DeviceLine dl     = new DeviceLine()
            {
                PatientID = userid, DeviceID = d.ID
            };
            Readings r = new Readings()
            {
                Pulse = Pulse_input, OxygenSaturation = OxygenSaturation_input, Date = DateTime.Now
            };

            r.DeviceLine.Add(dl);
            DB.Readings.Add(r);
            DB.SaveChanges();
            Helpers.AdvProg adv = new Helpers.AdvProg();
            adv.CheckForSuddenDropOrRise(r, userid);
            return(View());
        }
Пример #30
0
        public string GetLastReading(int ID)
        {
            Readings      output   = new Readings();
            string        command  = "SELECT TOP(1) * FROM Reading WHERE tankID = " + ID.ToString() + " ORDER BY ReadTime DESC";
            string        command2 = "SELECT * FROM Sensor, SensorType WHERE Sensor.SensorTypeID = SensorType.ID AND ReadingID=";
            SqlConnection conn     = new SqlConnection(_static.dbconn);
            SqlCommand    cmd      = new SqlCommand(command, conn);

            try
            {
                conn.Open();
                var reader = cmd.ExecuteReader();
                reader.Read();
                output.ID     = Convert.ToInt32(reader["ID"]);
                output.TankID = Convert.ToInt32(reader["TankID"]);
                output.time   = Convert.ToDateTime(reader["ReadTime"]);
                reader.Close();
                command2 += output.ID.ToString();
                SqlCommand cmd2 = new SqlCommand(command2, conn);
                reader = cmd2.ExecuteReader();
                reader.Read();
                List <Sensor> sensor = new List <Sensor>();
                do
                {
                    sensor.Add(new Sensor()
                    {
                        SensorName   = reader["Name"].ToString(),
                        SensorTypeID = Convert.ToInt32(reader["SensorTypeID"]),
                        ReadingValue = Convert.ToDouble(reader["ReadingValue"])
                    });
                } while (reader.Read());
                output.sensors = sensor.ToArray();
            }
            catch { }
            finally
            {
                conn.Close();
            }
            return(JsonConvert.SerializeObject(output));
        }
Пример #31
0
        public string AddReadings(int OxygenSaturation, int pulse, int cpr)
        {
            Patient    patient = DB.Patient.FirstOrDefault(p => p.CPRno == cpr);
            Device     d       = DB.Device.FirstOrDefault(p => p.PatientID == patient.ID);
            DeviceLine dl      = new DeviceLine()
            {
                PatientID = patient.ID, DeviceID = d.ID
            };
            Readings r = new Readings()
            {
                Pulse = pulse, OxygenSaturation = OxygenSaturation, Date = DateTime.Now
            };

            r.DeviceLine.Add(dl);
            DB.Readings.Add(r);
            DB.SaveChanges();

            //tjek om måling er megetafvigende:
            Helpers.AdvProg adv = new Helpers.AdvProg();
            adv.CheckForSuddenDropOrRise(r, cpr);

            return("ok");
        }
Пример #32
0
        public override Evaluation GetEvaluation(double correctValue)
        {
            var meanValue   = Readings.Average(x => x.Value);
            var meanMistake = Math.Abs(meanValue - correctValue);

            var    standardDeviation = Math.Sqrt(Readings.Sum(x => Math.Pow(meanValue - x.Value, 2)) / (Readings.Count - 1));
            string result;

            if (meanMistake > 0.5)
            {
                result = "precise";
            }
            else if (standardDeviation > 3)
            {
                result = "very precise";
            }
            else
            {
                result = "ultra precise";
            }

            return(new Evaluation(Name, result));
        }