private HealthStatusEnum AnalysisMotorStatus(DeviceDetail model)
        {
            HealthStatusEnum result       = HealthStatusEnum.Unknown;
            DeviceDetail     deviceDetail = model;

            if (deviceDetail.UpMotor && deviceDetail.DownMotor && deviceDetail.StopMotor)
            {
                result = HealthStatusEnum.Normal;
            }
            else
            {
                result = HealthStatusEnum.Error;

                deviceDetail.MotorAdvice = "电机操作异常,无法正常运行。";

                if (!deviceDetail.UpMotor)
                {
                    deviceDetail.MotorAdvice += "上升电机操作失败。";
                }

                if (!deviceDetail.DownMotor)
                {
                    deviceDetail.MotorAdvice += "下降电机操作失败。";
                }

                if (!deviceDetail.StopMotor)
                {
                    deviceDetail.MotorAdvice += "停止电机操作失败。";
                }
            }

            return(result);
        }
Example #2
0
 public void MapToDeviceDetail(DeviceDetail deviceDetail, LinkDeviceModel linkDeviceModel)
 {
     deviceDetail.DeviceName     = linkDeviceModel.DeviceName;
     deviceDetail.LinkedUserId   = linkDeviceModel.UserId;
     deviceDetail.ModifiedUserId = linkDeviceModel.UserId;
     deviceDetail.ModifiedDate   = DateTime.Now;
 }
        private HealthStatusEnum AnalysisValveStatus(DeviceDetail model)
        {
            HealthStatusEnum result       = HealthStatusEnum.Unknown;
            DeviceDetail     deviceDetail = model;

            if (deviceDetail.OpenValve && deviceDetail.CloseValve && deviceDetail.AutoValve)
            {
                result = HealthStatusEnum.Normal;
            }
            else
            {
                result = HealthStatusEnum.Error;

                deviceDetail.ValveAdvice = "阀门操作异常,无法正常运行。";

                if (!deviceDetail.OpenValve)
                {
                    deviceDetail.ValveAdvice += "打开阀门操作失败。";
                }

                if (!deviceDetail.CloseValve)
                {
                    deviceDetail.ValveAdvice += "关闭阀门操作失败。";
                }

                if (!deviceDetail.AutoValve)
                {
                    deviceDetail.ValveAdvice += "自动控制阀门操作失败。";
                }
            }

            return(result);
        }
Example #4
0
        public void UpdateDevice(int id, DeviceDetail device)
        {
            var newDevice = _db.DeviceDetails.FirstOrDefault(d => d.Basic.GsmArenaNumber == id);

            _db.Entry(newDevice).CurrentValues.SetValues(device);
            _db.SaveChanges();
        }
Example #5
0
        private async Task <DeviceDetailModel> UpdateDevice(DeviceDetail deviceDetail, LinkDeviceModel linkDeviceModel)
        {
            deviceDetailMapper.MapToDeviceDetail(deviceDetail, linkDeviceModel);
            unitOfWork.DeviceDetail.Update(deviceDetail);

            unitOfWork.Save();

            return(await GetDevice(linkDeviceModel.EmailAddress));
        }
Example #6
0
 public DeviceDetailModel MapToDeviceDetailModel(DeviceDetail deviceDetail)
 {
     return(new DeviceDetailModel()
     {
         Id = deviceDetail.Id,
         DeviceName = deviceDetail.DeviceName,
         SerailNumber = deviceDetail.SerailNumber,
         LinkedUserId = deviceDetail.LinkedUserId,
         // LinkedUserName = deviceDetail.LinkedUser == null ? "" :  `${ deviceDetail.LinkedUser.Firstname} ${ deviceDetail.LinkedUser.LastName}`,
     });
 }
        /// <summary>
        /// 查询网关下所有设备
        /// </summary>
        /// <param name="gatewayid">该用户所选网关的id值</param>
        /// <returns></returns>
        public ActionResult SelControlPanel(int gatewayid)
        {
            db.Configuration.LazyLoadingEnabled   = false;
            db.Configuration.ProxyCreationEnabled = false;
            var           data = db.iot_control_panel.Where(c => c.GateWayID == gatewayid).GroupBy(c => c.Uid);
            List <Device> list = new List <Device>();

            if (data != null)
            {
                foreach (var item in data.ToList())
                {
                    foreach (var row in item)
                    {
                        if (row.ParentID == 0)
                        {
                            Device model  = new Device();
                            var    cpanel = db.iot_control_panel.Where(c => c.ParentID == row.ID);
                            model.ID        = row.ID;
                            model.GateWayID = row.GateWayID;
                            model.KeyNumber = row.KeyNumber;
                            model.Name      = row.Name;
                            model.Position  = row.Position;
                            model.Uid       = row.Uid;

                            List <DeviceDetail> dlist = new List <DeviceDetail>();
                            foreach (var rowname in cpanel)
                            {
                                DeviceDetail detail = new DeviceDetail
                                {
                                    ID   = rowname.ID,
                                    Name = rowname.Name
                                };
                                dlist.Add(detail);
                            }
                            model.list = dlist;
                            list.Add(model);
                        }
                        if (row.ParentID == -1)
                        {
                            Device model  = new Device();
                            var    cpanel = db.iot_control_panel.Where(c => c.ParentID == row.ID);
                            model.ID        = row.ID;
                            model.GateWayID = row.GateWayID;
                            model.KeyNumber = row.KeyNumber;
                            model.Name      = row.Name;
                            model.Position  = row.Position;
                            model.Uid       = row.Uid;
                            list.Add(model);
                        }
                    }
                }
            }
            return(Json(list, JsonRequestBehavior.AllowGet));
        }
