Example #1
0
        public int DeleteDevice(DeviceDto model)
        {
            Device tblDevice = Mapper.Map <DeviceDto, Device>(model);

            _deviceRepository.DeleteDevice(tblDevice, _dbContext);
            return(_dbContext.SaveChanges());
        }
Example #2
0
        private static DeviceDto Map(Twin twin)
        {
            var deviceDto = new DeviceDto
            {
                DeviceId = twin.DeviceId,

                ConnectionStatus = twin.ConnectionState.ToString(),
                LastActivityTime = twin.LastActivityTime,
                LastUpdateTime   = twin.Properties.Reported.GetMetadata().LastUpdated
            };

            if (twin.Tags.Contains("location"))
            {
                deviceDto.Location = twin.Tags["location"].ToString();
            }

            if (twin.Properties.Reported.Contains("sensor"))
            {
                deviceDto.TemperatureC = float.Parse(twin.Properties.Reported["sensor"]["tempC"].ToString());
                deviceDto.Humidity     = float.Parse(twin.Properties.Reported["sensor"]["humidity"].ToString());
            }

            if (twin.Properties.Reported.Contains("network"))
            {
                deviceDto.Ip   = twin.Properties.Reported["network"]["ip"].ToString();
                deviceDto.Ssid = twin.Properties.Reported["network"]["ssid"].ToString();
                deviceDto.Rssi = twin.Properties.Reported["network"]["rssi"].ToString();
            }

            return(deviceDto);
        }
Example #3
0
 public int Update(DeviceDto prod, int deviceId)
 {
     using (IDbConnection dbConnection = Connection)
     {
         return(dbConnection.Execute(DeviceQueries.Update, new { prod.Name, prod.Description, prod.MacAddress, prod.WarrantyExpiration, prod.InternetUserId, deviceId }));
     }
 }
        /// <summary>
        /// Create the properties for the StateReport
        /// </summary>
        /// <param name="token"></param>
        /// <param name="device"></param>
        /// <returns></returns>
        public override async Task <List <Property> > CreateProperties(string token, DeviceDto device, string port)
        {
            LambdaLogger.Log("Power StateReport");

            List <Property> properties = new List <Property>();

            FieldValueDto value = await GetFieldValue(token, device, "powertState", port);

            if (value != null)
            {
                string stringValue = GetOnOff(value);

                var temperatureProperty = new StringValueProperty
                {
                    Namespace    = "Alexa.PowerController",
                    Name         = "powerState",
                    Value        = stringValue,
                    TimeOfSample = DateTime.UtcNow,
                    UncertaintyInMilliseconds = 600
                };
                properties.Add(temperatureProperty);
            }

            return(properties);
        }
        /// <summary>
        /// 处理分时数据
        /// </summary>
        /// <param name="period">时间间隔</param>
        public static async Task ProcessStatistics(DeviceDto dev, int period = 15)
        {
            var deviceExceptionSet = await _deviceExceptionSetService.GetDeviceExceptionSetByDeviceIdAsny(dev.Serialnum);

            var timeRange        = GetTimeRange(dev.UpdateTime, period);
            var timeSharingDatas = await _deviceTimeSharingStatisticsService.GetDeviceTimeSharingStatisticsByArgsAsny(dev.Serialnum, period, timeRange.Item1, timeRange.Item2);//获取设备分时统计数据

            DeviceTimeSharingStatisticsDto statistics;

            if (timeSharingDatas == null || timeSharingDatas.Count() == 0)
            {
                statistics = new DeviceTimeSharingStatisticsDto
                {
                    DeviceSerialnum = dev.Serialnum,
                    TimeSharing     = period,
                    Count           = 1,
                    StartValue      = dev.ProcessedValue,
                    EndValue        = dev.ProcessedValue,
                    MaxValue        = dev.ProcessedValue,
                    MinValue        = dev.ProcessedValue,
                    AvgValue        = dev.ProcessedValue,
                    CreateTime      = dev.UpdateTime,
                    UpdateTime      = dev.UpdateTime
                };

                if (deviceExceptionSet != null)
                {
                    if (dev.ProcessedValue > deviceExceptionSet.Max || dev.ProcessedValue < deviceExceptionSet.Min)
                    {
                        statistics.ExceptionCount = 1;
                    }
                }
            }
            else
            {
                statistics = timeSharingDatas.ToList()[timeSharingDatas.Count() - 1];
                statistics.Count++;
                statistics.EndValue = dev.ProcessedValue;
                if (dev.ProcessedValue > statistics.MaxValue)
                {
                    statistics.MaxValue = dev.ProcessedValue;
                }
                if (dev.ProcessedValue < statistics.MinValue)
                {
                    statistics.MinValue = dev.ProcessedValue;
                }
                statistics.AvgValue   = (statistics.AvgValue + dev.ProcessedValue) / 2;
                statistics.UpdateTime = dev.UpdateTime;

                if (deviceExceptionSet != null)
                {
                    if (dev.ProcessedValue > deviceExceptionSet.Max || dev.ProcessedValue < deviceExceptionSet.Min)
                    {
                        statistics.ExceptionCount++;
                    }
                }
            }

            await _deviceTimeSharingStatisticsService.AddDeviceTimeSharingStatisticsAsny(statistics);//保存
        }
