Exemple #1
0
        public void testHandleData_shouldReceiveGlobalNotification()
        {
            GlobalUpdate        globalUpdate  = null;
            DeviceUpdate        deviceUpdate  = null;
            List <Camera>       cameras       = null;
            List <Thermostat>   thermostats   = null;
            List <SmokeCOAlarm> smokeCOAlarms = null;
            List <Structure>    structures    = null;
            Metadata            metadata      = null;

            var notifier = new Notifier();

            notifier.GlobalUpdated       += (sender, args) => { globalUpdate = args.Data; };
            notifier.DeviceUpdated       += (sender, args) => { deviceUpdate = args.Data; };
            notifier.CameraUpdated       += (sender, args) => { cameras = args.Data; };
            notifier.ThermostatUpdated   += (sender, args) => { thermostats = args.Data; };
            notifier.SmokeCOAlarmUpdated += (sender, args) => { smokeCOAlarms = args.Data; };
            notifier.StructureUpdated    += (sender, args) => { structures = args.Data; };
            notifier.MetadataUpdated     += (sender, args) => { metadata = args.Data; };

            notifier.HandleData(new GlobalUpdate(
                                    thermostats: new List <Thermostat>(),
                                    smokeCOAlarms: new List <SmokeCOAlarm>(),
                                    cameras: new List <Camera>(),
                                    structures: new List <Structure>(),
                                    metadata: new Metadata()));

            Assert.IsNotNull(globalUpdate);
            Assert.IsNotNull(deviceUpdate);
            Assert.IsNotNull(cameras);
            Assert.IsNotNull(thermostats);
            Assert.IsNotNull(smokeCOAlarms);
            Assert.IsNotNull(structures);
            Assert.IsNotNull(metadata);
        }
        private void InitSystem()
        {
            Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(1000, 1000, Self, new Evalutate(), ActorRefs.NoSender);

            var gatewaystrepo = repositoryManager.Ask <List <GatewayModel> >(new GetAll()).Result;

            foreach (var gateway in gatewaystrepo)
            {
                var gatewayCreated     = new GatewayCreated(gateway.Id);
                var gatewaySended      = new GatewaySended(gateway.Id, gateway.Value);
                var gatewayStarted     = new GatewayStarted(gateway.Id, gateway.Ip);
                var gatewayUpdate      = new GatewayUpdate(gateway.Id, gateway.Name);
                var gatewayDisconnectd = new GatewayDisconnected(gateway.Id);
                var gatewayStatus      = new GatewayStatus(gateway.Id);

                deviceManager.Tell(gatewayCreated.GatewayPhysicalCreated);
                dashboardManager.Tell(gatewayCreated.GatewayDashBoardCreated);

                deviceManager.Tell(gatewaySended.GatewayPhysicalSended);
                dashboardManager.Tell(gatewaySended.GatewayDashBoardSended);

                dashboardManager.Tell(gatewayStarted.GatewayDashBoardStarted);

                dashboardManager.Tell(gatewayUpdate.GatewayDashBoardUpdate);

                deviceManager.Tell(gatewayDisconnectd.GatewayPhysicalDisconnected);
                dashboardManager.Tell(gatewayDisconnectd.GatewayDashBoardDisconnected);

                deviceManager.Tell(gatewayStatus.GatewayPhysicalStatus);

                foreach (var device in gateway.Devices)
                {
                    var deviceInfo        = new DeviceInfo(device.Id, gateway.Id);
                    var deviceCreated     = new DeviceCreated(deviceInfo);
                    var deviceSended      = new DeviceSended(deviceInfo, device.Value);
                    var deviceStarted     = new DeviceStarted(deviceInfo, device.Ip);
                    var deviceUpdate      = new DeviceUpdate(deviceInfo, device.Name);
                    var deviceDisconnectd = new DeviceDisconnected(deviceInfo);
                    var deviceStatus      = new DeviceStatus(deviceInfo);

                    deviceManager.Tell(deviceCreated.DevicePhysicalCreated);
                    dashboardManager.Tell(deviceCreated.DeviceDashBoardCreated);

                    deviceManager.Tell(deviceSended.DevicePhysicalSended);
                    dashboardManager.Tell(deviceSended.DeviceDashBoardSended);

                    dashboardManager.Tell(deviceStarted.DeviceDashBoardStarted);

                    dashboardManager.Tell(deviceUpdate.DeviceDashBoardUpdate);

                    deviceManager.Tell(deviceDisconnectd.DevicePhysicalDisconnected);
                    dashboardManager.Tell(deviceDisconnectd.DeviceDashBoardDisconnected);

                    deviceManager.Tell(deviceStatus.DevicePhysicalStatus);
                }
            }
        }