Example #8
0
        public void MapToDeviceDetailModel(DeviceDetailModel deviceDetailModel, DeviceDetail deviceDetail)
        {
            if (deviceDetail == null)
            {
                return;
            }

            deviceDetailModel.Id           = deviceDetail.Id;
            deviceDetailModel.DeviceName   = deviceDetail.DeviceName;
            deviceDetailModel.LinkedUserId = deviceDetail.LinkedUserId;
        }
Example #9
0
        public IActionResult InsertDeviceDetail([FromBody] InsertDeviceDetailRequestDTO dto)
        {
            InsertDeviceDetailResponse response = new InsertDeviceDetailResponse();
            Device device = GetDevice(dto.DeviceId);

            if (device == null)
            {
                return(NotFound(response));
            }

            var pins = uow.Pin.GetAvailablePins(dto.DeviceId, device.DeviceTypeId);

            if (!pins.Success)
            {
                return(NotFound(response));
            }

            if (!pins.Data.Any(f => f.Id == dto.PinId))
            {
                return(NotFound(response));
            }

            var sensor = uow.Sensor.GetSensor(dto.SensorId);

            if (!sensor.Success)
            {
                return(NotFound(response, sensor.Message));
            }

            var deviceDetail = new DeviceDetail()
            {
                DeviceId    = device.Id,
                SensorId    = sensor.Data.Id,
                PinId       = dto.PinId,
                Description = dto.Description
            };
            var result = uow.DeviceDetail.Insert(deviceDetail);

            if (!result.Success)
            {
                return(NotFound(response, result.Message));
            }

            if (!uow.Commit())
            {
                return(NotFound(response));
            }

            response.Id = deviceDetail.Id;

            return(Ok(response));
        }
Example #10
0
        /// <summary>
        /// Обрабатывает добавление новых устройств для этой группа устройств
        /// </summary>
        /// <typeparam name="T">Тип добавляемых устройств</typeparam>
        private void AddDeviceDetail <T>() where T : DeviceDetail
        {
            // вначале создать устройство
            DeviceDetail device = unitOfWork.CreateObject <T>();

            unitOfWork.AddParameterDetail(Model, device);

            // затем сконструировать модель просмотра
            DeviceDetaillViewModel vm = DeviceDetaillViewModel.BuildViewModel(device);

            DeviceDetaills.Add(vm);
            CurrentDeviceDetail = vm;
        }
        private HealthStatusEnum AnalysisPumpStatus(DeviceDetail model)
        {
            HealthStatusEnum result       = HealthStatusEnum.Normal;
            DeviceDetail     deviceDetail = model;

            if ((DateTime.Now - deviceDetail.LastChangeOilTime).TotalHours > deviceDetail.ChangOilTime)
            {
                result = HealthStatusEnum.Warning;

                deviceDetail.PumpAdvice = "距离上次更换泵油时间过长,建议更换泵油。";
            }

            return(result);
        }
        private void SaveDeviceDetail(DeviceEditViewModel model, string guid)
        {
            foreach (var log in model.Logs)
            {
                Stream stream = log.OpenReadStream();
                using (StreamReader reader = new StreamReader(stream))
                {
                    string strxml = reader.ReadToEnd();

                    DeviceDetail deviceDetail = HelperXML.DESerializer <DeviceDetail>(strxml);
                    deviceDetail.DeviceGUID = guid;

                    _deviceRepository.AddDetail(deviceDetail);
                }
            }
        }
Example #13
0
        /// <summary>
        /// Конструирует модель просмотра для представления предоставленных данных DeviceDetaill
        /// </summary>
        /// <param name="device">Данные, для которых должны быть сконструирована модель ViewModel</param>
        /// <returns>Сконструированная модель ViewModel или null, если она не может быть построена</returns>
        public static DeviceDetaillViewModel BuildViewModel(DeviceDetail device)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

            DeviceBRS1M tuning = device as DeviceBRS1M;

            if (tuning != null)
            {
                return(new DeviceBRS1MViewModel(tuning));
            }

            return(null);
        }
