Beispiel #1
0
        public IHttpActionResult FireAlarm(FireAlarm alarm)
        {
            AlarmDomain alarmDomain   = new AlarmDomain();
            DeviceRead  currentDevice = StaticContext.GetCurrentDevice();

            if (currentDevice == null)
            {
                throw new UnauthorizedAccessException("Device token required");
            }

            ValuesDomain valuesDomain = new ValuesDomain();
            DeviceValue  val          = new DeviceValue();

            val          = Utilities.Map <FireAlarm, DeviceValue>(alarm, val);
            val.DeviceId = currentDevice.Id;
            val.AlarmId  = alarm.AlarmId;
            valuesDomain.SaveValue(val);



            if (alarm.Side == "onserver")
            {
                AlarmFireDto alarmDto = new AlarmFireDto();
                alarmDto = Utilities.Map <FireAlarm, AlarmFireDto>(alarm, alarmDto);
                alarmDomain.FireAlarm(alarmDto);
            }
            return(Ok());
        }
Beispiel #2
0
        public async Task DeviceUpdated(DeviceMaster deviceInfo, DeviceValue value)
        {
            var device = _deviceMap.FirstOrDefault(x => x.Id == value.MasterDeviceId);

            if (device == null)
            {
                return;
            }

            _logger.LogInformation($"Device update {IdPrefix}{device.Id}");

            await _client.PublishAsync(new MqttApplicationMessage
            {
                Topic       = $"{_mqttConfig.BaseTopic}/{IdPrefix}{device.Id}/state",
                ContentType = "text/plain",
                Retain      = true,
                Payload     = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(deviceInfo.State, SerializerSettings))
            });

            await _client.PublishAsync(deviceInfo.Devices.Where(x => x.Value.CurrentValue != null).Select(x => new MqttApplicationMessage
            {
                Topic       = $"{_mqttConfig.BaseTopic}/{IdPrefix}{device.Id}/{x.Key}",
                ContentType = "text/plain",
                Retain      = true,
                Payload     = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(x.Value.CurrentValue, SerializerSettings))
            }));
        }
Beispiel #3
0
        private async Task AddOrUpdateValue(string name, string value, int deviceId, DataType dataType, string valueName,
                                            string genre, ZvsContext context)
        {
            context.DeviceValues.FirstOrDefaultAsync(d => d.DeviceId == deviceId && d.Name == valueName)
            .ContinueWith(t
                          =>
            {
                DeviceValue dv = t.Result;
                if (dv == null)
                {
                    dv = new DeviceValue
                    {
                        DeviceId  = deviceId,
                        Name      = valueName,
                        ValueType = dataType,
                        Genre     = genre
                    };

                    context.DeviceValues.Add(dv);
                }

                dv.Value = value;

                context.TrySaveChangesAsync().ContinueWith(tt =>
                {
                    if (tt.Result.HasError)
                    {
                        ZvsEngine.log.Error(tt.Result.Message);
                    }
                }).Wait();
            }).Wait();
        }
Beispiel #4
0
 public static StoredDeviceValueV1 <T> ToStored <T>(this DeviceValue <T> deviceValue)
 {
     return(new StoredDeviceValueV1 <T>
     {
         Value = deviceValue.Value,
         Status = deviceValue.Status.ToStored()
     });
 }