Example #6
0
        public async Task<ApiResult> Put(DeviceDto deviceUpdate)
        {
            RegistrationDescription registration = null;
            switch (deviceUpdate.Platform)
            {
                case "mpns":
                    registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                    break;
                case "wns":
                    registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                    break;
                case "apns":
                    registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                    break;
                case "gcm":
                    registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                    break;
                default:
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = deviceUpdate.RegistrationId;
            

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet<string>(deviceUpdate.Tags);
       

           
                await _hub.CreateOrUpdateRegistrationAsync(registration);

                return SuccessApiResult(deviceUpdate.RegistrationId);
        }
        public async Task <ActionResult <DeviceDto> > PostDevice(DeviceDto deviceDto)
        {
            Device device = new Device();

            device.Name         = deviceDto.Name;
            device.SerialNumber = deviceDto.SerialNumber;
            device.DeviceType   = Enum.Parse <DeviceType>(deviceDto.DeviceType);

            await _unitOfWork.Devices.AddAsnyc(device);

            try
            {
                await _unitOfWork.SaveChangesAsync();
            }

            /*catch (ValidationException vaildationException)
             * {
             *  ValidationResult validationResult = vaildationException.ValidationResult;
             *  return BadRequest(validationResult.ErrorMessage);
             * }*/
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }

            return(CreatedAtAction("GetDevice", new { id = device.Id }, new DeviceDto(device)));
        }
Example #8
0
        public async Task <DeviceDto> CreateDevice(DeviceDto deviceDto, [FromUri] string dbType)
        {
            Device device      = ConvertDeviceDtoToDevice(deviceDto);
            Device savedDevice = deviceFileService.CreateDevice(device);

            return(ConvertDeviceToDeviceDto(savedDevice));
        }
Example #9
0
        /// <summary>
        /// 新增设备
        /// </summary>
        private void Add()
        {
            // 设备类实体信息
            DeviceDto devDto = new DeviceDto();

            devDto.CabinetNo     = Convert.ToInt16(txtDevNo.Text);
            devDto.CabinetLayers = Convert.ToInt16(txtDevLayers.Text);
            devDto.CabinetCells  = Convert.ToInt16(txtDevCells.Text);

            try
            {
                // 添加设备
                int succeed = CallerFactory.Instance.GetService <ISystemConfigService>().Add(devDto);
                if (succeed != 0)
                {
                    MessageUtil.ShowTips("添加设备信息成功!");

                    // 更新主界面的表格
                    RaiseOnUpdateView(devDto);
                }
                else
                {
                    MessageUtil.ShowTips("添加设备信息失败!");
                }
            }
            catch (Exception ex)
            {
                MessageUtil.ShowError(ex.Message);
            }
        }