Example #14
0
        public InteractiveLogon(
            DeviceDetail deviceDetail,
            SignInLocation location,
            string userId,
            DateTime creationDateTime,
            string userDisplayName)
        {
            DeviceDetail      = deviceDetail;
            DeviceId          = deviceDetail.DeviceId;
            DeviceDisplayName = deviceDetail.DisplayName;

            Location         = location;
            UserId           = userId;
            UserDisplayName  = userDisplayName.ToUpper();
            CreationDateTime = creationDateTime;
        }
        private void CreatShowData(DeviceDetail device)
        {
            device = new DeviceDetail
            {
                //气密性
                LowPressStartP  = 10,
                LowPressEndP    = 20,
                LowPressDuring  = 2,
                HighPressStartP = 20000,
                HighPressDuring = 10,
                HighPressEndP   = 21000,

                //传感器
                VacuumPress      = 2,
                AirPress         = 10001,
                StandardAirPress = 10000,
                AirPressMax      = 10010,
                AirPressMin      = 9960,

                //阀门
                OpenValve  = true,
                CloseValve = true,
                AutoValve  = true,

                //真空泵
                UseDuring         = 3100,
                LastChangeOilTime = DateTime.Now,
                ChangOilTime      = 3000,

                //电机
                UpMotor    = true,
                DownMotor  = true,
                StopMotor  = true,
                UpDuring   = 30,
                DownDuring = 35,

                //加热炉
                StartStove      = true,
                StopStove       = true,
                HoldStove       = true,
                StoveTempMax    = 310,
                StoveTempMin    = 290,
                StandardAirTemp = 30,
                StoveAirTemp    = 31,
            };
        }
        public ViewResult Analysis(int id)
        {
            Device device = _deviceRepository.GetDevice(id);

            List <DeviceDetail> deviceDetails = _deviceRepository.GetDeviceDetails(device.GUID);

            DeviceDetail deviceDetail = new DeviceDetail();

            if (deviceDetails != null && deviceDetails.Count > 0)
            {
                deviceDetail = deviceDetails.OrderBy(c => c.CheckTime).Last();
            }
            else
            {
                CreatShowData(deviceDetail);
            }


            if (device != null)
            {
                DeviceAnalysisViewModel deviceAnalysisViewModel = new DeviceAnalysisViewModel
                {
                    Id = device.Id,
                    //分析气密性
                    GasStatus = ConvertStatus(AnalysisGasStatus(deviceDetail)),
                    //分析传感器
                    SensorStatus = ConvertStatus(AnalysisSensorStatus(deviceDetail)),
                    //分析阀门
                    ValueStatus = ConvertStatus(AnalysisValveStatus(deviceDetail)),
                    //分析真空泵
                    PumpStatus = ConvertStatus(AnalysisPumpStatus(deviceDetail)),
                    //分析升降电机
                    MotorStatus = ConvertStatus(AnalysisMotorStatus(deviceDetail)),
                    //分析加热炉
                    StoveStatus = ConvertStatus(AnalysisStoveStatus(deviceDetail)),
                };
                //分析总体健康
                deviceAnalysisViewModel.DeviceStatus = ConvertStatus(AnalysisDeviceStatus(deviceAnalysisViewModel));
                //得出健康建议
                deviceAnalysisViewModel.DeviceAdvice = AnalysisDeviceAdvice(deviceDetail);

                return(View(deviceAnalysisViewModel));
            }

            throw new Exception("查询不到这个设备信息");
        }
Example #17
0
        /// <summary>
        /// Регистрирует добавление новых устройств
        /// </summary>
        /// <param name="part">Группа устройств, для которого добавляются параметр</param>
        /// <param name="device">Добавляемое устройство</param>
        /// <exception cref="InvalidOperationException">Инициируется, если группа устройств не отслеживается этим UnitOfWork</exception>
        /// <exception cref="InvalidOperationException">Инициируется, если устройство уже добавлен в UnitOfWork</exception>
        public void AddParameterDetail(Part part, DeviceDetail device)
        {
            if (part == null)
            {
                throw new ArgumentNullException(nameof(part));
            }

            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

            CheckEntityDoesNotBelongToUnitOfWork(device);
            CheckEntityBelongsToUnitOfWork(part);

            underlyingContext.DeviceDetails.AddObject(device);
            part.DeviceDetails.Add(device);
            part.IsDirty = true;
        }
        private string AnalysisDeviceAdvice(DeviceDetail model)
        {
            StringBuilder result = new StringBuilder();

            result.Append(model.GasAdvice);
            result.Append(model.SenorAdvice);
            result.Append(model.ValveAdvice);
            result.Append(model.PumpAdvice);
            result.Append(model.MotorAdvice);
            result.Append(model.StoveAdvice);

            if (result.Length > 0)
            {
                result.Append("建议尽早联系售后人员进行检查");
            }

            //result.Append("     该设备整体健康状态良好,可以正常工作。但是气密性相较之前变差,处于不影响测试的边缘,建议尽早联系售后人员进行检查;而真空泵也长时间未更换泵油,建议更换泵油。");

            return(result.ToString());
        }