Beispiel #5
0
        private void ClientDeviceUpdated(object sender, DeviceValue value)
        {
            var masterId = value.MasterDeviceId == 0 ? value.DeviceId : value.MasterDeviceId;
            var device   = GetDevice(masterId);

            if (device?.SetValues(value) ?? false)
            {
                DeviceUpdated?.Invoke(this, value);
            }
        }
        public async Task <ActionResult> SetDeviceAsync([FromBody] DeviceValue setDevice)
        {
            var device = await _dbContext.GetDevices(User.Identity.Name)
                         .FirstOrDefaultAsync(settingDevice => settingDevice.Id == setDevice.Id);

            device.Value = setDevice.Value;

            await _dbContext.SaveChangesAsync();

            return(Ok(new { id = device.Id, value = device.Value }));
        }
        public IHttpActionResult SaveValue(string propertyName, DeviceValue value)
        {
            DeviceRead currentDevice = StaticContext.GetCurrentDevice();

            value.DeviceId     = currentDevice.Id;
            value.PropertyName = propertyName;
            ValuesDomain valuesDomain = new ValuesDomain();

            valuesDomain.SaveValue(value);
            return(Ok());
        }
 internal void SetPressureParams([NotNull] PatientPressureParams pressureParams)
 {
     if (pressureParams == null)
     {
         throw new ArgumentNullException(nameof(pressureParams));
     }
     IsAnyValueObtained        = true;
     SystolicArterialPressure  = new DeviceValue <short>(pressureParams.SystolicArterialPressure);
     DiastolicArterialPressure = new DeviceValue <short>(pressureParams.DiastolicArterialPressure);
     AverageArterialPressure   = new DeviceValue <short>(pressureParams.AverageArterialPressure);
 }
 internal void SetCommonParams([NotNull] CommonPatientParams patientParams)
 {
     if (patientParams == null)
     {
         throw new ArgumentNullException(nameof(patientParams));
     }
     IsAnyValueObtained = true;
     HeartRate          = new DeviceValue <short>(patientParams.HeartRate);
     RespirationRate    = new DeviceValue <short>(patientParams.RespirationRate);
     Spo2 = new DeviceValue <short>(patientParams.Spo2);
 }
        internal void HandleErrorOnPressureParamsProcessing()
        {
            // на тот случай, если данные в рамках итерации были получены, но итерация не завершилась, а ошиюба возникла
            if (AverageArterialPressure.Status == DeviceValueStatus.Obtained)
            {
                return;
            }

            SystolicArterialPressure  = new DeviceValue <short>(DeviceValueStatus.ErrorOccured);
            DiastolicArterialPressure = new DeviceValue <short>(DeviceValueStatus.ErrorOccured);
            AverageArterialPressure   = new DeviceValue <short>(DeviceValueStatus.ErrorOccured);
        }
        internal void HandleErrorOnCommoParamsProcessing()
        {
            // на тот случай, если данные в рамках итерации были получены, но итерация не завершилась, а ошибка возникла
            if (HeartRate.Status == DeviceValueStatus.Obtained)
            {
                return;
            }

            HeartRate       = new DeviceValue <short>(DeviceValueStatus.ErrorOccured);
            RespirationRate = new DeviceValue <short>(DeviceValueStatus.ErrorOccured);
            Spo2            = new DeviceValue <short>(DeviceValueStatus.ErrorOccured);
        }
