public async void Start() { try { Logger.LogInformation($"Connecting device {device_id}"); if (!this.Connect()) { return; } while (!this.cancelToken.IsCancellationRequested) { for (int i = 0; i < Events.Length; i++) { SampleEventModel nextEvent = Events[i]; nextEvent.device_id = this.device_id; // initialize device_id from configuration file and datetime nextEvent.datetime = DateTime.Now.ToString(); string eventData = JsonSerializer.Serialize(nextEvent); try { await this.devClient.Publish(topic, eventData, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce); } catch (MQTTnet.Exceptions.MqttCommunicationException ex) { Logger.LogInformation($"Connection interrupted for device {device_id}"); if (!this.Connect()) { throw ex; } } Logger.LogInformation($"Event {eventData} sucessfully sent"); if (this.cancelToken.IsCancellationRequested) { Logger.LogInformation($"Shutting down event generation for device {device_id}"); break; } else { await Task.Delay(msg_interval * 1000); // in msec } } } } finally { this.devClient.Stop(); this.isStarted = false; } Logger.LogInformation($"Event generation for device {device_id} stopped"); }
private static SampleEventModel SplitAndFill(string line) { var sampleAlert = new SampleEventModel(); var props = typeof(SampleEventModel).GetProperties(); var values = line.Split(";"); for (var i = 0; i < values.Length; i++) { props[i].SetValue(sampleAlert, values[i]); } return(sampleAlert); }