Example #19
0
        public void Add(Guid accountId, string deviceToken, PushNotificationServicePlatform platform)
        {
            using (var context = _contextFactory.Invoke())
            {
                var devices = context.Set <DeviceDetail>().Where(d => d.DeviceToken == deviceToken);

                context.Set <DeviceDetail>().RemoveRange(devices.Where(d => d.AccountId != accountId));

                if (devices.None(d => d.AccountId == accountId))
                {
                    var device = new DeviceDetail
                    {
                        AccountId   = accountId,
                        DeviceToken = deviceToken,
                        Platform    = platform
                    };
                    context.Set <DeviceDetail>().Add(device);
                }

                context.SaveChanges();
            }
        }
        private HealthStatusEnum AnalysisStoveStatus(DeviceDetail model)
        {
            HealthStatusEnum result       = HealthStatusEnum.Unknown;
            DeviceDetail     deviceDetail = model;

            double tempDiff = deviceDetail.StoveTempMax - deviceDetail.StoveTempMin;

            if (deviceDetail.StartStove && deviceDetail.StopStove && deviceDetail.HoldStove && tempDiff <= DIFFERENTTEMP)
            {
                result = HealthStatusEnum.Normal;
            }
            else if (!deviceDetail.StartStove || !deviceDetail.StopStove || !deviceDetail.HoldStove)
            {
                result = HealthStatusEnum.Error;
                deviceDetail.StoveAdvice = "加热炉操作异常,无法正常运行。";

                if (!deviceDetail.StartStove)
                {
                    deviceDetail.StoveAdvice += "开始加热操作失败。";
                }

                if (!deviceDetail.StopStove)
                {
                    deviceDetail.StoveAdvice += "停止加热操作失败。";
                }

                if (!deviceDetail.HoldStove)
                {
                    deviceDetail.StoveAdvice += "保持温度操作失败。";
                }
            }
            else
            {
                result = HealthStatusEnum.Warning;
                deviceDetail.StoveAdvice = "加热炉保持温度稳定性较差,会影响测试结果。";
            }

            return(result);
        }
        private HealthStatusEnum AnalysisSensorStatus(DeviceDetail model)
        {
            HealthStatusEnum result       = HealthStatusEnum.Unknown;
            DeviceDetail     deviceDetail = model;

            //真空压力差值
            double vacuumDiff = Math.Abs(deviceDetail.VacuumPress);
            //常压压力差值
            double airDiff = Math.Abs(deviceDetail.AirPress - deviceDetail.StandardAirPress);
            //稳定度
            double stableDiff = deviceDetail.AirPressMax - deviceDetail.AirPressMin;

            if (vacuumDiff <= DIFFERENTPRESS && airDiff <= DIFFERENTPRESS && stableDiff <= STABLEPRESS)
            {
                result = HealthStatusEnum.Normal;
            }
            else
            {
                result = HealthStatusEnum.Warning;

                if (vacuumDiff > LOWGASNORMAL)
                {
                    deviceDetail.SenorAdvice = "真空条件下读数不准确。";
                }

                if (airDiff > HIGHGASWARINGL)
                {
                    deviceDetail.SenorAdvice += "常压条件下读数不准确。";
                }

                if (stableDiff > STABLEPRESS)
                {
                    deviceDetail.SenorAdvice += "读数稳定性较差。";
                }
            }

            return(result);
        }
Example #22
0
        /// <summary>
        /// Регистрирует удаление существующих параметров
        /// </summary>
        /// <param name="part">группа устройств, чьи параметры удаляются</param>
        /// <param name="device">Удаляемое устройство</param>
        /// <exception cref="InvalidOperationException">Инициируется, если группа устройств не отслеживается этим UnitOfWork</exception>
        /// <exception cref="InvalidOperationException">Инициируется, если устройства не отслеживаются этим UnitOfWork</exception>
        public void RemoveParameterDetail(Part part, DeviceDetail device)
        {
            if (part == null)
            {
                throw new ArgumentNullException(nameof(part));
            }

            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

            CheckEntityBelongsToUnitOfWork(device);
            CheckEntityBelongsToUnitOfWork(part);
            if (!part.DeviceDetails.Contains(device))
            {
                throw new InvalidOperationException("Представленный DeviceDetail не относятся к поставленной группе устройств.");
            }

            part.DeviceDetails.Remove(device);
            underlyingContext.DeviceDetails.DeleteObject(device);
            part.IsDirty = true;
        }
        private HealthStatusEnum AnalysisGasStatus(DeviceDetail model)
        {
            HealthStatusEnum result       = HealthStatusEnum.Unknown;
            DeviceDetail     deviceDetail = model;

            //低压气密性
            double lowGas = (deviceDetail.LowPressEndP - deviceDetail.LowPressStartP) / deviceDetail.LowPressDuring;

            //高压气密性
            double highGas = (deviceDetail.HighPressEndP - deviceDetail.HighPressStartP) / deviceDetail.HighPressDuring;

            if (lowGas <= LOWGASNORMAL && highGas <= HIGHGASNORMAL)
            {
                result = HealthStatusEnum.Normal;
            }
            else if (lowGas > LOWGASWARING || highGas > HIGHGASWARINGL)
            {
                result = HealthStatusEnum.Error;
                deviceDetail.GasAdvice = "气密性异常,会造成测试不准确。";
            }
            else
            {
                result = HealthStatusEnum.Warning;

                if (lowGas <= LOWGASNORMAL)
                {
                    deviceDetail.GasAdvice = "低压气密性较差。";
                }

                if (highGas <= HIGHGASWARINGL)
                {
                    deviceDetail.GasAdvice += "高压气密性较差。";
                }
            }

            return(result);
        }