Beispiel #12
0
        public async Task <Result> RegisterAsync(DeviceValue deviceValue, Device device, CancellationToken cancellationToken)
        {
            if (deviceValue == null)
            {
                return(Result.ReportError("You must send a device value when registering a device value!"));
            }

            if (device == null)
            {
                return(Result.ReportError("You must send a device when registering a device value!"));
            }

            using (var context = new ZvsContext(EntityContextConnection))
            {
                var existingDv =
                    await
                    context.DeviceValues.FirstOrDefaultAsync(o => o.UniqueIdentifier == deviceValue.UniqueIdentifier &&
                                                             o.DeviceId == device.Id, cancellationToken);

                if (existingDv == null)
                {
                    //NEW VALUE
                    context.DeviceValues.Add(deviceValue);
                    return(await context.TrySaveChangesAsync(cancellationToken));
                }

                var hasChanged = false;
                PropertyChangedEventHandler action = (s, a) => hasChanged = true;
                existingDv.PropertyChanged += action;

                existingDv.CommandClass = deviceValue.CommandClass;
                existingDv.CustomData1  = deviceValue.CustomData1;
                existingDv.CustomData2  = deviceValue.CustomData2;
                existingDv.Genre        = deviceValue.Genre;
                existingDv.Index        = deviceValue.Index;
                existingDv.IsReadOnly   = deviceValue.IsReadOnly;
                existingDv.Description  = deviceValue.Description;
                existingDv.Name         = deviceValue.Name;
                existingDv.ValueType    = deviceValue.ValueType;
                existingDv.Value        = deviceValue.Value;
                existingDv.IsReadOnly   = deviceValue.IsReadOnly;

                existingDv.PropertyChanged -= action;

                if (hasChanged)
                {
                    return(await context.TrySaveChangesAsync(cancellationToken));
                }

                return(Result.ReportSuccess("Nothing to update"));
            }
        }
        public CheckPointParams(
            short cycleNumber,
            short iterationNumber,
            float inclinationAngle)
        {
            CycleNumber      = cycleNumber;
            IterationNumber  = iterationNumber;
            InclinationAngle = inclinationAngle;

            HeartRate                 = new DeviceValue <short>();
            RespirationRate           = new DeviceValue <short>();
            Spo2                      = new DeviceValue <short>();
            SystolicArterialPressure  = new DeviceValue <short>();
            DiastolicArterialPressure = new DeviceValue <short>();
            AverageArterialPressure   = new DeviceValue <short>();
        }
        public async Task RegisterAsyncUpdatedDeviceValueTest()
        {
            //arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var dvb = new DeviceValueBuilder(dbConnection);

            var device = UnitTesting.CreateFakeDevice();

            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                var deviceValue = new DeviceValue
                {
                    UniqueIdentifier = "UNIT_TESTING_VALUE1",
                    CommandClass     = "Command Class 1",
                    CustomData1      = "Custom Data 1",
                    CustomData2      = "Custom Data 2",
                    Description      = "Testing Value Description Here",
                    Name             = "Test Value",
                    ValueType        = DataType.BOOL,
                    Value            = true.ToString(),
                    Genre            = "Genre",
                    Index            = "Index",
                    IsReadOnly       = true
                };
                device.Values.Add(deviceValue);

                await context.SaveChangesAsync();

                deviceValue.Value = false.ToString();

                //act
                var result = await dvb.RegisterAsync(deviceValue, device, CancellationToken.None);

                var dv = await context.DeviceValues.FirstOrDefaultAsync(o => o.Name == deviceValue.Name);


                //assert
                Assert.IsFalse(result.HasError, result.Message);
                Assert.IsNotNull(dv, "Registered device value count not be found in database.");
                Assert.AreEqual(dv.Value, false.ToString(), "Device value not updated properly");
                Console.WriteLine(result.Message);
            }
        }
        public async Task RegisterAsyncNewDeviceValueTest()
        {
            //arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var dvb = new DeviceValueBuilder(dbConnection);

            var device = UnitTesting.CreateFakeDevice();

            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                await context.SaveChangesAsync();

                var deviceValue = new DeviceValue
                {
                    Description = "Testing Value Description Here",
                    Name        = "Test Value",
                    ValueType   = DataType.BOOL,
                    Value       = true.ToString(),
                    DeviceId    = device.Id
                };

                //act
                var result = await dvb.RegisterAsync(deviceValue, device, CancellationToken.None);

                var dv = await context.DeviceValues.FirstOrDefaultAsync(o => o.Name == deviceValue.Name);


                //assert
                Assert.IsFalse(result.HasError, result.Message);
                Assert.IsNotNull(dv, "Registered device value count not be found in database.");
                Console.WriteLine(result.Message);
            }
        }
Beispiel #16
0
        public void Dispatch(DeviceLookup lookup)
        {
            //Update values
            DateTime now = DateTime.Now;

            for (int i = 0; i < _config.Count; i++)
            {
                int messageIndex = i / TelemetryMessage.EntryLength;
                int entryIndex   = i % TelemetryMessage.EntryLength;

                DeviceValue entry = _messages[messageIndex].Devices[entryIndex];
                object      value = lookup[entry.Hash].Get();
                if (lookup[entry.Hash].Property.PropertyType == typeof(Int32))
                {
                    _messages[messageIndex].Devices[entryIndex].IValue = (Int32)value;
                }
                else if (lookup[entry.Hash].Property.PropertyType == typeof(float))
                {
                    _messages[messageIndex].Devices[entryIndex].DValue = (float)value;
                }
                else
                {
                    Console.WriteLine("Unknown Type: {0}", lookup[entry.Hash].Property.PropertyType);
                }
            }

            //Send packets
            foreach (TelemetryMessage message in _messages)
            {
                //var m = message;
                //m.Header.DateTime = now;

                //Send telemetry
                byte[] buffer = StructSerializer.Serialize(message);
                _stream.Write(buffer);
            }
        }
Beispiel #17
0
 private void DeviceUpdatedRelay(object sender, DeviceValue value)
 {
     _mqttClient.DeviceUpdated(_smartfriendsSession.GetDevice(value.MasterDeviceId), value).GetAwaiter().GetResult();
 }
