Add NullObject & FileNotFound exception handling for publishing telemetry data

This commit is contained in:
Denis-Cosmin Nutiu 2019-11-15 17:53:20 +02:00
parent 572c12d43f
commit 70c1dc290c
4 changed files with 46 additions and 19 deletions

View file

@ -104,15 +104,25 @@ namespace NucuCar.Sensors.EnvironmentSensor
$"{_lastMeasurement.Temperature:N2} \u00B0C | {_lastMeasurement.Pressure:N2} hPa | {_lastMeasurement.Humidity:N2} %rH"); $"{_lastMeasurement.Temperature:N2} \u00B0C | {_lastMeasurement.Pressure:N2} hPa | {_lastMeasurement.Humidity:N2} %rH");
} }
public string GetIdentifier()
{
return nameof(EnvironmentSensor);
}
public Dictionary<string, double> GetTelemetryData() public Dictionary<string, double> GetTelemetryData()
{ {
return new Dictionary<string, double> Dictionary<string, double> returnValue = null;
if (_lastMeasurement != null)
{ {
["temperature"] = _lastMeasurement.Temperature, returnValue = new Dictionary<string, double>
["humidity"] = _lastMeasurement.Humidity, {
["pressure"] = _lastMeasurement.Pressure, ["temperature"] = _lastMeasurement.Temperature,
["voc"] = _lastMeasurement.VolatileOrganicCompound ["humidity"] = _lastMeasurement.Humidity,
}; ["pressure"] = _lastMeasurement.Pressure,
["voc"] = _lastMeasurement.VolatileOrganicCompound
};
}
return returnValue;
} }
} }
} }

View file

@ -1,9 +1,11 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace NucuCar.Sensors.Telemetry namespace NucuCar.Sensors.Telemetry
{ {
public interface ITelemetrySensor public interface ITelemetrySensor
{ {
string GetIdentifier();
/* Dictionary containing the topic and the value */ /* Dictionary containing the topic and the value */
Dictionary<string, double> GetTelemetryData(); Dictionary<string, double> GetTelemetryData();
} }

View file

@ -53,7 +53,7 @@ namespace NucuCar.Sensors.Telemetry
jwt = Jose.JWT.Encode(new Dictionary<string, object>() jwt = Jose.JWT.Encode(new Dictionary<string, object>()
{ {
["iat"] = DateTime.UtcNow, ["iat"] = DateTime.UtcNow,
["exp"] = DateTime.UtcNow.AddMinutes(60), ["exp"] = DateTime.UtcNow.AddDays(60),
["aud"] = ProjectId ["aud"] = ProjectId
}, rsa, Jose.JwsAlgorithm.RS256); }, rsa, Jose.JwsAlgorithm.RS256);
} }
@ -74,17 +74,27 @@ namespace NucuCar.Sensors.Telemetry
public async Task StartAsync() public async Task StartAsync()
{ {
var options = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithClientId($"projects/{ProjectId}/locations/{Region}/registries/{RegistryId}/devices/{DeviceId}")
.WithCredentials("unused", GetMqttPassword())
.WithTcpServer("mqtt.googleapis.com")
.WithTls().Build())
.Build();
_logger.LogInformation("Starting the MQTT client."); _logger.LogInformation("Starting the MQTT client.");
ManagedMqttClientOptions options;
try
{
options = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithClientId($"projects/{ProjectId}/locations/{Region}/registries/{RegistryId}/devices/{DeviceId}")
.WithCredentials("unused", GetMqttPassword())
.WithTcpServer("mqtt.googleapis.com")
.WithTls().Build())
.Build();
}
catch (IOException e)
{
_logger.LogCritical(e.Message);
throw;
}
await _mqttClient.StartAsync(options); await _mqttClient.StartAsync(options);
_logger.LogInformation("Started the MQTT client!");
} }
public async Task PublishDataAsync(CancellationToken cancellationToken) public async Task PublishDataAsync(CancellationToken cancellationToken)
@ -92,6 +102,11 @@ namespace NucuCar.Sensors.Telemetry
foreach (var sensor in _registeredSensors) foreach (var sensor in _registeredSensors)
{ {
var data = sensor.GetTelemetryData(); var data = sensor.GetTelemetryData();
if (data == null)
{
_logger.LogWarning($"Warning! Data for {sensor.GetIdentifier()} is null!");
continue;
}
await UploadData(data, cancellationToken); await UploadData(data, cancellationToken);
} }
} }

View file

@ -1,16 +1,16 @@
{ {
"Telemetry": { "Telemetry": {
"Enabled": true, "Enabled": true,
"Interval": 5000, "Interval": 3000,
"ProjectId": "playground-239221", "ProjectId": "playground-239221",
"DeviceId": "3087236321317137", "DeviceId": "3087236321317137",
"RegistryId": "Development", "RegistryId": "Development",
"Region": "europe-west1", "Region": "europe-west1",
"RS256File": "Certificates\\key.key" "RS256File": "/home/denis/Projects/RiderProjects/NucuCar/NucuCar.Sensors/Certificates/jwt.key"
}, },
"EnvironmentSensor": { "EnvironmentSensor": {
"Enabled": true, "Enabled": true,
"Telemetry": false, "Telemetry": true,
"MeasurementInterval": 1000 "MeasurementInterval": 1000
}, },
"Logging": { "Logging": {