Example #24
0
        public ActionResult Edit(int id, FormCollection collection, DeviceRequest request)    ///分配????
        {
            var orderInfoorderData1 = this.IDKLManagerService.SelectDeviceOrderDetail(id);

            string str       = orderInfoorderData1.ProjectNumber;
            var    orderInfo = this.IDKLManagerService.GetDeviceOrderInfoByProjectNumberAndCreateTime(str, orderInfoorderData1.CreateTime);

            orderInfo.OrderState = (int)EnumOrderStateInfo.OrderSucceed;
            this.IDKLManagerService.UpdateDeviceOrderInfo(orderInfo);
            orderInfo.DeviceName            = orderInfoorderData1.DeviceName;
            orderInfoorderData1.OrderPerson = orderInfo.OrderPerson;
            //  orderInfo.ID = orderInfoorderData1.ID;
            //orderInfo.OrderState = (int)EnumOrderStateInfo.OrderSucceed;
            var    orderData = this.IDKLManagerService.GetDeviceOrderDetaislList(id);
            string t1        = collection["textbox"];
            string num       = t1.Substring(0, t1.Length);

            orderInfo.DeviceNumber = num;
            string N = collection["Number"];

            N = N.Replace(",", "");
            List <string> DeviceNumber = t1.Substring(0, t1.Length - Convert.ToInt32(N)).Split(new char[] { ',' }).ToList();

            orderData.RealityOrderNumber = Convert.ToInt32(N);
            if (orderData.RealityOrderNumber <= orderData.OrderNumber)
            {
                try
                {
                    this.IDKLManagerService.UpdateDeviceOrderDetail(orderData);
                }
                catch (Exception ex)
                {
                    return(Back(ex.Message));
                }
            }
            else
            {
                return(Back("实际数不能大于预约数"));
            }
            DeviceDetail model = new DeviceDetail();

            foreach (var item in DeviceNumber)
            {
                if (item == "" || item == null)
                {
                    model.DeviceNumber = item;///
                    model.OrderTime    = orderData.OrderDate;
                    try
                    {
                        this.IDKLManagerService.AddDeviceDetail(model);
                    }
                    catch (Exception ex)
                    {
                        return(Back(ex.Message));
                    }
                }
            }

            orderInfo.RealityOrderNumber = orderData.RealityOrderNumber;
            try
            {
                if (orderInfo.ProjectNumber == null || orderInfo.ProjectNumber == "")
                {
                    orderInfo.OrderState = (int)EnumOrderStateInfo.AddState;
                }

                this.IDKLManagerService.AddDeviceOrderInfo(orderInfo);
            }

            catch (Exception ex)
            {
                return(Back(ex.Message));
            }
            return(this.RefreshParent());
        }
Example #25
0
        public ActionResult GetCompanyByIDForJson(int id, [DefaultValue(0)] int licID, [DefaultValue(0)] int devID, string identifier, string lang, string status)
        {
            var companyController    = new CompanyController();
            var licenceController    = new LicenceController();
            var deviceController     = new DeviceController();
            var identifierController = new DeviceIdentifierController();
            var licencestatus        = status;

            var data = new CompanyDetail();

            data.licenceList = new List <LicenceDetail>();

            //1. Get Company
            var company = new Company();

            company = companyController.GetCompanyById(id, status);
            if (company != null && company.company_id > 0)
            {
                data.company_id      = company.company_id;
                data.company_name    = company.company_name;
                data.company_address = UtilityHelper.BuildAddress(company);

                var licenceList = new List <Licence>();
                if (devID > 0)
                {
                    //2.Get Device.
                    var device       = deviceController.GetDeviceById(devID);
                    var deviceDetail = new DeviceDetail();
                    //var archivedDeviceDetails = new DeviceDetail();
                    deviceDetail.device = device;
                    deviceDetail.deviceIdentifierList = new List <DeviceIdentifier>();
                    var identifierList = new List <DeviceIdentifier>();

                    //3. Get DeviceIdentifier
                    if (licID > 0)
                    {
                        identifierList = identifierController.GetAllDeviceIdentifier(licencestatus, "", licID, device.device_id).ToList();
                    }
                    else
                    {
                        identifierList = identifierController.GetAllDeviceIdentifier(licencestatus, "", 0, device.device_id).ToList();
                    }

                    if (identifierList != null && identifierList.Count > 0)
                    {
                        if (string.IsNullOrWhiteSpace(identifier.Trim()))
                        {
                            deviceDetail.deviceIdentifierList = identifierList;
                        }
                        else
                        {
                            deviceDetail.deviceIdentifierList = identifierList.Where(s => s.device_identifier == identifier).ToList();
                        }
                    }

                    //4. Get Licence

                    var licenceDetail         = new LicenceDetail();
                    var archivedLicenceDetail = new LicenceDetail();
                    if (licencestatus == "active")
                    {
                        if (licID > 0)
                        {
                            licenceDetail.licence = licenceController.GetLicenceById(licID, "active");
                        }
                        else
                        {
                            licenceDetail.licence = licenceController.GetLicenceById(device.original_licence_no, "active");
                        }
                        licenceDetail.deviceList = new List <DeviceDetail>();
                        licenceDetail.deviceList.Add(deviceDetail);
                        data.licenceList.Add(licenceDetail);
                    }
                    else
                    {
                        if (licID > 0)
                        {
                            archivedLicenceDetail.licence = licenceController.GetLicenceById(licID, "archived");
                        }
                        else
                        {
                            archivedLicenceDetail.licence = licenceController.GetLicenceById(device.original_licence_no, "archived");
                        }

                        archivedLicenceDetail.deviceList = new List <DeviceDetail>();
                        archivedLicenceDetail.deviceList.Add(deviceDetail);

                        //5. Add all the list to Company(data).

                        data.licenceList.Add(archivedLicenceDetail);
                    }
                }
                else
                {
                    if (licencestatus == "active")
                    {
                        if (licID == 0)
                        {
                            licenceList = licenceController.GetAllLicenceByCompanyId(company.company_id, "active").ToList();
                        }
                        else
                        {
                            licenceList.Add(licenceController.GetLicenceById(licID, "active"));
                        }
                    }

                    else
                    {
                        if (licID == 0)
                        {
                            licenceList = licenceController.GetAllLicenceByCompanyId(company.company_id, "archived").ToList();
                        }
                        else
                        {
                            licenceList.Add(licenceController.GetLicenceById(licID, "archived"));
                        }
                    }
                    if (licenceList != null && licenceList.Count > 0)
                    {
                        //2. Get Licence
                        foreach (var licence in licenceList)
                        {
                            var licenceDetail = new LicenceDetail();
                            licenceDetail.licence    = licence;
                            licenceDetail.deviceList = new List <DeviceDetail>();


                            //3. Get Device
                            //var deviceList = deviceController.GetAllDevice("", "", licence.original_licence_no).ToList();
                            var deviceList = new List <Device>();
                            deviceList = deviceController.GetAllDevice(licencestatus, "", licence.original_licence_no).ToList();

                            if (deviceList != null && deviceList.Count > 0)
                            {
                                foreach (var device in deviceList)
                                {
                                    var deviceDetail = new DeviceDetail();
                                    deviceDetail.device = device;
                                    deviceDetail.deviceIdentifierList = new List <DeviceIdentifier>();
                                    var identifierList = new List <DeviceIdentifier>();
                                    //4. Get DeviceIdentifier.
                                    //if (licID > 0)
                                    //{
                                    identifierList = identifierController.GetAllDeviceIdentifier(licencestatus, "", licID, device.device_id).ToList();
                                    //}
                                    //else
                                    //{
                                    //    identifierList = identifierController.GetAllDeviceIdentifier(licencestatus, "", 0, device.device_id).ToList();
                                    //}

                                    if (identifierList != null && identifierList.Count > 0)
                                    {
                                        deviceDetail.deviceIdentifierList = identifierList;
                                    }
                                    licenceDetail.deviceList.Add(deviceDetail);
                                }
                            }
                            //5. Add all the list to Company(data)
                            data.licenceList.Add(licenceDetail);
                        }
                    }
                }
            }

            var jsonResult = Json(new { data }, JsonRequestBehavior.AllowGet);

            jsonResult.MaxJsonLength = int.MaxValue;
            return(jsonResult);
        }