Beispiel #18
0
        public async Task ContraLessThanTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var logEntries        = new List <LogEntry>();
            var ranstoredCommands = new List <int>();
            var log = new StubIFeedback <LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    logEntries.Add(e);
                    return(Task.FromResult(0));
                }
            };

            var commandProcessor = new StubICommandProcessor
            {
                RunCommandAsyncNullableOfInt32StringStringCancellationToken = (commandId, argument, argument2, cancellationToken) =>
                {
                    if (commandId.HasValue)
                    {
                        ranstoredCommands.Add(commandId.Value);
                    }
                    return(Task.FromResult(Result.ReportSuccess()));
                }
            };


            Database.SetInitializer(new CreateFreshDbInitializer());

            var cts            = new CancellationTokenSource();
            var triggerManager = new TriggerRunner(log, commandProcessor, dbConnection);
            await triggerManager.StartAsync(cts.Token);

            var cmd = new Command();
            var dv  = new DeviceValue
            {
                Value     = "first value",
                ValueType = DataType.STRING,
                Triggers  = new ObservableCollection <DeviceValueTrigger> {
                    new DeviceValueTrigger
                    {
                        Name      = "trigger1",
                        IsEnabled = true,
                        Operator  = TriggerOperator.LessThan,
                        Value     = "1",
                        Command   = cmd
                    }
                }
            };

            var device = UnitTesting.CreateFakeDevice();

            device.Values.Add(dv);
            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                var r = await context.TrySaveChangesAsync(cts.Token);

                Assert.IsFalse(r.HasError, r.Message);
                dv.Value = "3";

                //Act
                var r2 = await context.TrySaveChangesAsync(cts.Token);

                Assert.IsFalse(r2.HasError, r2.Message);
            }
            await Task.Delay(700, cts.Token);

            await triggerManager.StopAsync(cts.Token);

            //Assert
            Assert.IsTrue(logEntries.All(o => o.Level != LogEntryLevel.Error), "Expected no error log entries");
            Assert.IsTrue(ranstoredCommands.Count == 0, "Trigger runner did not run the correct amount of commands.");
        }
Beispiel #19
0
        public async Task QuickFireTriggerTest()
        {
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var logEntries        = new List <LogEntry>();
            var ranstoredCommands = new List <int>();

            //Arrange
            var log = new StubIFeedback <LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    logEntries.Add(e);
                    return(Task.FromResult(0));
                }
            };

            var commandProcessor = new StubICommandProcessor
            {
                RunCommandAsyncNullableOfInt32StringStringCancellationToken = (commandId, argument, argument2, cancellationToken) =>
                {
                    if (commandId.HasValue)
                    {
                        ranstoredCommands.Add(commandId.Value);
                    }
                    return(Task.FromResult(Result.ReportSuccess()));
                }
            };

            var cts            = new CancellationTokenSource();
            var triggerManager = new TriggerRunner(log, commandProcessor, dbConnection);
            await triggerManager.StartAsync(cts.Token);

            var cmd = new Command();
            var dv  = new DeviceValue
            {
                Value     = "first value",
                ValueType = DataType.STRING,
                Triggers  = new ObservableCollection <DeviceValueTrigger> {
                    new DeviceValueTrigger
                    {
                        Name      = "trigger1",
                        IsEnabled = true,
                        Operator  = TriggerOperator.EqualTo,
                        Value     = "some unique value",
                        Command   = cmd
                    }
                }
            };

            var device = UnitTesting.CreateFakeDevice();

            device.Values.Add(dv);

            //Act
            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                await context.TrySaveChangesAsync(cts.Token);

                dv.Value = "Not It!";
                await context.TrySaveChangesAsync(cts.Token);

                dv.Value = "not this one";
                await context.TrySaveChangesAsync(cts.Token);

                dv.Value = "some unique value";
                await context.TrySaveChangesAsync(cts.Token);

                dv.Value = "not it";
                await context.TrySaveChangesAsync(cts.Token);

                dv.Value = "some unique value";
                await context.TrySaveChangesAsync(cts.Token);

                Console.WriteLine(context.DeviceValueTriggers.Count());
            }

            await Task.Delay(700, cts.Token);

            await triggerManager.StopAsync(cts.Token);

            //Assert
            Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Info), "Expected only info type log entries");
            Assert.IsTrue(ranstoredCommands.Count == 2, "Trigger runner did not run the correct amount of commands.");
            Assert.IsTrue(ranstoredCommands.All(o => o == cmd.Id), "Scheduled task runner did not run the correct command.");
        }