public async Task <string> SendListToIotHubAsync() { List <GeoLocation> session = new List <GeoLocation>(await App.Database.GetGeoLocationItemsAsync()); var telemetrysToSend = new List <TelemetryDataPoint>(); // Enumerable.Empty<object>().Select(o => definition).ToList() for (int i = 0; i < session.Count; i++) { TelemetryDataPoint tmdp = new TelemetryDataPoint(); tmdp.latitude = session[i].Latitude; tmdp.longitude = session[i].Longitude; tmdp.date_time = session[i].TimeDate; tmdp.sessionId = session[i].SessionId; tmdp.deviceId = session[i].DeviceId; tmdp.inactivityDetected = session[i].InactivityDetected; // tmdp.alarmed = session[i].Alarmed; telemetrysToSend.Add(tmdp); } var messageString = JsonConvert.SerializeObject(telemetrysToSend); var message = new Message(System.Text.Encoding.ASCII.GetBytes(messageString)); Log.Verbose(TAG, "\nSENDING MESSAGE TO IOT-HUB"); Log.Verbose(TAG, "Message: " + message.ContentType + "\nMessageString: " + messageString); await deviceClient.SendEventAsync(message); session.Clear(); telemetrysToSend.Clear(); return(messageString); }
public static async Task <string> GetWeather() { string url = "http://api.openweathermap.org/data/2.5/weather?id=2158177&appid=df39100f7fe7b297c789818c5f2bb1bd"; string weatherjson = await GetAsync(url); var obj = Windows.Data.Json.JsonObject.Parse(weatherjson); var otemperature = ((int)obj["main"].GetObject()["temp"].GetNumber()) - 273; var opressure = (int)obj["main"].GetObject()["pressure"].GetNumber(); var ohumidity = (int)obj["main"].GetObject()["humidity"].GetNumber(); var telemetryDataPoint = new TelemetryDataPoint() { temperature = otemperature, pressure = opressure, humidity = ohumidity }; var stream1 = new MemoryStream(); var ser = new DataContractJsonSerializer(typeof(TelemetryDataPoint)); ser.WriteObject(stream1, telemetryDataPoint); stream1.Position = 0; var sr = new StreamReader(stream1); string MessageString = sr.ReadToEnd(); ; return(MessageString); }
public async Task MoveSim(SimObject simObject) { GridBlock gridBlock; try { //Gets a random direction and attempts to move the sim gridBlock = await _gridManager.MoveInDirection(simObject, await GetRandomDirection().ConfigureAwait(false)).ConfigureAwait(false); if (gridBlock != null) { var telemetryDataPoint = new TelemetryDataPoint { DeviceId = simObject.IoTDeviceInfo.DeviceId, Name = simObject.Name, Type = simObject.Type, Grid_x = gridBlock.Location.Rowx, Grid_y = gridBlock.Location.Columny, InZone = gridBlock.IsZone, Operation = "move_completed" }; await SendIoTHubMessage(simObject, telemetryDataPoint).ConfigureAwait(false); } } catch (LocationOccupiedException lex) { _logger.LogError(lex.Message); } catch (OffTheGridException oex) { _logger.LogError(oex.Message); } }
private void SensorValueupload(object state) { try { // Air sensor readings double temperatureCelsius = bme280Sensor.Temperature.DegreesCelsius; double temperatureFahrenheit = bme280Sensor.Temperature.DegreesFahrenheit; double humidity = bme280Sensor.Humidity; double pressure = bme280Sensor.Pressure.Kilopascals; double lightLevel = GroveBaseHatAnalogPorts.Read(AnalogPorts.AnalogPort.A0); double soilMoisture1 = GroveBaseHatAnalogPorts.Read(AnalogPorts.AnalogPort.A2); double soilMoisture2 = GroveBaseHatAnalogPorts.Read(AnalogPorts.AnalogPort.A4); LoggingService.Log(string.Format("C {0:0.0}° F {1:0.0}° H {2:0}% P {3:0.000}kPa L {4:0}% Soil1 {5:0}% Soil2 {6:0}% ", temperatureCelsius, temperatureFahrenheit, humidity, pressure, lightLevel, soilMoisture1, soilMoisture2)); // Setup for the the logging of sensor values var loggingData = new LoggingFields(); // Construct Azure IoT Central friendly payload var telemetryDataPoint = new TelemetryDataPoint(); telemetryDataPoint.Celsius = temperatureCelsius; loggingData.AddDouble(nameof(telemetryDataPoint.Celsius), temperatureCelsius); telemetryDataPoint.Fahrenheit = temperatureFahrenheit; loggingData.AddDouble(nameof(telemetryDataPoint.Fahrenheit), temperatureFahrenheit); telemetryDataPoint.Humidity = humidity; loggingData.AddDouble(nameof(telemetryDataPoint.Humidity), humidity); telemetryDataPoint.Pressure = pressure; loggingData.AddDouble(nameof(telemetryDataPoint.Pressure), pressure); telemetryDataPoint.Light = lightLevel; loggingData.AddDouble(nameof(telemetryDataPoint.Light), lightLevel); telemetryDataPoint.SoilMoisture1 = soilMoisture1; loggingData.AddDouble(nameof(telemetryDataPoint.SoilMoisture1), soilMoisture1); telemetryDataPoint.SoilMoisture2 = soilMoisture2; loggingData.AddDouble(nameof(telemetryDataPoint.SoilMoisture2), soilMoisture2); // Log the sensor values to ETW logging LoggingService.LogEvent("Sensor readings", loggingData, LoggingLevel.Verbose); using (var message = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(telemetryDataPoint)))) { LoggingService.Log("AzureIoTHubClient SendEventAsync starting"); azureIoTHubClient.SendEventAsync(message).Wait(); LoggingService.Log("AzureIoTHubClient SendEventAsync finished"); } } catch (Exception ex) { LoggingService.Error("Failed to send telemetry", ex); } }
public static async Task <TelemetryDataPoint> GetWeatherObj() { string url = "http://api.openweathermap.org/data/2.5/weather?id=2158177&appid=df39100f7fe7b297c789818c5f2bb1bd"; string weatherjson = await GetAsync(url); var obj = Windows.Data.Json.JsonObject.Parse(weatherjson); var otemperature = ((int)obj["main"].GetObject()["temp"].GetNumber()) - 273; var opressure = (int)obj["main"].GetObject()["pressure"].GetNumber(); var ohumidity = (int)obj["main"].GetObject()["humidity"].GetNumber(); var telemetryDataPoint = new TelemetryDataPoint() { temperature = otemperature, pressure = opressure, humidity = ohumidity }; return(telemetryDataPoint); }
public static async Task <TelemetryDataPoint> GetWeatherObj() { string url = string.Format("http://api.openweathermap.org/data/2.5/weather?id={0}&appid={1}", Cities[CurrentCityIndex].id, AzureConnections.MyConnections.OpenWeatherAppKey); string weatherjson = await GetAsync(url); dynamic obj = JsonConvert.DeserializeObject(weatherjson); dynamic fgh = obj.main; dynamic temp = obj.main.temp; dynamic press = obj.main.pressure; dynamic humid = obj.main.humidity; var otemperature = (int)(float.Parse(temp.ToString())); var opressure = (int)(int.Parse(press.ToString())); var ohumidity = (int)(int.Parse(humid.ToString())); var telemetryDataPoint = new TelemetryDataPoint() { city = Weather.Cities[Weather.CurrentCityIndex].name, temperature = otemperature - 273, pressure = opressure, humidity = ohumidity }; return(telemetryDataPoint); }
protected void Page_Load(object sender, EventArgs e) { string message = "{\"SensorNodeId\":12346,\"Temperature\":23.51,\"Humidity\":38.81,\"Acceleration\":{\"X\":-1,\"Y\":0,\"Z\":1},\"Ambient_light\":5563,\"Pressure\":900,\"Switch\":{\"User1\":\"NodeP\",\"Hall\":1},\"Vibration\":{\"Frequency\":228,\"Power\":122},\"Node_status\":{\"Battery_level\":72}}"; TelemetryDataPoint messageDataPoint = Newtonsoft.Json.JsonConvert.DeserializeObject <TelemetryDataPoint>(message); TelemetryDataPoint newPoint = new TelemetryDataPoint() { SensorNodeId = 2, Temperature = 25, Humidity = 78, Ambient_light = 344, Pressure = 455 }; newPoint.Acceleration = new TelemetryDataPoint.Accel() { X = 10, Y = 20, Z = 30 }; newPoint.Switch = new TelemetryDataPoint.Switchdata() { User1 = "Hewho", Hall = true }; newPoint.Vibration = new TelemetryDataPoint.Vibr() { Frequency = 2300, Power = 3455 }; newPoint.Node_status = new TelemetryDataPoint.Node_s() { Battery_level = 67 }; System.Diagnostics.Debug.WriteLine(newPoint.Pressure + " testi"); System.Diagnostics.Debug.WriteLine(messageDataPoint.Pressure + " testi2"); /* Read from SQL database */ try { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = "tcp:slanetestserver.database.windows.net,1433"; builder.UserID = "hhuotari"; builder.Password = "******"; builder.InitialCatalog = "slaneTestdb"; builder.PersistSecurityInfo = false; builder.MultipleActiveResultSets = false; builder.Encrypt = true; builder.TrustServerCertificate = false; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { System.Diagnostics.Debug.WriteLine("\nQuery data example:"); connection.Open(); StringBuilder sb = new StringBuilder(); sb.Append("SELECT * FROM SensorDataValues"); String sql = sb.ToString(); System.Diagnostics.Debug.WriteLine("=========================================\n"); using (SqlCommand command = new SqlCommand(sql, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { var nrOfFields = reader.FieldCount; while (reader.Read()) { System.Diagnostics.Debug.WriteLine("New record read from db:"); Object[] dataFields = new Object[nrOfFields]; reader.GetSqlValues(dataFields); System.Diagnostics.Debug.WriteLine("Id: " + reader.GetName(0) + " " + dataFields[0]); System.Diagnostics.Debug.WriteLine("Id: " + reader.GetName(2) + " " + dataFields[2]); } } } connection.Close(); } } catch (SqlException errorReceived) { Console.WriteLine(errorReceived.ToString()); } /* Write into SQL database */ try { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = "tcp:slanetestserver.database.windows.net,1433"; builder.UserID = "hhuotari"; builder.Password = "******"; builder.InitialCatalog = "slaneTestdb"; builder.PersistSecurityInfo = false; builder.MultipleActiveResultSets = false; builder.Encrypt = true; builder.TrustServerCertificate = false; int SensorId = messageDataPoint.SensorNodeId; double Temperature = messageDataPoint.Temperature; double Humidity = messageDataPoint.Humidity; double AccelarationX = messageDataPoint.Acceleration.X; double AccelarationY = messageDataPoint.Acceleration.Y; double AccelarationZ = messageDataPoint.Acceleration.Z; int AmbientLight = messageDataPoint.Ambient_light; int Pressure = messageDataPoint.Pressure; string SwitchDataUser = messageDataPoint.Switch.User1; bool Hall = messageDataPoint.Switch.Hall; int VibrationFrequency = messageDataPoint.Vibration.Frequency; int VibrationPower = messageDataPoint.Vibration.Power; int BatteryLevel = messageDataPoint.Node_status.Battery_level; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { System.Diagnostics.Debug.WriteLine("\nWrite data example:"); SqlCommand cmd = new SqlCommand(@"INSERT INTO SensorDataStream ( SensorId,Temperature, Humidity, AccelerationX, AccelerationY, AccelerationZ, AmbientLight, Pressure, SwitchDataUser, Hall, VibrationFrequency, VibrationPower, BatteryLevel) VALUES (@SensorId,@Temperature, @Humidity, @AccelerationX, @AccelerationY, @AccelerationZ, @AmbientLight, @Pressure, @SwitchDataUser, @Hall, @VibrationFrequency, @VibrationPower, @BatteryLevel)", connection); cmd.Parameters.AddWithValue("@SensorId", SensorId); cmd.Parameters.AddWithValue("@Temperature", Temperature); cmd.Parameters.AddWithValue("@Humidity", Humidity); cmd.Parameters.AddWithValue("@AccelerationX", AccelarationX); cmd.Parameters.AddWithValue("@AccelerationY", AccelarationY); cmd.Parameters.AddWithValue("@AccelerationZ", AccelarationZ); cmd.Parameters.AddWithValue("@AmbientLight", AmbientLight); cmd.Parameters.AddWithValue("@Pressure", Pressure); cmd.Parameters.AddWithValue("@SwitchDataUser", SwitchDataUser); cmd.Parameters.AddWithValue("@Hall", Hall); cmd.Parameters.AddWithValue("@VibrationFrequency", VibrationFrequency); cmd.Parameters.AddWithValue("@VibrationPower", VibrationPower); cmd.Parameters.AddWithValue("@BatteryLevel", BatteryLevel); cmd.Connection = connection; connection.Open(); cmd.ExecuteNonQuery(); connection.Close(); } } catch (SqlException errorReceived) { Console.WriteLine(errorReceived.ToString()); } Console.ReadLine(); }
public async Task SendStartupMessages() { _logger.LogInformation("Sending startup messages"); List <Task> tasks = new List <Task>(); foreach (Person p in _people) { Task t = Task.Run(async() => { Location curLocation = await _gridManager.GetGridLocation(p.GridLocation).ConfigureAwait(false); var telemetryDataPoint = new TelemetryDataPoint { DeviceId = p.IoTDeviceInfo.DeviceId, Name = p.Name, Type = p.Type, Grid_x = curLocation.Rowx, Grid_y = curLocation.Columny, Operation = "startup_completed" }; await SendIoTHubMessage(p, telemetryDataPoint).ConfigureAwait(false); }); tasks.Add(t); } foreach (Zone z in _zones) { Task t = Task.Run(async() => { Location curLocation = await _gridManager.GetGridLocation(z.GridLocation).ConfigureAwait(false); var telemetryDataPoint = new TelemetryDataPoint { DeviceId = z.IoTDeviceInfo.DeviceId, Name = z.Name, Type = z.Type, Grid_x = curLocation.Rowx, Grid_y = curLocation.Columny, Operation = "startup_completed" }; await SendIoTHubMessage(z, telemetryDataPoint).ConfigureAwait(false); }); tasks.Add(t); } foreach (Vehicle v in _vehicles) { Task t = Task.Run(async() => { Location curLocation = await _gridManager.GetGridLocation(v.GridLocation).ConfigureAwait(false); var telemetryDataPoint = new TelemetryDataPoint { DeviceId = v.IoTDeviceInfo.DeviceId, Name = v.Name, Type = v.Type, Grid_x = curLocation.Rowx, Grid_y = curLocation.Columny, Operation = "startup_completed" }; await SendIoTHubMessage(v, telemetryDataPoint).ConfigureAwait(false); }); tasks.Add(t); } try { Task.WaitAll(tasks.ToArray()); } catch (AggregateException e) { _logger.LogInformation("The following exceptions were encountered during processing"); for (int j = 0; j < e.InnerExceptions.Count; j++) { _logger.LogError(e.InnerExceptions[j].ToString()); } } }