Exemplo n.º 1
0
        public async Task <bool> PutAsync(int id, SensorDataModel value)
        {
            using (HttpClient client = new HttpClient())
            {
                SensorDataModel fan = await GetDataById(id);

                if (fan != null)
                {
                    fan.CO2         = value.CO2;
                    fan.Humidity    = value.Humidity;
                    fan.RoomID      = value.RoomID;
                    fan.SensorID    = value.SensorID;
                    fan.Temperature = value.Temperature;
                    fan.Pressure    = value.Pressure;
                }

                string        postBody      = JsonConvert.SerializeObject(value);
                StringContent stringContent = new StringContent(postBody, Encoding.UTF8, "application/json");
                await client.PutAsync($"{URI}/{id}", stringContent);

                return(true);
            }

            return(false);
        }
Exemplo n.º 2
0
 public Sensor ToSensorDomainModel(SensorDataModel sensorDataModel)
 {
     return(new Sensor(sensorDataModel.Id, new SensorValue(sensorDataModel.Position, sensorDataModel.Type))
     {
         Readings = sensorDataModel.Readings?.Select(ToReadingDomainModel).ToList()
     });
 }
Exemplo n.º 3
0
        public void ReturnEditSensorView_WhenSensorByIdIsValid()
        {
            // Arrange
            var sensorServiceMock = new Mock <ISensorService>();
            var httpClientMock    = new Mock <HttpClientProvider>();

            var controller = new SensorController(sensorServiceMock.Object,
                                                  httpClientMock.Object);

            controller.UserMocking("test");

            var sensor = new SensorDataModel()
            {
                OwnerId = It.IsAny <string>()
            };

            sensorServiceMock.Setup(s => s.GetUserSensorById(It.IsAny <int>()))
            .Returns(sensor);

            // Act
            controller.EditSensor(It.IsAny <int>());

            // Assert
            controller.WithCallTo(c => c.EditSensor(It.IsAny <int>()))
            .ShouldRenderView("EditSensor");
        }
Exemplo n.º 4
0
        public SensorChartViewModel GetChart(SensorDataModel sensorData)
        {
            var xAxis = new DateTimeAxis
            {
                Title        = "Time",
                Position     = AxisPosition.Bottom,
                StringFormat = "yyyy-MM-dd"
            };

            var yAxis = new LinearAxis
            {
                Title              = string.Format("{0}/{1}", sensorData.SensorName, sensorData.Unit),
                Position           = AxisPosition.Left,
                MajorGridlineStyle = LineStyle.Solid,
                MinorGridlineStyle = LineStyle.Dot
            };

            var sensorSeries = new LineSeries
            {
                Title               = sensorData.SensorName,
                StrokeThickness     = 2,
                LineStyle           = LineStyle.Solid,
                MarkerType          = MarkerType.Circle,
                MarkerFill          = OxyColors.DarkRed,
                MarkerSize          = 3,
                Color               = OxyColors.Green,
                TrackerFormatString = "{0}\n{1}: {2:F}\n{3}: {4:0.####}"
            };

            return(new SensorChartViewModel(xAxis, yAxis, sensorSeries));
        }