Example #26
0
        private void StatisticSubscriptionMetaDataReceived(object sender, EventArgs <DataSet> e)
        {
            LogStatusMessage("Loading received meta-data...", logToClient: false);

            DataSet dataSet = e.Argument;

            m_deviceDetails.Clear();
            m_measurementDetails.Clear();
            m_phasorDetails.Clear();
            m_schemaVersion.Clear();
            m_powerCalculation.Clear();
            m_statusLights.Clear();

            foreach (DataTable table in dataSet.Tables)
            {
                if (table.TableName == "DeviceDetail")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        DeviceDetail deviceDetail = new DeviceDetail
                        {
                            NodeID              = row.ConvertField <Guid>("NodeID"),
                            UniqueID            = row.ConvertField <Guid>("UniqueID"),
                            OriginalSource      = row.ConvertField <string>("OriginalSource"),
                            IsConcentrator      = row.ConvertField <bool>("IsConcentrator"),
                            Acronym             = row.ConvertField <string>("Acronym"),
                            Name                = row.ConvertField <string>("Name"),
                            AccessID            = row.ConvertField <int>("AccessID"),
                            ParentAcronym       = row.ConvertField <string>("ParentAcronym"),
                            ProtocolName        = row.ConvertField <string>("ProtocolName"),
                            FramesPerSecond     = row.ConvertField <int>("FramesPerSecond"),
                            CompanyAcronym      = row.ConvertField <string>("CompanyAcronym"),
                            VendorAcronym       = row.ConvertField <string>("VendorAcronym"),
                            VendorDeviceName    = row.ConvertField <string>("VendorDeviceName"),
                            Longitude           = row.ConvertField <decimal>("Longitude"),
                            Latitude            = row.ConvertField <decimal>("Latitude"),
                            InterconnectionName = row.ConvertField <string>("InterconnectionName"),
                            ContactList         = row.ConvertField <string>("ContactList"),
                            Enabled             = row.ConvertField <bool>("Enabled"),
                            UpdatedOn           = row.ConvertField <DateTime>("UpdatedOn")
                        };

                        if (row.ConvertField <bool>("Enabled"))
                        {
                            StatusLight statusLight = new StatusLight
                            {
                                DeviceAcronym = row.ConvertField <string>("Acronym"),
                                Timestamp     = DateTime.MinValue,
                                GoodData      = false
                            };

                            m_statusLights.Add(statusLight);
                        }

                        m_deviceDetails.Add(deviceDetail);
                    }
                }
                else if (table.TableName == "MeasurementDetail")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        MeasurementDetail measurementDetail = new MeasurementDetail
                        {
                            DeviceAcronym     = row.ConvertField <string>("DeviceAcronym"),
                            ID                = row.ConvertField <string>("ID"),
                            SignalID          = row.ConvertField <Guid>("SignalID"),
                            PointTag          = row.ConvertField <string>("PointTag"),
                            SignalReference   = row.ConvertField <string>("SignalReference"),
                            SignalAcronym     = row.ConvertField <string>("SignalAcronym"),
                            PhasorSourceIndex = row.ConvertField <int>("PhasorSourceIndex"),
                            Description       = row.ConvertField <string>("Description"),
                            Internal          = row.ConvertField <bool>("Internal"),
                            Enabled           = row.ConvertField <bool>("Enabled"),
                            UpdatedOn         = row.ConvertField <DateTime>("UpdatedOn")
                        };

                        m_measurementDetails.Add(measurementDetail);
                    }
                }
                else if (table.TableName == "PhasorDetail")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        PhasorDetail phasorDetail = new PhasorDetail
                        {
                            DeviceAcronym = row.ConvertField <string>("DeviceAcronym"),
                            Label         = row.ConvertField <string>("Label"),
                            Type          = row.ConvertField <string>("Type"),
                            Phase         = row.ConvertField <string>("Phase"),
                            SourceIndex   = row.ConvertField <int>("SourceIndex"),
                            UpdatedOn     = row.ConvertField <DateTime>("UpdatedOn")
                        };

                        m_phasorDetails.Add(phasorDetail);
                    }
                }
                else if (table.TableName == "SchemaVersion")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        SchemaVersion schemaVersion = new SchemaVersion
                        {
                            VersionNumber = row.ConvertField <int>("VersionNumber")
                        };

                        m_schemaVersion.Add(schemaVersion);
                    }
                }
                else if (table.TableName == "PowerCalculation")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        PowerCalculation powerCalculation = new PowerCalculation()
                        {
                            VoltageAngleID = row.ConvertField <Guid>("VoltageAngleSignalID"),
                            CurrentAngleID = row.ConvertField <Guid>("CurrentAngleSignalID")
                        };

                        m_powerCalculation.Add(powerCalculation);
                    }
                }
            }

            try
            {
                string appData           = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string ecaClientDataPath = Path.Combine(appData, "Grid Protection Alliance", "openECAClient");
                string metadataCache     = Path.Combine(ecaClientDataPath, "Metadata.xml");

                Directory.CreateDirectory(ecaClientDataPath);

                if (FilePath.TryGetWriteLock(metadataCache))
                {
                    dataSet.WriteXml(metadataCache, XmlWriteMode.WriteSchema);
                    Program.LogStatus($"Data set serialized with {dataSet.Tables.Count} tables...");
                }
            }
            catch (Exception ex)
            {
                Program.LogException(new InvalidOperationException($"Failed to serialize dataset: {ex.Message}", ex));
            }

            try
            {
                ClientScript?.metaDataReceived();
            }
            catch (NullReferenceException)
            {
                // Client script unavailable for self-created hub instances
            }

            MetadataReceived?.Invoke(this, EventArgs.Empty);
        }
        /// <summary>
        /// 得到该用户所有网关下的所有开关插座设备
        /// </summary>
        /// <param name="openId">openId</param>
        public JsonResult GetUserAllCon(string openId)
        {
            db.Configuration.LazyLoadingEnabled   = false;
            db.Configuration.ProxyCreationEnabled = false;

            //使用SQl语句嵌套查询
            string sql = "SELECT * FROM iot_control_panel WHERE GateWayID IN ( " +
                         "SELECT GateWayID FROM iot_user_gateway WHERE UserId = (" +
                         $"SELECT UserId FROM iot_user WHERE OpenId = '{openId}' GROUP BY UserId))";
            var temp = db.Database.SqlQuery <iot_control_panel>(sql).ToList();

            if (temp == null)
            {
                return(Json(new { statu = StatusCode.NotFound, Message = "未找到任何设备" }, JsonRequestBehavior.AllowGet));
            }
            List <Device> list = new List <Device>();

            if (temp != null)
            {
                foreach (var item in temp)
                {
                    if (item.ParentID == 0)
                    {
                        Device model  = new Device();
                        var    cpanel = db.iot_control_panel.Where(c => c.ParentID == item.ID);
                        model.ID        = item.ID;
                        model.GateWayID = item.GateWayID;
                        model.KeyNumber = item.KeyNumber;
                        model.Name      = item.Name;
                        model.Position  = item.Position;
                        model.Uid       = item.Uid;

                        List <DeviceDetail> dlist = new List <DeviceDetail>();
                        foreach (var rowname in cpanel)
                        {
                            DeviceDetail detail = new DeviceDetail
                            {
                                ID   = rowname.ID,
                                Name = rowname.Name
                            };
                            dlist.Add(detail);
                        }
                        model.list = dlist;
                        list.Add(model);
                    }
                    if (item.ParentID == -1)
                    {
                        Device model  = new Device();
                        var    cpanel = db.iot_control_panel.Where(c => c.ParentID == item.ID);
                        model.ID        = item.ID;
                        model.GateWayID = item.GateWayID;
                        model.KeyNumber = item.KeyNumber;
                        model.Name      = item.Name;
                        model.Position  = item.Position;
                        model.Uid       = item.Uid;
                        list.Add(model);
                    }
                }
            }
            return(Json(list, JsonRequestBehavior.AllowGet));
        }
 public IResult Insert(DeviceDetail deviceDetail)
 {
     deviceDetail.Id = connection.Insert(deviceDetail);
     return(deviceDetail.Id > 0 ? new SuccessResult() : new ErrorResult(Messages.DeviceDetail.NotInserted));
 }
        private void StatisticSubscriptionMetaDataReceived(object sender, EventArgs <DataSet> e)
        {
            LogStatusMessage("Loading received meta-data...", logToClient: false);

            DataSet dataSet = e.Argument;

            m_deviceDetails.Clear();
            m_measurementDetails.Clear();
            m_phasorDetails.Clear();
            m_schemaVersion.Clear();
            m_statusLights.Clear();

            foreach (DataTable table in dataSet.Tables)
            {
                if (table.TableName == "DeviceDetail")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        DeviceDetail deviceDetail = new DeviceDetail
                        {
                            NodeID              = row.ConvertField <Guid>("NodeID"),
                            UniqueID            = row.ConvertField <Guid>("UniqueID"),
                            OriginalSource      = row.ConvertField <string>("OriginalSource"),
                            IsConcentrator      = row.ConvertField <bool>("IsConcentrator"),
                            Acronym             = row.ConvertField <string>("Acronym"),
                            Name                = row.ConvertField <string>("Name"),
                            AccessID            = row.ConvertField <int>("AccessID"),
                            ParentAcronym       = row.ConvertField <string>("ParentAcronym"),
                            ProtocolName        = row.ConvertField <string>("ProtocolName"),
                            FramesPerSecond     = row.ConvertField <int>("FramesPerSecond"),
                            CompanyAcronym      = row.ConvertField <string>("CompanyAcronym"),
                            VendorAcronym       = row.ConvertField <string>("VendorAcronym"),
                            VendorDeviceName    = row.ConvertField <string>("VendorDeviceName"),
                            Longitude           = row.ConvertField <decimal>("Longitude"),
                            Latitude            = row.ConvertField <decimal>("Latitude"),
                            InterconnectionName = row.ConvertField <string>("InterconnectionName"),
                            ContactList         = row.ConvertField <string>("ContactList"),
                            Enabled             = row.ConvertField <bool>("Enabled"),
                            UpdatedOn           = row.ConvertField <DateTime>("UpdatedOn")
                        };

                        if (row.ConvertField <bool>("Enabled"))
                        {
                            StatusLight statusLight = new StatusLight
                            {
                                DeviceAcronym = row.ConvertField <string>("Acronym"),
                                Timestamp     = DateTime.MinValue,
                                GoodData      = false
                            };

                            m_statusLights.Add(statusLight);
                        }

                        m_deviceDetails.Add(deviceDetail);
                    }
                }
                else if (table.TableName == "MeasurementDetail")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        MeasurementDetail measurementDetail = new MeasurementDetail
                        {
                            DeviceAcronym     = row.ConvertField <string>("DeviceAcronym"),
                            ID                = row.ConvertField <string>("ID"),
                            SignalID          = row.ConvertField <Guid>("SignalID"),
                            PointTag          = row.ConvertField <string>("PointTag"),
                            SignalReference   = row.ConvertField <string>("SignalReference"),
                            SignalAcronym     = row.ConvertField <string>("SignalAcronym"),
                            PhasorSourceIndex = row.ConvertField <int>("PhasorSourceIndex"),
                            Description       = row.ConvertField <string>("Description"),
                            Internal          = row.ConvertField <bool>("Internal"),
                            Enabled           = row.ConvertField <bool>("Enabled"),
                            UpdatedOn         = row.ConvertField <DateTime>("UpdatedOn")
                        };

                        m_measurementDetails.Add(measurementDetail);
                    }
                }
                else if (table.TableName == "PhasorDetail")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        PhasorDetail phasorDetail = new PhasorDetail
                        {
                            DeviceAcronym = row.ConvertField <string>("DeviceAcronym"),
                            Label         = row.ConvertField <string>("Label"),
                            Type          = row.ConvertField <string>("Type"),
                            Phase         = row.ConvertField <string>("Phase"),
                            SourceIndex   = row.ConvertField <int>("SourceIndex"),
                            UpdatedOn     = row.ConvertField <DateTime>("UpdatedOn")
                        };

                        m_phasorDetails.Add(phasorDetail);
                    }
                }
                else if (table.TableName == "SchemaVersion")
                {
                    foreach (DataRow row in table.Rows)
                    {
                        SchemaVersion schemaVersion = new SchemaVersion
                        {
                            VersionNumber = row.ConvertField <int>("VersionNumber")
                        };

                        m_schemaVersion.Add(schemaVersion);
                    }
                }
            }

            ClientScript?.metaDataReceived();
        }
        public IResult DeleteDeviceDetail(DeviceDetail deviceDetail)
        {
            bool isDeleted = connection.Delete(deviceDetail);

            return(isDeleted ? new SuccessResult() : new ErrorResult(Messages.DeviceDetail.NotDeleted));
        }