Example #10
0
        private void ConfigureData()
        {
            device = new Domain.Device()
            {
                Id          = 1,
                Vendor      = "V1",
                Status      = true,
                DateCreated = DateTime.Today,
                UId         = 1,
                GatewayId   = 1
            };
            deviceDto = new DeviceDto()
            {
                Id          = 1,
                Vendor      = "V1",
                Status      = true,
                DateCreated = DateTime.Today,
                UId         = 1,
                GatewayId   = 1
            };

            mapper = new MapperConfiguration(c => c.AddProfile <AutoMapping>()).CreateMapper();
            deviceRepositoryMock.Get(device.Id).Returns(Task <Domain.Device> .FromResult(device));
            deviceRepositoryMock.Insert(device).Returns(Task <Domain.Device> .FromResult(device));
            deviceRepositoryMock.GetDeviceCount(1).Returns(5);
            deviceRepositoryMock.GetDeviceCount(2).Returns(11);
            deviceRepositoryMock.Delete(device).Returns(Task <Domain.Device> .FromResult(device));
            service = new DeviceService(deviceRepositoryMock, mapper);
        }
Example #11
0
        public static FieldDescriptorDto GetField(this DeviceDto device, string fieldNameOrTag)
        {
            if (device.FieldDescriptors == null)
            {
                return(null);
            }

            foreach (var deviceFieldDescriptor in device.FieldDescriptors)
            {
                // Check tags.
                deviceFieldDescriptor.Tags = deviceFieldDescriptor.Tags ?? new List <string>();
                if (deviceFieldDescriptor.Tags.Any(tag => fieldNameOrTag.Equals(tag, StringComparison.InvariantCultureIgnoreCase)))
                {
                    return(deviceFieldDescriptor);
                }

                // Check field name
                if (fieldNameOrTag.Equals(deviceFieldDescriptor.Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(deviceFieldDescriptor);
                }

                // Check field label
                if (fieldNameOrTag.Equals(deviceFieldDescriptor.Label, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(deviceFieldDescriptor);
                }
            }

            return(null);
        }
        public override async Task <List <Property> > CreateProperties(string token, DeviceDto device, string port)
        {
            LambdaLogger.Log("Get Color property");

            List <Property> properties = new List <Property>();

            FieldValueDto value = await GetFieldValue(token, device, "color", port);

            if (value == null || string.IsNullOrWhiteSpace(value.sv))
            {
                return(properties);
            }

            string[] hsv = value.sv.Split(",", StringSplitOptions.RemoveEmptyEntries);

            if (hsv.Length == 3)
            {
                var temperatureProperty = new ColorValueProperty
                {
                    Namespace = InterfaceNamespace,
                    Name      = "color",
                    Value     = new HsvColor
                    {
                        Hue        = Convert.ToSingle(hsv[0]),
                        Saturation = Convert.ToSingle(hsv[0]),
                        Brightness = Convert.ToSingle(hsv[0]),
                    },
                    TimeOfSample = DateTime.UtcNow,
                    UncertaintyInMilliseconds = 600
                };
                properties.Add(temperatureProperty);
            }

            return(properties);
        }
 public JDownloaderApi(JDownloaderContext context, DeviceDto device, IJDownloaderHttpClient jdownloaderClient)
 {
     DownloadController = new DownloadController(context, device, jdownloaderClient);
     DownloadsV2        = new DownloadsV2(context, device, jdownloaderClient);
     Jd            = new Jd(context, device, jdownloaderClient);
     LinkgrabberV2 = new LinkgrabberV2(context, device, jdownloaderClient);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="token"></param>
        /// <param name="device"></param>
        /// <returns></returns>
        public override async Task <List <Property> > CreateProperties(string token, DeviceDto device, string port)
        {
            LambdaLogger.Log("Temperature StateReport");

            List <Property> properties = new List <Property>();

            FieldValueDto value = await GetFieldValue(token, device, "temperature", port);

            if (value != null && value.v.HasValue)
            {
                var temperatureProperty = new NumericValueWithUnitsProperty
                {
                    Namespace = InterfaceNamespace,
                    Name      = "temperature",
                    Value     = new TemperaturePropertyValue
                    {
                        // TODO: Support °F
                        Scale = "CELSIUS",
                        Value = value.v.Value,
                    },
                    TimeOfSample = DateTime.UtcNow,
                    UncertaintyInMilliseconds = 600
                };
                properties.Add(temperatureProperty);
            }

            return(properties);
        }
Example #15
0
        public HttpResponseMessage Post(HttpRequestMessage request, DeviceDto deviceDto)
        {
            return(CreateHttpResponse(request, () => {
                HttpResponseMessage response = null;

                if (ModelState.IsValid)
                {
                    var device = Mapper.Map <DeviceDto, Device>(deviceDto);
                    if (deviceDto.Id == 0)
                    {
                        this.deviceRepository.Add(device);
                        deviceDto.Id = this.deviceRepository.GetLastInsertId();
                    }
                    else
                    {
                        this.deviceRepository.Edit(device);
                    }
                    this.unitOfWork.Commit();

                    response = request.CreateResponse(HttpStatusCode.OK, new { success = true, id = deviceDto.Id });
                }
                else
                {
                    response = request.CreateResponse(HttpStatusCode.BadRequest, new { success = false });
                }

                return response;
            }));
        }
Example #16
0
        public async Task <IHttpActionResult> PostDevice(device device)
        {
            using (DMSEntities dbContext = new DMSEntities())
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                dbContext.devices.Add(device);
                await dbContext.SaveChangesAsync();

                // New code:
                // Load author name


                var dto = new DeviceDto()
                {
                    device_id    = device.device_id,
                    name         = device.name,
                    manufacturer = device.manufacturer,
                    model        = device.model,
                    OS           = device.OS,
                    OS_version   = device.OS_version,
                    CPU          = device.CPU,
                    RAM          = device.RAM
                };

                return(CreatedAtRoute("DefaultApi", new { id = device.device_id }, dto));
            }
        }
        public IActionResult UpdateDevice(string deviceId, Device updateDevice)
        {
            if (updateDevice == null)
            {
                return(BadRequest(ModelState));
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (deviceId != updateDevice.Id)
            {
                return(BadRequest(ModelState));
            }
            if (!deviceRepository.DeviceExists(deviceId))
            {
                ModelState.AddModelError("", $"Device Type Id {deviceId} no exists");
                return(NotFound(ModelState));
            }
            DeviceDto      device        = deviceRepository.GetDevice(deviceId);
            string         topic         = clientUserRepository.CreateTopic(device.Id, device.Topic);
            ClaimsIdentity claimIdentity = this.User.Identity as ClaimsIdentity;
            string         userId        = claimIdentity.FindFirst(ClaimTypes.Name).Value;
            ClientUser     client        = clientUserRepository.GetClientUser(userId);

            clientUserRepository.UnSubcribeTopic(client.Id, topic);
            clientService.UnsubscribeTopic(topic);
            deviceRepository.UpdateDevice(deviceId, updateDevice);
            string newTopic = clientUserRepository.CreateTopic(updateDevice.Id, updateDevice.Topic);

            clientUserRepository.SubcribeTopic(client.Id, newTopic);
            clientService.SubscribeTopic(newTopic);
            return(Ok("Update Success"));
        }
Example #18
0
        public async Task <Result> AddDevice(DeviceDto device)
        {
            Result result = new Result();

            if ((this._repository as IDeviceRepository).GetDeviceCount(device.GatewayId) >= 10)
            {
                result.AddError("The gateway has reached the devices limit. Please delete a device in order to add a new one");
            }
            else if (device.UId == 0)
            {
                result.AddError("Please, specify a universal id.");
            }
            else if (device.Vendor == null || device.Vendor == "")
            {
                result.AddError("Please, specify a vendor.");
            }
            else if (this._repository.GetAll().Any(x => x.UId == device.UId))
            {
                result.AddError("There is already a device with the specified unversal id");
            }
            else
            {
                try
                {
                    device.DateCreated = DateTime.Today;
                    await this._repository.Insert(_mapper.Map <Device>(device));
                }
                catch (System.Exception)
                {
                    result.AddError("Unexpected error adding a device");
                }
            }
            return(result);
        }
Example #19
0
 /// <summary>
 /// https://developer.amazon.com/docs/device-apis/alexa-thermostatcontroller.html
 /// </summary>
 /// <param name="capability"></param>
 /// <param name="device"></param>
 private void PopulateThermostatControllerCapability(Capability capability, DeviceDto device, string port)
 {
     PopulatePropertyIfSupported(capability, device, "lowerSetpoint", port);
     PopulatePropertyIfSupported(capability, device, "targetSetpoint", port);
     PopulatePropertyIfSupported(capability, device, "upperSetpoint", port);
     PopulatePropertyIfSupported(capability, device, "thermostatMode", port);
 }
Example #20
0
 public int Add(DeviceDto prod)
 {
     using (IDbConnection dbConnection = Connection)
     {
         return(dbConnection.Execute(DeviceQueries.Add, prod));
     }
 }
Example #21
0
        public DeviceDto GetDevice(string deviceId)
        {
            var device = devices.AsQueryable().Where(device => device.Id == deviceId)
                         .Select(device => new
            {
                device.Id,
                device.Name,
                device.DeviceTypeId,
                device.ConnectedDeviceId,
                device.DeviceStatus,
                device.GPIO,
                device.Topic
            }).FirstOrDefault();
            DeviceDto deviceDto = new DeviceDto
            {
                Id                = device.Id,
                DeviceTypeId      = device.DeviceTypeId,
                Name              = device.Name,
                GPIO              = device.GPIO,
                DeviceStatus      = device.DeviceStatus,
                ConnectedDeviceId = device.ConnectedDeviceId,
                Topic             = device.Topic,
            };

            deviceDto.DeviceStatus.LastConnected.ToLocalTime();
            deviceDto.DeviceStatus.LastDisconnected.ToLocalTime();
            return(deviceDto);
        }
        public async Task SetPercentage_ForMultiPortDevice_TurnOn_Port1_SendsTurnOnPort1()
        {
            // Arrange
            string messageId = "Message12";
            var    device    = new DeviceDto {
                Id = "Endpoint1"
            };
            var deviceAndPort = new DeviceAndPort(device, 1);
            var request       = BuildRequest(messageId, "SetPercentage", deviceAndPort.ToString());

            List <DeviceDto> devices = new List <DeviceDto>
            {
                new DeviceDto
                {
                    DisplayName = "Device 1"
                }
            };

            var devicesClient      = new FakeDevicesClient(devices);
            var measurementsClient = new FakeMeasurementsClient();
            var statusClient       = new FakeStatusClient();

            var controller = new PercentageController(devicesClient, measurementsClient, statusClient);

            // Act
            PowerControlResponse response = (PowerControlResponse)await controller.HandleAlexaRequest(request, null);

            // Assert
            Assert.IsNotNull(response);
            Assert.AreEqual("@Switch Set percentage 110 port-1", statusClient.SentMessage);
        }
Example #23
0
        public void TryCreateDeviceUnderOtherNetworkTest()
        {
            var environmentFactory    = EnvironmentFactoryFactory.Create();
            var authenticationContext = Substitute.For <IAuthenticationContext>();
            var messagingService      = Substitute.For <IMessagingServiceClient>();

            var userOperations    = environmentFactory.ManagementEnvironment.MgmtUserOperations;
            var companyOperations = environmentFactory.ManagementEnvironment.MgmtCompanyOperations;
            var settingProvider   = new SettingProvider(environmentFactory.ManagementEnvironment.MgmtSettingOperations);

            var userService = new UserService(userOperations, authenticationContext, settingProvider, null);
            var userId1     =
                userService.Register(new RegisterDto()
            {
                Name = "user", Email = EmailHelper.Generate(), Password = "******"
            }, null);

            var companyService = new CompanyService(companyOperations, authenticationContext, null, new CapabilityProvider(settingProvider));

            authenticationContext.GetContextUser().Returns(userId1);

            var companyId1 = companyService.Create("new company1");

            var serviceOperations = environmentFactory.ManagementEnvironment.MgmtServiceOperations;
            var serviceService    = new ServiceService(serviceOperations, companyOperations, authenticationContext, null, new CapabilityProvider(settingProvider));

            var serviceId1 = serviceService.Create(new ServiceDto()
            {
                CompanyId = companyId1, Name = "svc"
            });

            var companyId2 = companyService.Create("new company2");

            var serviceId2 = serviceService.Create(new ServiceDto()
            {
                CompanyId = companyId2, Name = "svc"
            });

            var networkOperations = environmentFactory.ManagementEnvironment.MgmtNetworkOperations;
            var networkService    = new NetworkService(networkOperations, serviceOperations, companyOperations, authenticationContext, null);

            var deviceOperations = environmentFactory.ManagementEnvironment.MgmtDeviceOperations;
            var deviceService    = new DeviceService(deviceOperations, networkOperations, serviceOperations, companyOperations, authenticationContext, messagingService);

            var networkId2 = networkService.Create(new NetworkDto()
            {
                ServiceId = serviceId2, CompanyId = companyId2, Name = "svc"
            });

            var device = new DeviceDto()
            {
                NetworkId = networkId2,
                CompanyId = companyId1,
                ServiceId = serviceId1,
                Name      = "test"
            };

            deviceService.Create(device);
        }
        public async Task <DeviceDto> GetDeviceById(int id)
        {
            var device = await deviceManager.GetDeviceById(id);

            DeviceDto output = objectMapper.Map <ManageCloudDevices.Models.Device, DeviceDto>(device);

            return(output);
        }
Example #25
0
 public async Task <IActionResult> Get([FromQuery] DeviceDto param)
 {
     if (await _fCMService.CheckDevice(param.EmpId, param.DeviceId))
     {
         return(StatusCode(201));
     }
     return(BadRequest());
 }
Example #26
0
 public bool Add(DeviceDto device)
 {
     if (_deviceRepository.Add(device) != 0)
     {
         return(true);
     }
     return(false);
 }
Example #27
0
 public UsageDto(Usage usage)
 {
     Id     = usage.Id;
     From   = usage.From;
     To     = usage.To;
     Person = new PersonDto(usage.Person);
     Device = new DeviceDto(usage.Device);
 }
Example #28
0
        public ActionResult Edit(DeviceDto model)
        {
            GetDeviceType(); GetUser(); GetRoom(); GetDevices();
            ResultHelper result = JsonConvert.DeserializeObject <ResultHelper>(deviceService.SetDevice(model));

            ViewBag.Message = Helper.GetResultMessage(result.Result, result.ResultDescription);
            return(View());
        }
Example #29
0
 public bool Update(DeviceDto device, int deviceId)
 {
     if (_deviceRepository.Update(device, deviceId) != 0)
     {
         return(true);
     }
     return(false);
 }
Example #30
0
        /// <summary>
        /// 通知UI界面更新表格
        /// </summary>
        /// <param name="deviceDto">UI界面表格显示的设备实体信息</param>
        private void RaiseOnUpdateView(DeviceDto deviceDto)
        {
            if (OnUpdateView == null)
            {
                return;
            }

            OnUpdateView(deviceDto);
        }
        public void Can_Start_VideoAnalytics()
        {
            DeviceDto cameraDevice =
                __controllerService.GetCameraDeviceByGuid(Guid.Parse("{ff0e79c3-9a33-47f5-9552-223a69a22bbe}"));

            NvrCameraDto nvrCameraDto = cameraDevice as NvrCameraDto;
            AnalyticsEventTemplateDto analyticsEventTemplateDto =
                _systemService.GetAnalyticsEventTemplate(nvrCameraDto.AnalyticsEventTemplateId.Value);
        }
        public async Task SaveAsync(string gatewayName, DeviceBase device)
        {
            var properties = GetProperties(device);

            var dto = new DeviceDto
            {
                Gateway = gatewayName,
                Id = $"{gatewayName}.{device.Id}",
                Name = device.Name,
                Properties = JsonConvert.SerializeObject(properties)
            };

            using (var database = new Database("ConnectionString"))
            {
                var result = await database.UpdateAsync("Device", "Id", dto, dto.Id, new[] {"Gateway", "Name", "Properties"});

                if (result == 1)
                {
                    return;
                }

                await database.InsertAsync("Device", "Id", false, dto);
            }
        }