Exemplo n.º 5
0
        public SensorDataModel GetAdminSensorById(int Id)
        {
            Sensor          sensorModel = this.context.Sensors.First(s => s.Id == Id);
            SensorDataModel sensor      = SensorDataModel.Convert(sensorModel);

            return(sensor);
        }
        public SensorDataModel GetSensorData()
        {
            port.WriteLine(GETDATA);
            string s = port.ReadLine();

            Console.WriteLine(s);

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

            double humidity, moisture, temperature;

            double.TryParse(data[0], out humidity);
            double.TryParse(data[1], out moisture);
            double.TryParse(data[2], out temperature);

            DateTime        timeNow     = DateTime.UtcNow;
            SensorDataModel _sensorData = new SensorDataModel
            {
                TimeStamp   = timeNow,
                Humidity    = humidity,
                Moisture    = moisture,
                Temperature = temperature
            };

            return(_sensorData);
        }
        public async Task <ActionResult <SensorDataModel> > PostSensorDataModel(SensorDataModel sensorDataModel)
        {
            _context.Fans.Add(sensorDataModel);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("Get", new { id = sensorDataModel.SensorID }, sensorDataModel));
        }
        public async Task <IActionResult> PutSensorDataModel(int id, SensorDataModel sensorDataModel)
        {
            if (id != sensorDataModel.SensorID)
            {
                return(BadRequest());
            }

            _context.Entry(sensorDataModel).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SensorDataModelExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Add([FromBody] SensorDataModel model)
        {
            List <Wifi> wifis = new List <Wifi>();

            foreach (var item in model.s.wifi)
            {
                wifis.Add(new Wifi {
                    MacAddress = item.Key, RSSI = item.Value
                });
            }

            var sensorData = new SensorData()
            {
                Device = model.d,
                Family = model.f,
                GPS    = new Gps()
                {
                    Altitude  = model.gps["alt"],
                    Latitude  = model.gps["lat"],
                    Longitude = model.gps["lon"]
                },
                Wifis = wifis,
                Date  = UnixTimeStampToDateTime(model.t)
            };

            _repository.Add(sensorData);

            await _repository.UnitOfWork.SaveChangesAsync();

            return(CreatedAtAction(nameof(Get), new { id = sensorData.Id }, null));
        }
Exemplo n.º 10
0
        public static AdminSensorViewModel Convert(SensorDataModel sensor)
        {
            AdminSensorViewModel sensorViewModel = new AdminSensorViewModel()
            {
                Id              = sensor.Id,
                Name            = sensor.Name,
                MeasurementType = sensor.MeasurementType,
                Description     = sensor.Description,
                URL             = sensor.URL,
                PollingInterval = sensor.PollingInterval,
                CurrentValue    = sensor.CurrentValue,
                MinValue        = sensor.MinValue,
                MaxValue        = sensor.MaxValue,
                IsBoolType      = sensor.IsBoolType,
                IsPublic        = sensor.IsPublic,
                IsShared        = sensor.IsShared,
                OwnerId         = sensor.OwnerId,
                Owner           = sensor.Owner,
                SharedWithUsers = sensor.SharedWithUsers,
                LastUpdate      = sensor.LastUpdate,
                IsDeleted       = sensor.IsDeleted
            };

            return(sensorViewModel);
        }
Exemplo n.º 11
0
        public static async Task MQTTLinkResult()
        {
            var factory     = new MqttFactory();
            var mqttClient2 = factory.CreateMqttClient();
            var options     = new MqttClientOptionsBuilder()
                              .WithTcpServer("iot.cht.com.tw", 1883).WithCredentials("PKXRT95R2GFC4BKW4P", "PKXRT95R2GFC4BKW4P")
                              .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311).Build();
            UnicodeEncoding uniEncoding = new UnicodeEncoding();

            byte[] firstString = uniEncoding.GetBytes("");
            await mqttClient2.ConnectAsync(options, CancellationToken.None);

            await mqttClient2.SubscribeAsync("/v1/device/24986291524/sensor/ZAWARUDO/rawdata", MqttQualityOfServiceLevel.AtLeastOnce);

            bool firstFlag = false;

            mqttClient2.UseApplicationMessageReceivedHandler(e =>//收到訊息時
            {
                if (firstFlag)
                {
                    Console.WriteLine("收到訊息:");
                    Console.WriteLine($"主題 : {e.ApplicationMessage.Topic}");
                    Console.WriteLine($"Response : {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");//response的value
                    var ss = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                    SensorDataModel model = JsonSerializer.Deserialize <SensorDataModel>(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                    Console.WriteLine($"QoS模式 : {e.ApplicationMessage.QualityOfServiceLevel}");
                    Console.WriteLine($"Retain = {e.ApplicationMessage.Retain}");
                    InsertDriveResult(model.value);
                }
                else
                {
                    firstFlag = true;
                }
            });
        }
Exemplo n.º 12
0
 public async void PostAsync(SensorDataModel value)
 {
     using (HttpClient client = new HttpClient())
     {
         string        postBody      = JsonConvert.SerializeObject(value);
         StringContent stringContent = new StringContent(postBody, Encoding.UTF8, "application/json");
         await client.PostAsync(URI, stringContent);
     }
 }
Exemplo n.º 13
0
        public async Task <SensorDataModel> GetDataById(int id)
        {
            using (HttpClient client = new HttpClient())
            {
                string content = await client.GetStringAsync($"{URI}/{id}");

                SensorDataModel data = JsonConvert.DeserializeObject <SensorDataModel>(content);
                return(data);
            }
        }
Exemplo n.º 14
0
        public IActionResult GetSensorData(string id)
        {
            var data = new SensorDataModel
            {
                SensorId    = id,
                LastUpdated = DateTime.UtcNow
            }.AsResource();

            return(Ok(data));
        }
 public void PostSensorData(SensorDataModel sensorData)
 {
     db.SensorData.Add(new SqlSensorData
     {
         DeviceId  = sensorData.DeviceId,
         TimeStamp = DateTime.Now,
         Payload   = sensorData.Payload.ToString()
     });
     db.SaveChanges();
 }
Exemplo n.º 16
0
        public async Task <IActionResult> ModifySensorData([Required, FromBody] SensorDataModel sdm)
        {
            if (sdm == null)
            {
                return(BadRequest());
            }
            await _repository.ModifySensorDataAsync(sdm);

            return(Ok());
        }
Exemplo n.º 17
0
        public async Task <IActionResult> AddSensorData([FromBody, Required] SensorDataModel sensorDataModel)
        {
            if (sensorDataModel == null)
            {
                return(BadRequest());
            }
            await _repository.AddSensorDataAsync(sensorDataModel);

            _mqtt.Publish(new Data(double.Parse(sensorDataModel.Value), sensorDataModel.Type), "sensor/data");
            return(Ok());
        }
Exemplo n.º 18
0
        public SensorDataModel UpdateSensor(SensorDataModel sensorData)
        {
            using (var writeApi = _infux.GetWriteApi())
            {
                var point = PointData.Measurement("moisture")
                            .Tag("device", sensorData.Device)
                            .Field("value", sensorData.Reading)
                            .Timestamp(DateTime.UtcNow, WritePrecision.Ns);

                writeApi.WritePoint("Sensors", "Droppy", point);
            }

            return(sensorData);
        }
        public void Put(int id, [FromBody] SensorDataModel value)
        {
            SensorDataModel item = Get(id);

            if (item != null)
            {
                item.SensorID    = value.SensorID;
                item.RoomID      = value.RoomID;
                item.Temperature = value.Temperature;
                item.Humidity    = value.Humidity;
                item.CO2         = value.CO2;
                item.Pressure    = value.Pressure;
            }
        }
        public async Task <bool> Put(int id, [FromBody] float value)
        {
            bool isTempTrue = false;

            List <SensorDataModel> mockList = new List <SensorDataModel>()
            {
                new SensorDataModel(1, "Stue", 25.12f, 30, 12, 1200),
                new SensorDataModel(2, "Stue", 25.12f, 30, 12, 1200),
                new SensorDataModel(3, "Stue", 25.12f, 30, 12, 1200)
            };

            SensorDataModel model = mockList.Find(m => m.SensorID == id);

            while (!isTempTrue)
            {
                try
                {
                    if (model.Temperature > value + 2)
                    {
                        throw new Exception("More than two degrees");
                    }
                    if (model.Temperature < value - 2)
                    {
                        throw new Exception("Less than two degrees");
                    }

                    isTempTrue = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    if (e.Message == "More than two degrees")
                    {
                        model.Temperature -= 0.1f;
                    }

                    if (e.Message == "Less thant two degrees")
                    {
                        model.Temperature += 0.1f;
                    }
                }
            }



            return(isTempTrue);
        }
Exemplo n.º 21
0
        public SensorDataModel GetUsersSharedSensor(int id)
        {
            var sharedSensor = this.context.Sensors.Single(s => s.Id == id && s.IsDeleted == false).SharedWithUsers.ToList();

            var sensorDModel = new SensorDataModel()
            {
                Id = id,
            };

            for (int i = 0; i < sharedSensor.Count; i++)
            {
                sensorDModel.SharedWithUsers.Add(sharedSensor[i].UserName);
                sensorDModel.Owner = sharedSensor[i].UserName;
            }

            return(sensorDModel);
        }
        // POST api/sensors
        public string Post([FromBody] SensorDataModel sensorDataModel)
        {
            try {
                var unitService               = new UnitService();
                var soilReadingService        = new SoilReadingService();
                var temperatureReadingService = new TemperatureReadingService();
                var rainEventService          = new RainEventService();
                var cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
                var now     = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cstZone);

                var unitId = unitService.ValidateProductKey(sensorDataModel.ProductKey);
                if (unitId == -1)
                {
                    return("Invalid product key.");
                }
                var unitSettings = unitService.GetUnitById(unitId).Settings;
                var rainFlag     = (unitSettings != null && unitSettings.RainLimit < sensorDataModel.Rain);
                //if (unitSettings != null && unitSettings.RainLimit < sensorDataModel.Rain) {
                var rainEvent = new RainEvent {
                    DateTime   = now,
                    UnitId     = unitId,
                    RainAmount = sensorDataModel.Rain
                };
                rainEventService.Insert(rainEvent);

                //rainFlag = true;
                //}
                var soilLimitsDict = sensorDataModel.SoilReadings.ToDictionary(x => (int.Parse(x.SensorNumber) - 1), x => (unitSettings != null && x.SoilMoisture > unitSettings.SoilMoistureLimit));
                var tempFlag       = unitSettings != null && unitSettings.StopOnFreeze && sensorDataModel.Temperature < 34.0;
                var commandDict    = unitService.GetValveCommands(unitId, soilLimitsDict, tempFlag, rainFlag);

                soilReadingService.Insert(sensorDataModel.SoilReadings, unitId);
                var tempReading = new TemperatureReading {
                    UnitId      = unitId,
                    DateTime    = now,
                    Temperature = sensorDataModel.Temperature
                };
                temperatureReadingService.Insert(tempReading);

                var serializer = new JavaScriptSerializer();
                var jsonString = serializer.Serialize(commandDict);
                return(jsonString);
            } catch (Exception ex) {
                return(ex.Message);
            }
        }
        public IHttpActionResult SaveSensorData(SensorDataModel sensorDataModel)
        {
            MySqlConnection connection = new MySqlConnection(ConnectionString);
            int             sensorRows = 0;

            try
            {
                connection.Open();
                if (sensorDataModel != null)
                {
                    string query = "INSERT INTO sensordata(Acceleration, Frequency, Gyroscope, Light, Location, Noise, Proximity, Question, QuestionId, Id, AssignmentId,TimeAtSensoring) VALUES ('" +
                                   sensorDataModel.Acceleration + "','" +
                                   sensorDataModel.Frequency + "','" +
                                   sensorDataModel.Gyroscope + "','" +
                                   sensorDataModel.Light + "','" +
                                   sensorDataModel.Location + "','" +
                                   sensorDataModel.Noise + "','" +
                                   sensorDataModel.Proximity + "','" +
                                   sensorDataModel.Question + "','" +
                                   sensorDataModel.QuestionId + "','" +
                                   sensorDataModel.Id + "','" +
                                   sensorDataModel.AssignmentId + "','" +
                                   sensorDataModel.TimeAtSensoring + "')";

                    MySqlCommand sqlCommand = new MySqlCommand(query, connection);
                    sensorRows = sqlCommand.ExecuteNonQuery();
                }

                if (sensorRows > 0)
                {
                    return(Ok());
                }
                return(BadRequest());
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.InnerException == null ? ex.Message + " - " + ex.StackTrace : ex.Message + " - " + ex.InnerException.Message);
                throw ex;
            }
        }
        public void ReturnSensorDataModelWithSharedUsersName()
        {
            //Arrange
            var dbContextMock       = new Mock <ApplicationDbContext>();
            var httpClientMock      = new Mock <IHttpClientProvider>();
            var emailServiceMock    = new Mock <IEmailService>();
            var ownerMock           = new Mock <ApplicationUser>();
            var userToShareWithMock = new Mock <ApplicationUser>();
            int Id = 4;

            var sensorServices = new Dataflow.DataServices.SensorService(dbContextMock.Object, httpClientMock.Object, emailServiceMock.Object);

            List <ApplicationUser> users = new List <ApplicationUser>
            {
                new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                },
                new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                },
                new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                }
            };

            List <string> usernames = new List <string>
            {
                "Ivan",
                "Mariq",
                "Prolet"
            };

            List <Sensor> sensors = new List <Sensor>()
            {
                new Sensor()
                {
                    Id              = Id,
                    Name            = "termometur",
                    IsBoolType      = false,
                    URL             = "theGreatUrl",
                    PollingInterval = 20,
                    IsPublic        = true,
                    IsShared        = true,
                    OwnerId         = "stringId",
                    Owner           = ownerMock.Object,
                    IsDeleted       = false,
                    SharedWithUsers = users
                },

                new Sensor()
                {
                    Id              = 7,
                    Name            = "Door",
                    IsBoolType      = true,
                    URL             = "theGreatUrlPart2",
                    PollingInterval = 25,
                    IsPublic        = false,
                    IsShared        = false,
                    OwnerId         = "stringId",
                    Owner           = ownerMock.Object,
                    IsDeleted       = false
                },
            };

            var sensorsSetMock = new Mock <DbSet <Sensor> >().SetupData(sensors);

            dbContextMock.SetupGet(m => m.Sensors).Returns(sensorsSetMock.Object);

            //Act
            SensorDataModel result = sensorServices.GetUsersSharedSensor(Id);

            //Assert
            Assert.AreEqual(usernames.Count, result.SharedWithUsers.Count);
            Assert.AreEqual(usernames.First(), result.SharedWithUsers.First());
            dbContextMock.Verify(d => d.Sensors, Times.Once);
        }
