private void CreateEvent(SensorStatus sensorStatus) { var sensor = _sensorServer.GetSensorById(sensorStatus.SensorId).Result; var isAlarming = IsAlarming(sensorStatus, sensor); var existingEvent = _events.FirstOrDefault(e => e.Id == sensor.Id); if (isAlarming) { if (existingEvent == null) { // Sensor doesn't have an event so create one var newEvent = CreateNewEvent(sensorStatus, sensor); newEvent.Alarms.Add(CreateEventAlarm(sensorStatus, isAlarming)); _cacheService.AddEntity(newEvent); _events.Add(newEvent); } else { // Event exists for this sensor existingEvent.StatusType = sensorStatus.StatusType.ToString(); existingEvent.TimeRecieved = sensorStatus.TimeStamp; existingEvent.IsAlarming = isAlarming; // Prevents an exception caused by the current running task when closing the application if (App.Current != null) { App.Current.Dispatcher.Invoke(() => existingEvent.Alarms.Add(CreateEventAlarm(sensorStatus, isAlarming))); } _cacheService.UpdateEntity(existingEvent); } } else if (existingEvent != null) { // Event exists for this sensor existingEvent.StatusType = sensorStatus.StatusType.ToString(); existingEvent.TimeRecieved = sensorStatus.TimeStamp; existingEvent.IsAlarming = isAlarming; // Prevents an exception caused by the current running task when closing the application if (App.Current != null) { App.Current.Dispatcher.Invoke(() => existingEvent.Alarms.Add(CreateEventAlarm(sensorStatus, isAlarming))); } _cacheService.UpdateEntity(existingEvent); } }
public void AddEvent(Sensor result, SensorStatus sensorStatus) { InvokerHelper.RunSave(async() => { SensorCollection currentSensorCollection; bool event_exist = false; //foreach (var sensor in SensorCollection) //{ // if (result.Id == sensor.CurrentSensor.Id) // { // event_exist = true; // break; // } //} Parallel.ForEach(SensorCollection, (sensor, state) => { if (result.Id == sensor.CurrentSensor.Id) { event_exist = true; state.Stop(); } }); if (IsSensorAlarming(result, sensorStatus)) { if (event_exist) { currentSensorCollection = SensorCollection.FirstOrDefault(t => t.CurrentSensor.Id == result.Id); if (currentSensorCollection != null) { bool canUpdate = await cacheService.UpdateEntity(currentSensorCollection.CurrentSensor); if (canUpdate) { currentSensorCollection.SensorEvents.EventAlarms?. Add(new EventAlarm(sensorStatus)); UpdateSensorEvent?. Invoke(null, currentSensorCollection); } } } else { currentSensorCollection = new SensorCollection() { CurrentSensor = result, FirstSensorStatus = sensorStatus, SensorEvents = new Event() { EventAlarms = new List <EventAlarm>() { new EventAlarm(sensorStatus) } } }; bool canSave = await cacheService.AddEntity(currentSensorCollection.CurrentSensor); if (canSave) { if (sensorStatus.StatusType == StatusType.Alarm) { SensorCollection.Add(currentSensorCollection); } else { SensorCollection.Insert(0, currentSensorCollection); } AddSensorEvent?. Invoke(null, currentSensorCollection); } } } }); }