Exemple #3
0
        async Task <DeviceState[]> SetDeviceState(string deviceId, DeviceUpdate state)
        {
            var manager = ServiceProvider.GetService <IDeviceManager>();
            var device  = await DeviceDatabase.Shared.GetDevice(deviceId);

            if (!await manager.SetDeviceState(device, state))
            {
                throw new Exception("Error processing the request");
            }
            return(new[] { await DeviceDatabase.Shared.GetDeviceState(deviceId, state.PropertyKey) });
        }
Exemple #4
0
 public async Task <bool> HandleRequest(Rosie.Device device, DeviceUpdate request)
 {
     //switch (request.Key)
     //{
     //	case DeviceStateKey.SwitchState:
     //		if (request.BoolValue.Value)
     //			await api.TurnOnDevice();
     //		return true;
     //}
     return(false);
 }
Exemple #5
0
        public void testDeviceUpdate_shouldReturnSameObjectInGetters()
        {
            var testThermos     = new List <Thermostat>();
            var testSmokeAlarms = new List <SmokeCOAlarm>();
            var testCams        = new List <Camera>();

            var update = new DeviceUpdate(testThermos, testSmokeAlarms, testCams);

            Assert.AreSame(testThermos, update.Thermostats);
            Assert.AreSame(testSmokeAlarms, update.SmokeCOAlarms);
            Assert.AreSame(testCams, update.Cameras);
        }
Exemple #6
0
        public JsonResult CreateUpdate()
        {
            try
            {
                String jsonData = new StreamReader(Request.InputStream).ReadToEnd();
                Newtonsoft.Json.Linq.JObject token = JObject.Parse(jsonData);
                var deviceSerialNumber             = (string)token.SelectToken("DeviceSerialNumber");
                var value = (string)token.SelectToken("Value");

                var device = db.Devices
                             .Where(m => m.SerialNumber == deviceSerialNumber)
                             .FirstOrDefault();

                if (device == null)
                {
                    return(Json(new
                    {
                        status = "ERROR",
                        message = "Device not found"
                    }));
                }

                var update = new DeviceUpdate();
                update.Value    = value;
                update.DateTime = DateTime.Now;
                device.Updates.Add(update);
                db.SaveChanges();

                return(Json(
                           new
                {
                    status = "OK",
                    message = "Device update created"
                }));
            }
            catch (Exception ex)
            {
                return(Json(new
                {
                    status = "ERROR",
                    message = "Error: " + ex.Message
                }));
            }
        }
Exemple #7
0
 public static object GetValue(this NodeDeviceCommands command, DeviceUpdate update)
 {
     if (command.SimpleStringCommand == "38 - 0")
     {
         if (update.DataType == DataTypes.Bool)
         {
             return(update.BoolValue.Value ? 99 : 0);
         }
         if (update.DataType == DataTypes.Decimal)
         {
             return(Clamp((int)update.DecimalValue.Value, 0, 99));
         }
         if (update.DataType == DataTypes.Int)
         {
             return(Clamp(update.IntValue.Value, 0, 99));
         }
     }
     return(update.Value);
 }
        public async void OnRegistered(string registrationId)
        {
            ///CheckFile();

            HttpClient client = new HttpClient();

            var request = JsonConvert.SerializeObject("0");
            var body    = new StringContent(request, System.Text.Encoding.UTF8, "application/json");

            client.BaseAddress = new Uri("http://lnbservices.azurewebsites.net");
            var url = "/api/RegisterNotification";

            var response = await client.PostAsync(url, body);

            if (response.IsSuccessStatusCode)
            {
                var estado = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result).ToString();
                if (!string.IsNullOrEmpty(estado))
                {
                    var device = new DeviceUpdate
                    {
                        Handler  = registrationId,
                        ID       = estado,
                        Platform = "gcm",
                        Tags     = new string[] { "juegos", "noticias" }
                    };
                    var deviceResquest = JsonConvert.SerializeObject(device);
                    body = new StringContent(deviceResquest, System.Text.Encoding.UTF8, "application/json");

                    response = await client.PutAsync(url, body);

                    var data = response.Content;
                    if (response.IsSuccessStatusCode)
                    {
                        var data1 = response.Content;
                    }
                }
            }
            else
            {
                string n = response.StatusCode.ToString();
            }
        }
        public bool TcUpdate([FromBody] TcHttpModel req)
        {
            List <Device> devicesList = db.DeviceModels.ToList();

            ExtensionMethods.WriteStringToFile(req.build.buildFullName);
            client.Publish("/home/temperature", Encoding.ASCII.GetBytes(req.build.buildFullName));

            foreach (Device device in devicesList)
            {
                if (device.SubscribedBranches.Contains(req.build.branchName))
                {
                    bool         result = req.build.buildResult == "success";
                    DeviceUpdate deviceUpdateMessage = new DeviceUpdate(req.build.buildName, req.build.notifyType, result, req.build.branchName);
                    Utilities.MakeWebRequestToDevice(device.IpAddress, deviceUpdateMessage);
                }
            }

            return(true);
        }
