예제 #1
0
		public void SetDeviceState(SetDeviceStateData setDeviceStateData) {
			var device = UserDeviceService.GetBySecretKey(setDeviceStateData.SecretKey);

			if (device != null) {
				DeviceHistoricalState deviceHistoricalState = new DeviceHistoricalState() {
					State = device.ActualState,
					StateTransitionDateTime = DateTime.Now,
					DeviceId = device.Id
				};

				UserDeviceService.SetupFreshLastPing(device);
				if (UserDeviceService.UpdateDeviceState(device, setDeviceStateData.DeviceState)) {
					var historialStateES = new EntityService<DeviceHistoricalState>();
					historialStateES.Create(deviceHistoricalState);
				}

				IKernel kernel = new StandardKernel(new ConnectYourselfNinjectModule());
				var deviceEventsContainer = kernel.Get<IDevicesEventsContainer>();

				deviceEventsContainer.RegisterDeviceStateChangeEvent(new DeviceStateChangedEvent {
					DeviceId = device.Id,
					DateTime = deviceHistoricalState.StateTransitionDateTime,
					State = setDeviceStateData.DeviceState,
					AppUserId = device.AppUserId
				});
			}
		}
		public IHttpActionResult SetDeviceState(SetDeviceStateData setDeviceStateData) {
			var userId = User.Identity.GetUserId();
			UserDeviceService userDeviceService = new UserDeviceService();

			if (setDeviceStateData == null) {
				return BadRequest("Input is null");
			}

			var device = userDeviceService.GetBySecretKey(setDeviceStateData.SecretKey);

			if (device != null) {
				DeviceHistoricalState deviceHistoricalState = new DeviceHistoricalState() {
					State = device.ActualState,
					StateTransitionDateTime = DateTime.Now,
					DeviceId = device.Id
				};

				if (userDeviceService.UpdateDeviceState(device, setDeviceStateData.DeviceState)) {
					var historialStateES = new EntityService<DeviceHistoricalState>();
					historialStateES.Create(deviceHistoricalState);

					IKernel kernel = new StandardKernel(new ConnectYourselfNinjectModule());
					var deviceEventsContainer = kernel.Get<IDevicesEventsContainer>();

					deviceEventsContainer.RegisterDeviceStateChangeEvent(new DeviceStateChangedEvent {
						DeviceId = device.Id,
						DateTime = deviceHistoricalState.StateTransitionDateTime,
						State = setDeviceStateData.DeviceState,
						AppUserId = device.AppUserId
					});

					//send state change message to device
					if (device.ConnectionState == DeviveConnectionState.FullDuplex && !String.IsNullOrEmpty(device.ConnectionId)) {
						var devicesHub = GlobalHost.ConnectionManager.GetHubContext<DevicesHub>();
						devicesHub.Clients.Client(device.ConnectionId).RemoteSetState(setDeviceStateData.DeviceState);
					}

					return Ok();
				} else {
					return BadRequest("Failed to update state device");
				}
			} else {
				return BadRequest("Device does not exists");
			}
		}