Exemplo n.º 25
0
 public SensorChartViewModel GetChartViewModel(SensorDataModel sensorDataModel)
 {
     return(_sensorChartViewModelSet.FirstOrDefault(x => x.IsMatchedWithSensorDataModel(sensorDataModel)));
 }
Exemplo n.º 26
0
 public OneWindowModel()
 {
     isOpen     = false;
     SensorData = new SensorDataModel();
 }
Exemplo n.º 27
0
 public async Task AddSensorDataAsync(SensorDataModel sdm)
 {
     var coll = _dbContext.GetCollection <SensorDataModel>("SENSORS");
     await coll.InsertOneAsync(sdm);
 }
Exemplo n.º 28
0
 public async Task ModifySensorDataAsync(SensorDataModel sdm)
 {
     var coll = _dbContext.GetCollection <SensorDataModel>("SENSORS");
     await coll.ReplaceOneAsync(x => x.ID == sdm.ID, sdm);
 }
 public void Post([FromBody] SensorDataModel value)
 {
     data.Add(value);
 }
Exemplo n.º 30
0
 public bool IsMatchedWithSensorDataModel(SensorDataModel sensorDataModel)
 {
     return(SensorDataModel.OrchardId == sensorDataModel.OrchardId &&
            SensorDataModel.CollectorId == sensorDataModel.CollectorId &&
            SensorDataModel.SensorId == sensorDataModel.SensorId);
 }