Exemple #10
0
        public void MakeWebRequestToDevice(string url, DeviceUpdate deviceUpdate)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(String.Format("{0}/Update", url));

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = JsonConvert.SerializeObject(deviceUpdate);
                streamWriter.Write(json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }
        }
Exemple #11
0
        /// <summary>
        /// Updates the device.
        /// </summary>
        /// <returns>The device.</returns>
        /// <param name="deviceUpdate">Device update.</param>
        /// <param name="deviceId">Device identifier.</param>
        public async Task <Device> UpdateDeviceAsync(DeviceUpdate deviceUpdate, string deviceId = null)
        {
            if (!MainDeviceSet)
            {
                throw new MatchmoreException("Main nor optional device is not ready");
            }

            var _deviceId     = deviceId ?? MainDevice.Id;
            var updatedDevice = await _client.UpdateDeviceAsync(deviceId, deviceUpdate);

            var(device, isMain) = FindDevice(updatedDevice.Id);
            if (isMain)
            {
                MainDevice = updatedDevice;
            }
            else
            {
                _state.UpsertDevice(updatedDevice);
            }
            return(updatedDevice);
        }
Exemple #12
0
        /// <summary>
        /// Updates name or/and device token for existing device Token can be only updated for mobile devices.
        /// </summary>
        /// <param name="device">The device update description.</param>
        /// <returns>Device</returns>
        public Device UpdateDevice(DeviceUpdate device)
        {
            // verify the required parameter 'device' is set
            if (device == null)
            {
                throw new ApiException(400, "Missing required parameter 'device' when calling UpdateDevice");
            }


            var path = "/devices/{deviceId}";

            path = path.Replace("{format}", "json");

            var    queryParams  = new Dictionary <String, String>();
            var    headerParams = new Dictionary <String, String>();
            var    formParams   = new Dictionary <String, String>();
            var    fileParams   = new Dictionary <String, FileParameter>();
            String postBody     = null;

            postBody = ApiClient.Serialize(device);                                     // http body (model) parameter

            // authentication setting, if any
            String[] authSettings = new String[] {  };

            // make the HTTP request
            IRestResponse response = (IRestResponse)ApiClient.CallApi(path, Method.PATCH, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

            if (((int)response.StatusCode) >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling UpdateDevice: " + response.Content, response.Content);
            }
            else if (((int)response.StatusCode) == 0)
            {
                throw new ApiException((int)response.StatusCode, "Error calling UpdateDevice: " + response.ErrorMessage, response.ErrorMessage);
            }

            return((Device)ApiClient.Deserialize(response.Content, typeof(Device), response.Headers));
        }
Exemple #13
0
        public async Task <bool> HandleRequest(Device device, DeviceUpdate request)
        {
            try
            {
                var nodeId     = int.Parse(device.ServiceDeviceId);
                var nodeDevice = await NodeDatabase.Shared.GetDevice(nodeId);

                if (!ZWaveCommands.RosieCommandsToZwaveDictionary.TryGetValue(request.PropertyKey, out var commandId))
                {
                    throw new NotSupportedException($"The following key is not supported in Zwave: {request.PropertyKey}");
                }
                var command = await nodeDevice.GetCommand(request);

                var s = await nodeApi.SetState(command, command.GetValue(request));

                return(s);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return(false);
        }
Exemple #14
0
        protected override void Seed(DemoIoTWeb.Models.DemoIoTContext context)
        {
            User admin = new User();

            admin.Email    = "*****@*****.**";
            admin.Password = Crypto.HashPassword("admin123");
            admin.isAdmin  = true;
            context.Users.Add(admin);
            context.SaveChanges();

            User testUser = new User();

            testUser.Email    = "*****@*****.**";
            testUser.Password = Crypto.HashPassword("test123");
            context.Users.Add(testUser);
            context.SaveChanges();

            if (context.Devices.Count() == 0)
            {
                Device device = new Device();
                device.SerialNumber = "1";
                device.Description  = "Dispositivo de teste";
                device.User         = testUser;
                context.Devices.Add(device);
                context.SaveChanges();

                for (int i = 0; i < 100; i++)
                {
                    DeviceUpdate update = new DeviceUpdate();
                    update.Value    = i.ToString();
                    update.DateTime = DateTime.Now;
                    device.Updates.Add(update);
                }

                context.SaveChanges();
            }
        }
 /// <summary>
 /// Al recibir una solicitud de actualización de un usuario
 /// </summary>
 /// <param name="sender">Emisor</param>
 /// <param name="e">Actualización de dispositivo</param>
 private void User_OnRequestsUpdate(object sender, DeviceUpdate e)
 {
     m_deviceManager.Send(e.SerialNumber, e);
 }
Exemple #16
0
        public static async Task <NodeDeviceCommands> GetCommand(this NodeDevice device, DeviceUpdate update)
        {
            if (!ZWaveCommands.RosieCommandsToZwaveDictionary.TryGetValue(update.PropertyKey, out var commandId))
            {
                throw new NotSupportedException($"The following key is not supported in Zwave: {update.PropertyKey}");
            }
            var data    = commandId.Split('-');
            var classId = int.Parse(data[0]);
            var index   = int.Parse(data[1]);

            var commands = await NodeDatabase.Shared.GetDeviceCommands(device.NodeId);

            var matchingCommand = commands.FirstOrDefault(x => x.ClassId == classId && x.Index == index);

            if (matchingCommand != null)
            {
                return(matchingCommand);
            }

            //Multi level switches don't have switch state
            if (update.PropertyKey == DevicePropertyKey.SwitchState)
            {
                matchingCommand = commands.FirstOrDefault(x => x.ClassId == 38 && x.Index == 0);
            }
            if (matchingCommand != null)
            {
                return(matchingCommand);
            }
            throw new Exception($"Device doesn't support Command: {update.PropertyKey}");
        }
Exemple #17
0
 public void UpdateDevice(DeviceUpdate update)
 {
     throw new NotImplementedException();
 }
        private void GattDeviceManager_OnDevicesUpdated(Dictionary <string, GattInformation> GattInformationDictionary, DeviceUpdate UpdateType)
        {
            OutString = "";

            switch (UpdateType)
            {
            case DeviceUpdate.Added:
                OutString += "Device Added";
                break;

            case DeviceUpdate.Removed:
                OutString += "Device Removed";
                break;

            case DeviceUpdate.Updated:
                OutString += "Device Updated";
                break;
            }

            OutString += Environment.NewLine + "Devices:" + Environment.NewLine;

            foreach (GattInformation info in GattInformationDictionary.Values)
            {
                OutString += "Name: " + info.Name + " - Paired: " + info.Pairing + " - Can Pair: " + info.CanPair + Environment.NewLine;
            }

            GattInformations = GattInformationDictionary;
            deviceUpdated    = true;
        }
Exemple #19
0
 public static extern ScanStatus PollDevice(ref DeviceUpdate device, bool block);
Exemple #20
0
 public Task <bool> HandleRequest(Device device, DeviceUpdate request)
 {
     throw new NotImplementedException();
 }
 public abstract void UpdateDevice(BasicDevice device, DeviceUpdate update);
Exemple #22
0
 /// <summary>
 /// Called when an update occurs on any device object.
 /// </summary>
 /// <param name="update">a <see cref="DeviceUpdate"/> object containing all devices at the time of the update.</param>
 public NestDeviceEventArgs(DeviceUpdate update)
 {
     this.Data = update;
 }