示例#1
0
        /// <summary>
        ///     处理传感器采集数据
        /// </summary>
        /// <param name="facilityAddDatas"></param>
        public static async Task <XResponseMessage> ProcessFacilityAddData(IEnumerable <FacilityAddData> facilityAddDatas)
        {
            if (facilityAddDatas == null)
            {
                throw new ArgumentNullException("facilityAddDatas");
            }

            var result = new XResponseMessage();

            var addDatas = facilityAddDatas as IList <FacilityAddData> ?? facilityAddDatas.ToList();

            if (addDatas.Count > 0 && addDatas != null)
            {
                try
                {
                    addDatas.ForEach(async item =>
                    {
                        // 添加设施
                        var facilityDb = await AddFacility(item);

                        // 添加设备
                        await AddDevice(item, facilityDb);

                        // 添加摄像机
                        await AddCamera(item, facilityDb);
                    });
                }
                catch (Exception ex)
                {
                    return(ResultHelper.CreateExceptionMessage(ex, "添加设施、设备、摄像机出错"));
                }
            }
            return(ResultHelper.CreateMessage("", ErrorType.NoError));
        }
示例#2
0
        /// <summary>
        ///     获取基地下所有设施
        /// </summary>
        /// <param name="farmSerialnum">基地编码</param>
        /// <returns></returns>
        public static async Task <XResponseMessage> ProcessGetFacilities(string farmSerialnum)
        {
            if (farmSerialnum == null)
            {
                throw new ArgumentNullException("farmSerialnum");
            }

            try
            {
                var types = (await _facilityService.GetFacilitiesByFarmIdAsny(farmSerialnum)).ToList().Select(t => new FacilityModel()
                {
                    Serialnum    = t.Serialnum,
                    Name         = t.Name,
                    Farm         = farmSerialnum,
                    FacilityType = t.FacilityTypeSerialnum,
                    //Address = t.Address,
                    //PhotoUrl = t.PhotoUrl,
                    //ContactMan = t.ContactMan,
                    //ContactPhone = t.ContactPhone,
                    //ContactMobile = t.ContactMobile,
                    CreateTime = t.CreateTime
                });
                return(ResultHelper.CreateMessage("", ErrorType.NoError, types));
            }
            catch (Exception ex)
            {
                return(ResultHelper.CreateMessage("", ErrorType.InternalError, null, ex));
            }
        }
示例#3
0
        /// <summary>
        /// 处理采集数据块
        /// </summary>
        /// <param name="collectDataBlock"></param>
        public static XResponseMessage ProcessCollectData(CollectDataBlock collectDataBlock)
        {
            if (collectDataBlock == null)
            {
                throw new ArgumentNullException("collectDataBlock");
            }

            if (collectDataBlock.SensorDatas != null && collectDataBlock.SensorDatas.Any())
            {
                var result = CollectDataProcessor.ProcessSensorData(collectDataBlock.SensorDatas);
                if (result != null && result.Success != ErrorType.NoError)
                {
                    return(result);
                }
            }
            if (collectDataBlock.MediaDatas != null && collectDataBlock.MediaDatas.Any())
            {
                var result = CollectDataProcessor.ProcessMediaData(collectDataBlock.MediaDatas);
                if (result != null && result.Success != ErrorType.NoError)
                {
                    return(result);
                }
            }
            if (collectDataBlock.PictureDatas != null && collectDataBlock.PictureDatas.Any())
            {
                var result = CollectDataProcessor.ProcessPictureData(collectDataBlock.PictureDatas);
                if (result != null && result.Success != ErrorType.NoError)
                {
                    return(result);
                }
            }
            //return null;
            return(ResultHelper.CreateMessage("", ErrorType.NoError));
        }
示例#4
0
 /// <summary>
 ///     处理控制数据块
 /// </summary>
 /// <param name="controlDataBlock"></param>
 public static XResponseMessage ProcessControlData(ControlDataBlock controlDataBlock)
 {
     if (controlDataBlock == null)
     {
         throw new ArgumentNullException("controlDataBlock");
     }
     //todo 此处处理设备控制指令有重复,需要再仔细考虑
     if (controlDataBlock.ControlCmds != null && controlDataBlock.ControlCmds.Any())
     {
         var result = ControlDataProcessor.ProcessControlQueries(controlDataBlock.ControlQueries);
         if (result != null && result.Success != ErrorType.NoError)
         {
             return(result);
         }
     }
     if (controlDataBlock.ControlQueries != null && controlDataBlock.ControlQueries.Any())
     {
         var result = ControlDataProcessor.ProcessControlQueries(controlDataBlock.ControlQueries);
         if (result != null && result.Success == ErrorType.NoError)
         {
             return(result);
         }
     }
     if (controlDataBlock.ControlResults != null && controlDataBlock.ControlResults.Any())
     {
         var result = ControlDataProcessor.ProcessControlResults(controlDataBlock.ControlResults);
         if (result != null && result.Success == ErrorType.NoError)
         {
             return(result);
         }
     }
     //return null;
     return(ResultHelper.CreateMessage("", ErrorType.NoError));
 }
示例#5
0
        ///// <summary>
        ///// 循环处理队列
        ///// </summary>
        //private static void Process()
        //{
        //    if (!FarmRunLogQueue.IsEmpty)
        //    //if (true)
        //    {
        //        try
        //        {
        //            //保存原始数据
        //            var list = FarmRunLogQueue.ToArray();
        //            var entityList = new EntityList<FarmRunLog>(list);
        //            entityList.Save(true);
        //            //处理统计信息
        //            entityList.ForEach(ProcessStatistics);

        //            //清除刚取出来的数据
        //            FarmRunLog log = null;
        //            for (int i = 0; i < list.Length; i++)
        //            {
        //                FarmRunLogQueue.TryDequeue(out log);
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            ServiceLogger.Current.WriteException(ex);
        //        }
        //    }
        //}
        /// <summary>
        /// 处理<see cref="FarmStatus"/>数据
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public static XResponseMessage Process(FarmStatus status)
        {
            if (status == null)
            {
                throw new ArgumentNullException("status");
            }
            //#if DEBUG
            //            Stopwatch sw = new Stopwatch();
            //            sw.Start();
            //#endif
            try
            {
                //ProcessLog(status);
            }
            catch (Exception ex)
            {
                return(ResultHelper.CreateMessage("", ErrorType.InternalError, null, ex));
            }

            //#if DEBUG
            //            sw.Stop();
            //            ServiceLogger.Current.WriteDebugLog("基地上传耗时:" + sw.ElapsedMilliseconds + "ms");
            //#endif
            return(null);
        }
        /// <summary>
        /// 上传控制结果
        /// </summary>
        /// <param name="controlQueries"></param>
        public static XResponseMessage ProcessControlResults(IEnumerable <ControlResult> controlResults)
        {
            if (!controlResults.Any())
            {
                throw new ArgumentNullException("controlResults");
            }
            try
            {
                controlResults.ForEach(async controlResult =>
                {
                    var devCommand = await _deviceControlCommandService.GetDeviceControlCmdByIdAsny(controlResult.Serialnum);
                    var device     = await _deviceService.GetDeviceByIdAsny(devCommand.DeviceSerialnum);

                    if (devCommand != null)
                    {
                        var devControlLog = new DeviceControlLogDto
                        {
                            Serialnum        = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-" + devCommand.DeviceSerialnum,
                            DeviceSerialnum  = devCommand.DeviceSerialnum,
                            CommandSerialnum = controlResult.Serialnum,
                            ControlResult    = controlResult.Result,
                            CreateTime       = DateTime.Now,
                            DeviceShowValue  = device.ShowValue,
                            DeviceValue      = device.ProcessedValue,
                            FailReason       = controlResult.FailReason,
                            Remark           = ""
                        };

                        await _deviceControlLogService.AddControlLog(devControlLog);

                        var devControlConmand = await _deviceControlCommandService.GetDeviceControlCmdByIdAsny(devCommand.Serialnum);
                        if (devControlConmand.Status == (int)DeviceCommandTypeEnum.Getted)
                        {
                            if (controlResult.Result)
                            {
                                devControlConmand.Status = (int)DeviceCommandTypeEnum.ActionSuccess;
                                //接收到来自客户端的上传控制指令的时候,控制成功状态变为2
                            }
                            else
                            {
                                devControlConmand.Status = (int)DeviceCommandTypeEnum.ActionError;
                                //接收到来自客户端的上传控制指令的时候,控制失败状态变为3
                            }
                            devControlConmand.UpdateTime = DateTime.Now;
                            await _deviceControlCommandService.UpdateControlCommandAsny(devControlConmand);
                        }
                    }
                });

                return(ResultHelper.CreateMessage("", ErrorType.NoError));
            }
            catch (Exception ex)
            {
                return(ResultHelper.CreateMessage("", ErrorType.InternalError, null, ex));
            }
        }
示例#7
0
        /// <summary>
        ///     查询设施下所有设备
        /// </summary>
        /// <param name="facilitySerialnum"></param>
        /// <returns></returns>
        public static async Task <XResponseMessage> ProcessGetFacilityDevices(string facilitySerialnum)
        {
            if (facilitySerialnum == null)
            {
                throw new ArgumentNullException("facilitySerialnum");
            }
            decimal?nullValueDecimal = null;

            try
            {
                //查询设施下所有传感器采集和控制设备
                var devices =
                    _deviceService.GetDevicesByFacilityId(facilitySerialnum).ToList().Select(t => new DeviceModel()
                {
                    Serialnum           = t.Serialnum,
                    Name                = t.Name,
                    FacilitySerialnum   = facilitySerialnum,
                    DeviceTypeSerialnum = t.DeviceTypeSerialnum,
                    ProcessedValue      = t.ProcessedValue,
                    ShowValue           = t.ShowValue,
                    Unit                = t.Unit,
                    UpdateTime          = t.UpdateTime,
                    Max = _deviceExceptionSetService.GetDeviceExceptionSetByDeviceId(t.Serialnum) != null
                        ? _deviceExceptionSetService.GetDeviceExceptionSetByDeviceId(t.Serialnum).Max : nullValueDecimal,
                    Min = _deviceExceptionSetService.GetDeviceExceptionSetByDeviceId(t.Serialnum) != null
                        ? _deviceExceptionSetService.GetDeviceExceptionSetByDeviceId(t.Serialnum).Min : nullValueDecimal,
                });
                //查询设施下所有音视频设备
                var cameras =
                    (await _facilityCameraService.GetFacilityCamerasByFacilityIdAsny(facilitySerialnum)).ToList().Select(cam => new MediaData()
                {
                    DeviceCode   = cam.Serialnum,
                    FacilityCode = cam.FacilitySerialnum,
                    Url          = cam.IP,
                    MediaPort    = cam.HttpPort,
                    ContrPort    = cam.DataPort,
                    User         = cam.UserID,
                    Pwd          = cam.UserPwd,
                    Channel      = cam.Channel
                });


                var deviceModels = devices as IList <DeviceModel> ?? devices.ToList();
                return(ResultHelper.CreateMessage("", ErrorType.NoError, new
                {
                    Collect = deviceModels.Where(d => d.DeviceTypeSerialnum.StartsWith("collect")),
                    Control = deviceModels.Where(d => d.DeviceTypeSerialnum.StartsWith("control")),
                    Camera = cameras
                }));
            }
            catch (Exception ex)
            {
                return(ResultHelper.CreateMessage("", ErrorType.InternalError, null, ex));
            }
        }
        /// <summary>
        ///  查询控制指令
        /// </summary>
        /// <param name="controlQueries"></param>
        public static XResponseMessage ProcessControlQueries(IEnumerable <ControlQuery> controlQueries)
        {
            var sw = new Stopwatch();

            sw.Start();
            if (controlQueries == null)
            {
                throw new ArgumentNullException("controlQueries");
            }
            var enumerable = controlQueries as ControlQuery[] ?? controlQueries.ToArray();

            if (enumerable.Any())
            {
                var facCodes = controlQueries.Select(que => que.FacilityCode);
                //var devCmds = _redis.GetVals<DeviceControlCommandDto>("deviceControlCommand", DataType.Protobuf).FindAll(cmd=>cmd.DeviceSerialnum.EqualIgnoreCase());
                var devControlCmds = facCodes.SelectMany(facCode =>
                                                         _deviceControlCommandService.GetDeviceControlCmdsByFacilityId(facCode));

                var cmds = new List <ControlCmd>();
                if (devControlCmds != null && devControlCmds.Count() > 0)
                {
                    devControlCmds.ForEach(async cmdDb =>
                    {
                        if (cmdDb.Status == (int)DeviceCommandTypeEnum.Created)
                        {
                            //if (cmdDb != null)
                            //{
                            var devControlConmand        = await _deviceControlCommandService.GetControlCommandByDeviceIdAsny(cmdDb.Serialnum);
                            devControlConmand.Status     = (int)DeviceCommandTypeEnum.Getted;             //接收到来自客户端的控制指令请求的时候,状态变为1
                            devControlConmand.UpdateTime = DateTime.Now;
                            await _deviceControlCommandService.AddControlCommandAsny(devControlConmand);  //添加控制指令
                                                                                                          //}

                            var cmd = new ControlCmd
                            {
                                Serialnum    = cmdDb.Serialnum,
                                FacilityCode = (await _deviceService.GetDeviceByIdAsny(cmdDb.DeviceSerialnum)).FacilitySerialnum,
                                DeviceCode   = cmdDb.DeviceSerialnum,
                                Command      = Convert.ToInt32(cmdDb.Command),
                                Time         = cmdDb.CreateTime,
                                ContinueTime = cmdDb.ControlContinueTime,
                            };
                            cmds.Add(cmd);
                        }
                    });
                }

                sw.Stop();
                ServiceLogger.Current.WriteDebugLog("处理控制指令花费的时间为:{0}", sw.ElapsedMilliseconds);
                return(ResultHelper.CreateMessage("", ErrorType.NoError, cmds));
            }
            return(ResultHelper.CreateMessage("无控制指令", ErrorType.NoError));
        }
示例#9
0
        /// <summary>
        /// 处理设备添加数据
        /// </summary>
        /// <param name="device">设备添加数据</param>
        /// <returns></returns>
        public async Task <XResponseMessage> ProcessAsync(DeviceModel device)
        {
            var faccility = await _facilityService.GetFacilityByIdAsny(device.FacilitySerialnum);

            if (faccility == null)
            {
                return(ResultHelper.CreateMessage("设施不存在", ErrorType.FacilityNotExists));
            }
            //if (!_deviceService.CheckCode(device.Serialnum)) return;
            //if (!await _farmService.ExistsAsync(device.FacilitySerialnum)) return ResultHelper.CreateMessage("基地不存在", ErrorType.FarmNotExists);
            var deviceType = await _deviceTypeService.GetByIdAsync(device.DeviceTypeSerialnum); //不存在的设备类型无法添加

            if (deviceType == null)
            {
                return(ResultHelper.CreateMessage("设备类型不存在", ErrorType.DeviceTypeNotExists));
            }
            var item = await _deviceService.GetDeviceByIdAsny(device.Serialnum);

            //数据库中不存在该设备(有必要吗?)
            if (item != null)
            {
                return(null);
            }
            item = new DeviceDto
            {
                Serialnum           = device.Serialnum,
                Name                = device.Name,
                DeviceTypeSerialnum = device.DeviceTypeSerialnum,
                FacilitySerialnum   = device.FacilitySerialnum,
                CreateTime          = device.UpdateTime,
                UpdateTime          = device.UpdateTime,
                Status              = 1,
                Sort                = 0,
                Unit                = device.Unit,
                ProcessedValue      = device.ProcessedValue,
                ShowValue           = device.ShowValue,
                RelayType           = device.RelayType,
            };

            try
            {
                var result = await _deviceService.AddDevice(item);

                LogHelper.Info("[设备]设备{0}{1}添加{2}", device.Name, device.Serialnum, result);
                return(ResultHelper.CreateMessage($"添加设备{(result ? "成功" : "失败")}",
                                                  result ? ErrorType.NoError : ErrorType.InternalError));
            }
            catch (AggregateException ex)
            {
                return(ResultHelper.CreateExceptionMessage(ex, "添加设备失败"));
            }
        }
示例#10
0
        /// <summary>
        /// 处理设施添加数据
        /// </summary>
        /// <param name="facility">设施添加数据</param>
        /// <returns></returns>
        public async Task <XResponseMessage> ProcessAsync(FacilityModel facility)
        {
            if (facility == null)
            {
                return(null);
            }
            if (!await _farmService.ExistsAsync(facility.Farm))
            {
                return(ResultHelper.CreateMessage("基地不存在", ErrorType.FarmNotExists));
            }

            var facilityType = await _facilityTypeService.GetByIdAsync(facility.FacilityType); //不存在的设施类型无法添加

            if (facilityType == null)
            {
                return(ResultHelper.CreateMessage("设施类型不存在", ErrorType.FacilityTypeNotExists));
            }

            var item = await _facilityService.GetFacilityByIdAsny(facility.Serialnum);

            //数据库中不存在该设施
            if (item != null)
            {
                return(null);
            }
            item = new FacilityDto
            {
                Serialnum             = facility.Serialnum,
                Name                  = facility.Name,
                FarmSerialnum         = facility.Farm,
                FacilityTypeSerialnum = facility.FacilityType,
                CreateTime            = DateTime.Now,
                UpdateTime            = facility.CreateTime ?? DateTime.Now,
                Status                = 1,
                Sort                  = 0
            };
            try
            {
                var result = await _facilityService.AddFacility(item);

                LogHelper.Info("[设施]设施{0}{1}添加{2}", item.Name, item.Serialnum, result);
                return(ResultHelper.CreateMessage($"添加设施{(result ? "成功" : "失败")}",
                                                  result ? ErrorType.NoError : ErrorType.InternalError));
            }
            catch (AggregateException ex)
            {
                return(ResultHelper.CreateExceptionMessage(ex, "添加设施失败"));
            }
        }
示例#11
0
        public async Task<XResponseMessage> ProcessAsync(IEnumerable<SensorData> mdList)
        {
            if (mdList == null || !mdList.Any()) return ResultHelper.CreateMessage("设备数据为空", ErrorType.NoContent);
            var sensorDatas = mdList.Where(md => md != null);
            var result = true;
            //并行处理
            //Parallel.ForEach(sensorDatas, async sensorData =>
            //{
            var flg = await ProcessAsync1(sensorDatas);
            if (!flg)
                result = false;
            //});

            return ResultHelper.CreateMessage("上传设备数据", result ? ErrorType.NoError : ErrorType.InternalError);
        }
示例#12
0
        /// <summary>
        /// 处理视频设备添加数据
        /// </summary>
        /// <param name="media">视频设备添加数据</param>
        /// <returns></returns>
        public async Task <XResponseMessage> ProcessAsync(MediaData media)
        {
            if (!_facilityCameraService.CheckCode(media.DeviceCode))
            {
                return(ResultHelper.CreateMessage("设备编码规则错误", ErrorType.InternalError));
            }
            if (!await _facilityService.ExistsWithRedisAsync(media.FacilityCode))
            {
                return(ResultHelper.CreateMessage("设施不存在", ErrorType.FacilityNotExists));
            }
            var item = await _facilityCameraService.GetFacilityCameraByIdAsny(media.DeviceCode);

            //数据库中不存在该设备(有必要吗?)
            if (item != null)
            {
                return(null);
            }
            item = new FacilityCameraDto
            {
                Serialnum         = media.DeviceCode,
                Name              = media.DeviceName,
                FacilitySerialnum = media.FacilityCode,
                Channel           = media.Channel,
                UserID            = media.User,
                UserPwd           = media.Pwd,
                IP         = media.Url,
                DataPort   = media.ContrPort,
                HttpPort   = media.MediaPort,
                Sort       = 0,
                Status     = true,
                RtspPort   = 54,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now
            };

            try
            {
                var result = await _facilityCameraService.AddFacilityCamera(item);

                LogHelper.Info("[视频]视频{0}{1}添加{2}", item.Name, item.Serialnum, result);
                return(ResultHelper.CreateMessage($"添加视频设备{(result ? "成功" : "失败")}",
                                                  result ? ErrorType.NoError : ErrorType.InternalError));
            }
            catch (AggregateException ex)
            {
                return(ResultHelper.CreateExceptionMessage(ex, "添加视频设备失败"));
            }
        }
示例#13
0
        /// <summary>
        ///     处理设施更新数据
        /// </summary>
        /// <param name="updates"></param>
        /// <returns></returns>
        public static async Task <XResponseMessage> ProcessFacilityUpdate(List <FacilityUpdateData> updates)
        {
            if (updates == null)
            {
                throw new ArgumentNullException("updates");
            }

            if (!updates.Any())
            {
                return(ResultHelper.CreateMessage("无任何设施更新数据", ErrorType.NoContent));
            }
            foreach (var update in updates)
            {
                var facilitySerialnum = update.Serialnum;
                if (facilitySerialnum.IsNullOrWhiteSpace())
                {
                    return(ResultHelper.CreateMessage("设施编码不能为空", ErrorType.CanNotProcessRequestData));
                }

                try
                {
                    var facility = _redis.Smember <FacilityDto>("facility", DataType.Protobuf).Find(f => f.Serialnum.EqualIgnoreCase(facilitySerialnum));
                    var fac      = facility != null ? facility : await _facilityService.GetFacilityByIdAsny(facilitySerialnum);

                    if (fac == null)
                    {
                        return(ResultHelper.CreateMessage(facilitySerialnum, ErrorType.NoContent));
                    }

                    fac.Name = update.Name;
                    fac.FacilityTypeSerialnum = update.Type;
                    //await _facilityService.AddFacility(fac);
                    if (facility != null)
                    {
                        _redis.Srem("facility", facility, DataType.Protobuf);
                    }
                    _redis.Sadd("facility", fac, DataType.Protobuf);//加入到缓冲
                }
                catch (Exception ex)
                {
                    return(ResultHelper.CreateMessage("", ErrorType.InternalError, null, ex));
                }
            }
            return(null);
        }
示例#14
0
        /// <summary>
        /// 更新设施
        /// </summary>
        /// <param name="facility">设施更新数据</param>
        /// <returns></returns>
        public async Task <XResponseMessage> ProcessAsync(FacilityModel facility)
        {
            if (facility == null)
            {
                return(null);
            }
            if (!_facilityService.CheckCode(facility.Serialnum))
            {
                return(ResultHelper.CreateMessage("设施不存在", ErrorType.FacilityNotExists));
            }
            var facilityType = await _facilityTypeService.GetByIdAsync(facility.FacilityType); //不存在的设施类型无法更新

            if (facilityType == null)
            {
                return(ResultHelper.CreateMessage("设施类型不存在", ErrorType.FacilityTypeNotExists));
            }
            var item = await _facilityService.GetFacilityByIdAsny(facility.Serialnum);

            //数据库中存在该设施并且创建时间大于最新的更新时间
            if (item == null || !(facility.CreateTime > item.UpdateTime))
            {
                return(null);
            }
            item.Serialnum             = facility.Serialnum;
            item.Name                  = facility.Name;
            item.FarmSerialnum         = facility.Farm;
            item.FacilityTypeSerialnum = facility.FacilityType;
            item.UpdateTime            = facility.CreateTime ?? DateTime.Now;
            item.FarmSerialnum         = facility.Farm;
            try
            {
                var result = await _facilityService.UpdateFacilityAsnyc(item);

                LogHelper.Info("[设施]设施{0}{1}更新{2}", item.Name, item.Serialnum, result);
                return(ResultHelper.CreateMessage($"更新设施{(result ? "成功" : "失败")}",
                                                  result ? ErrorType.NoError : ErrorType.InternalError));
            }
            catch (AggregateException ex)
            {
                return(ResultHelper.CreateExceptionMessage(ex, "更新设施失败"));
            }

            return(null);
        }
示例#15
0
        public async Task <XResponseMessage> ProcessAsync(ControlDataBlock controlDataBlock)
        {
            if (controlDataBlock == null)
            {
                return(null);
            }

            if (controlDataBlock.ControlQueries != null)
            {
                try
                {
                    var result =
                        await
                        AhnqIotContainer.Container.Resolve <ControlQueryProcess>()
                        .ProcessAsync(controlDataBlock.ControlQueries);

                    return(ResultHelper.CreateMessage("查询控制指令", obj: result));
                }
                catch (AggregateException ex)
                {
                    return(ResultHelper.CreateExceptionMessage(ex, "查询控制指令失败", ErrorType.InternalError));
                }
            }
            if (controlDataBlock.ControlResults == null)
            {
                return(null);
            }
            {
                try
                {
                    var result =
                        await
                        AhnqIotContainer.Container.Resolve <ControlResultProcess>()
                        .ProcessAsync(controlDataBlock.ControlResults);

                    return(ResultHelper.CreateMessage("上传控制指令", obj: result));
                }
                catch (AggregateException ex)
                {
                    return(ResultHelper.CreateExceptionMessage(ex, "上传控制指令失败", ErrorType.InternalError));
                }
            }
        }
示例#16
0
        /// <summary>
        /// 处理视频设备更新数据
        /// </summary>
        /// <param name="media">视频设备更新数据</param>
        /// <returns></returns>
        public async Task <XResponseMessage> ProcessAsync(MediaData media)
        {
            if (!_facilityCameraService.CheckCode(media.DeviceCode))
            {
                return(ResultHelper.CreateMessage("设备编码规则错误", ErrorType.InternalError));
            }
            if (!await _facilityService.ExistsAsync(media.FacilityCode))
            {
                return(ResultHelper.CreateMessage("设施不存在", ErrorType.FacilityNotExists));
            }
            var item = await _facilityCameraService.GetFacilityCameraByIdAsny(media.DeviceCode);

            //数据库中不存在该设备(有必要吗?)
            if (item == null || media.CreateTime < item.UpdateTime)
            {
                return(null);
            }
            item.Serialnum         = media.DeviceCode;
            item.Name              = media.DeviceName;
            item.FacilitySerialnum = media.FacilityCode;
            item.Channel           = media.Channel;
            item.UserID            = media.User;
            item.UserPwd           = media.Pwd;
            item.IP         = media.Url;
            item.DataPort   = media.ContrPort;
            item.HttpPort   = media.MediaPort;
            item.UpdateTime = media.CreateTime;

            try
            {
                var result = await _facilityCameraService.UpdateCamera(item);

                LogHelper.Info("[视频]视频{0}{1}更新{2}", item.Name, item.Serialnum, result);
                return(ResultHelper.CreateMessage($"更新视频设备{(result ? "成功" : "失败")}",
                                                  result ? ErrorType.NoError : ErrorType.InternalError));
            }
            catch (AggregateException ex)
            {
                return(ResultHelper.CreateExceptionMessage(ex, "更新视频设备失败"));
            }
        }
示例#17
0
        /// <summary>
        ///     检验实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private bool ProcessEntity()
        {
            if (RequestWrapper.Data.IsNullOrWhiteSpace())
            {
                ResponseWrapper = ResultHelper.CreateMessage("请提供有效的数据", ErrorType.NotSupportedProtocalType);
                Response();
                return(false);
            }

            BeginProcessEntity?.Invoke(this, RequestWrapper.Data);

            //检测协议格式
            var entity = AwEntityHelper.GetAwEntity(RequestWrapper.Data);

            if (entity == null)
            {
                LogHelper.Error("[数据格式] {0}", RequestWrapper.Data);
                ResponseWrapper = ResultHelper.CreateMessage("数据格式错误", ErrorType.CanNotProcessRequestData);
                Response();
                return(false);
            }
            //数据包描述信息
            LogHelper.Trace(entity.Description);
            //检测版本号
            if (!AwEntityHelper.CheckVersion(entity.Version))
            {
                LogHelper.Error("[协议版本] {0}错误", entity.Version);
                ResponseWrapper = ResultHelper.CreateMessage("协议版本错误", ErrorType.VersionError);
            }

            EndProcessEntity?.Invoke(this, RequestWrapper.Data);
            if (ResponseWrapper != null)
            {
                Response();
                return(false);
            }

            _awEntity = entity;
            return(true);
        }
示例#18
0
        /// <summary>
        ///     处理获取设施类型
        /// </summary>
        /// <returns></returns>
        public static async Task <XResponseMessage> ProcessFacilityTypeGet()
        {
            try
            {
                var facilityTypeList = _redis.GetVals <FacilityTypeDto>("facilityType", DataType.Protobuf);
                var facilityTypes    = facilityTypeList.Count > 0 ? facilityTypeList : await _facilityTypeService.GetAllAsny();

                var types = facilityTypes.Select(t => new FacilityTypeModel()
                {
                    Serialnum       = t.Serialnum,
                    Name            = t.Name,
                    ParentSerialnum = t.ParentSerialnum,
                    PhotoUrl        = t.PhotoUrl,
                    Introduce       = t.Introduce
                });
                return(ResultHelper.CreateMessage("", ErrorType.NoError, types));
            }
            catch (Exception ex)
            {
                return(ResultHelper.CreateMessage("", ErrorType.InternalError, null, ex));
            }
        }
示例#19
0
        /// <summary>
        ///     处理数据区
        /// </summary>
        /// <returns></returns>
        private async Task <bool> ProcessDataBlockObject()
        {
            var entity = _awEntity;

            if (entity.DataBlockObject == null)
            {
                ResponseWrapper = ResultHelper.CreateMessage("无数据对象块", ErrorType.NoContent);
                // Response();
                return(false);
            }

            #region 数据来源检测

            if (entity.DataBlockObject.Source == null)
            {
                ResponseWrapper = ResultHelper.CreateMessage("数据来源数据块不存在", ErrorType.NoContent);
                //Response();
                return(false);
            }

            //处理前准备
            BeginProcessSource?.Invoke(this, entity.DataBlockObject.Source);

            //检测FarmCode基地编码是否存在
            var farm = await _farmService.GetByIdAsync(entity.DataBlockObject.Source.FarmCode);

            if (farm == null)
            {
                ResponseWrapper = ResultHelper.CreateMessage("基地编码不存在", ErrorType.FarmNotExists);
                //Response();
                return(false);
            }
            //检测FarmKey是否正确
            if (entity.DataBlockObject.Source.FarmKey.IsNullOrWhiteSpace() ||
                !farm.UploadPassword.Equals(entity.DataBlockObject.Source.FarmKey))
            {
                ResponseWrapper = ResultHelper.CreateMessage("基地授权码错误", ErrorType.AuthorizeFailed);
                //Response();
                return(false);
            }

            //后续处理
            EndProcessSource?.Invoke(this, entity.DataBlockObject.Source);

            if (ResponseWrapper != null)
            {
                //Response();
                return(false);
            }

            #endregion

            //时间检测:超过10分钟的数据包不作处理
            if (DateTime.Now.Subtract(entity.DataBlockObject.CreateTime).TotalMinutes > 10)
            {
                LogHelper.Debug("数据包超过10分钟,不作处理:{0}", RequestWrapper.Data);
                ResponseWrapper = ResultHelper.CreateMessage("数据包超过10分钟未处理");
                return(false);
            }

            #region 处理核心数据内容

            var coreDataBlcok = entity.DataBlockObject.DataContentRequest;
            if (coreDataBlcok == null)
            {
                ResponseWrapper = ResultHelper.CreateMessage("数据内容块不存在", ErrorType.NoContent);
                //Response();
                return(false);
            }

            #region 采集数据处理

            //采集数据处理
            if (coreDataBlcok.CollectDataBlock == null)
            {
            }
            else
            {
                var collectDataBlock = coreDataBlcok.CollectDataBlock;
                //传感器数据
                if (collectDataBlock.SensorDatas != null && collectDataBlock.SensorDatas.Any())
                {
                    var result =
                        await
                        AhnqIotContainer.Container.Resolve <SensorDataProcess>()
                        .ProcessAsync(collectDataBlock.SensorDatas);

                    if (result != null)
                    {
                        ResponseWrapper = result;
                        return(false);
                    }
                }

                //多媒体数据
                //await AhnqIotContainer.Container.Resolve<MediaDataProcess>().ProcessAsync(collectDataBlock.MediaDatas);
                if (collectDataBlock.MediaDatas != null && collectDataBlock.MediaDatas.Any())
                {
                    LogHelper.Warn("不处理多媒体数据");
                }
                //图片数据
                if (collectDataBlock.PictureDatas != null && collectDataBlock.PictureDatas.Any())
                {
                    LogHelper.Warn("不处理图片数据");
                }
            }

            #endregion

            #region 控制数据处理

            //控制数据处理
            if (coreDataBlcok.ControlDataBlock == null)
            {
            }
            else
            {
                var controlDataBlock = coreDataBlcok.ControlDataBlock;
                var result           =
                    await AhnqIotContainer.Container.Resolve <ControlDataProcess>().ProcessAsync(controlDataBlock);

                if (result != null)
                {
                    ResponseWrapper = result;
                    return(false);
                }
            }

            #endregion

            #region 查询数据处理

            //查询数据处理
            if (coreDataBlcok.QueryDataBlock == null)
            {
            }
            else
            {
                var queryDataBlock = coreDataBlcok.QueryDataBlock;
                var result         = await AhnqIotContainer.Container.Resolve <QueryDataProcess>().ProcessAsync(queryDataBlock);

                if (result != null)
                {
                    ResponseWrapper = result;
                    return(false);
                }
            }

            #endregion

            #region 管理数据处理

            //管理数据处理
            if (coreDataBlcok.ManageDataBlock == null)
            {
            }
            else
            {
                var manageDataBlock = coreDataBlcok.ManageDataBlock;
                var result          = await AhnqIotContainer.Container.Resolve <ManageDataProcess>().ProcessAsync(manageDataBlock);

                if (result != null)
                {
                    ResponseWrapper = result;
                    return(false);
                }
            }

            #endregion

            #region   数据管理

            //上传数据管理
            if (coreDataBlcok.RuntimeDataBlock == null)
            {
            }
            else
            {
                var runtimeDataBlock = coreDataBlcok.RuntimeDataBlock;
            }

            #endregion

            #endregion

            return(true);
        }
示例#20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="md"></param>
        /// <param name="id">原始数据包ID</param>
        /// <returns></returns>
        public async Task <XResponseMessage> ProcessAsync(QueryDataBlock md)
        {
            if (md == null)
            {
                return(null);
            }
            if (md.FacilityType) //查询设施类型
            {
                try
                {
                    var result = await AhnqIotContainer.Container.Resolve <FacilityTypeProcess>().ProcessAsync();

                    return(ResultHelper.CreateMessage("查询设施类型", obj: result));
                }
                catch (AggregateException ex)
                {
                    ex.InnerExceptions.ToList().ForEach(e =>
                    {
                        LogHelper.Error("查询设施类型出错:{0}", e.Message);
                        LogHelper.Fatal(e.ToString());
                    });
                    return(ResultHelper.CreateExceptionMessage(ex, ex.Message));
                }
            }
            if (md.FarmCode != null && !md.FarmCode.Farm.IsNullOrWhiteSpace()) //查询基地下设施
            {
                try
                {
                    var result =
                        await AhnqIotContainer.Container.Resolve <QueryFacilitysProcess>().ProcessAsync(md.FarmCode.Farm);

                    return(ResultHelper.CreateMessage("查询基地下设施", obj: result));
                }
                catch (AggregateException ex)
                {
                    ex.InnerExceptions.ToList().ForEach(e =>
                    {
                        LogHelper.Error("查询设施类型出错:{0}", e.Message);
                        LogHelper.Fatal(e.ToString());
                    });
                    return(ResultHelper.CreateExceptionMessage(ex, ex.Message));
                }
            }
            if (!md.FacilityCode.IsNullOrWhiteSpace()) //查询指定设施
            {
                try
                {
                    var result =
                        await AhnqIotContainer.Container.Resolve <QueryFacilityProcess>().ProcessAsync(md.FacilityCode);

                    return(ResultHelper.CreateMessage("查询指定设施", obj: result));
                }
                catch (AggregateException ex)
                {
                    ex.InnerExceptions.ToList().ForEach(e =>
                    {
                        LogHelper.Error("查询指定设施出错:{0}", e.Message);
                        LogHelper.Fatal(e.ToString());
                    });
                    return(ResultHelper.CreateExceptionMessage(ex, ex.Message));
                }
            }
            if (md.DeviceType) //查询设备类型
            {
                try
                {
                    var result = await AhnqIotContainer.Container.Resolve <DeviceTypeProcess>().ProcessAsync();

                    return(ResultHelper.CreateMessage("查询指定设施", obj: result));
                }
                catch (AggregateException ex)
                {
                    ex.InnerExceptions.ToList().ForEach(e =>
                    {
                        LogHelper.Error("查询指定设施出错:{0}", e.Message);
                        LogHelper.Fatal(e.ToString());
                    });
                    return(ResultHelper.CreateExceptionMessage(ex, ex.Message));
                }
            }
            if (md.Facility != null && !md.Facility.Facility.IsNullOrWhiteSpace()) //查询设施下的设备
            {
                try
                {
                    var result =
                        await
                        AhnqIotContainer.Container.Resolve <QueryDevicesProcess>().ProcessAsync(md.Facility.Facility);

                    return(ResultHelper.CreateMessage("查询设施下的设备", obj: result));
                }
                catch (AggregateException ex)
                {
                    ex.InnerExceptions.ToList().ForEach(e =>
                    {
                        LogHelper.Error("查询设施下的设备出错:{0}", e.Message);
                        LogHelper.Fatal(e.ToString());
                    });
                    return(ResultHelper.CreateExceptionMessage(ex, ex.Message));
                }
            }
            if (!md.DeviceCode.IsNullOrWhiteSpace()) //查询指定设备
            {
                try
                {
                    var result =
                        await AhnqIotContainer.Container.Resolve <QueryDeviceProcess>().ProcessAsync(md.DeviceCode);

                    return(ResultHelper.CreateMessage("查询指定设备", obj: result));
                }
                catch (AggregateException ex)
                {
                    ex.InnerExceptions.ToList().ForEach(e =>
                    {
                        LogHelper.Error("查询指定设备出错:{0}", e.Message);
                        LogHelper.Fatal(e.ToString());
                    });
                    return(ResultHelper.CreateExceptionMessage(ex, ex.Message));
                }
            }
            if (md.MediaCode.IsNullOrWhiteSpace())
            {
                return(null);
            }
            {
                try
                {
                    var result =
                        await AhnqIotContainer.Container.Resolve <QueryMediaProcess>().ProcessAsync(md.MediaCode);

                    return(ResultHelper.CreateMessage("查询指定视频设备", obj: result));
                }
                catch (AggregateException ex)
                {
                    ex.InnerExceptions.ToList().ForEach(e =>
                    {
                        LogHelper.Error("查询指定视频设备出错:{0}", e.Message);
                        LogHelper.Fatal(e.ToString());
                    });
                    return(ResultHelper.CreateExceptionMessage(ex, ex.Message));
                }
            }


            return(null);
        }
示例#21
0
        /// <summary>
        ///     更新设备数据
        /// </summary>
        /// <param name="update"></param>
        /// <returns></returns>
        public static async Task <XResponseMessage> ProcessDeviceUpdate(DeviceUpdateData update)
        {
            if (update == null)
            {
                throw new ArgumentNullException("update");
            }

            //更新设备
            if (update.Devices != null && update.Devices.Any())
            {
                var updateList = new List <DeviceDto>();
                var setList    = new List <DeviceExceptionSetDto>();

                //foreach (var deviceModel in update.Facility.Where(d => d != null))
                update.Devices.Where(d => d != null).ForEach(async deviceModel =>
                {
                    var devDb = await _deviceService.GetDeviceByIdAsny(deviceModel.Serialnum);
                    //if (devDb == null)
                    //{
                    devDb.Serialnum           = deviceModel.Serialnum;
                    devDb.Name                = deviceModel.Name;
                    devDb.FacilitySerialnum   = deviceModel.FacilitySerialnum;
                    devDb.DeviceTypeSerialnum = deviceModel.DeviceTypeSerialnum;
                    devDb.Unit                = deviceModel.Unit;
                    devDb.ProcessedValue      = deviceModel.ProcessedValue;
                    devDb.ShowValue           = deviceModel.ShowValue;
                    devDb.CreateTime          = devDb.UpdateTime = deviceModel.UpdateTime;
                    //devDb.Save();
                    updateList.Add(devDb);
                    var set = await _deviceExceptionSetService.GetDeviceExceptionSetByDeviceIdAsny(devDb.Serialnum) ??
                              new DeviceExceptionSetDto()
                    {
                        DeviceSerialnum = devDb.Serialnum
                    };
                    if (deviceModel.Max != null)
                    {
                        set.Max = deviceModel.Max.Value;
                    }
                    if (deviceModel.Min != null)
                    {
                        set.Min = deviceModel.Min.Value;
                    }
                    setList.Add(set);
                    //}
                });

                try
                {
                    if (updateList.Count() > 0 && updateList != null)
                    {
                        updateList.ForEach(dev =>
                        {
                            DeviceDto device = null;
                            if (_redis.Exists("device") == 1)
                            {
                                device = _redis.Smember <DeviceDto>("device", DataType.Protobuf).Find(d => d.Serialnum.EqualIgnoreCase(dev.Serialnum));
                            }
                            if (device != null)
                            {
                                _redis.Srem("device", dev, DataType.Protobuf);
                            }
                            //await _deviceService.AddDevice(dev);//保存设备
                            _redis.Sadd("device", dev, DataType.Protobuf);
                        });
                    }
                    if (setList.Count() > 0 && setList != null)
                    {
                        setList.ForEach(async set =>
                        {
                            await _deviceExceptionSetService.AddDeviceExceptionSet(set); //保存设备异常区间
                        });
                    }
                }
                catch (Exception ex)
                {
                    return(ResultHelper.CreateMessage("", ErrorType.InternalError, null, ex));
                }
            }

            //更新音视频设备
            //var cameraDb = FacilityCamera.FindAllWithCache().ToList();
            if (update.Cameras != null && update.Cameras.Any())
            {
                var cameraDb = new List <FacilityCameraDto>();
                update.Cameras.ForEach(async mediaData =>
                {
                    if (mediaData != null)
                    {
                        var cam = await _facilityCameraService.GetFacilityCameraByIdAsny(mediaData.DeviceCode);
                        if (cam != null)
                        {
                            cam.FacilitySerialnum = mediaData.FacilityCode;
                            cam.IP       = mediaData.Url;
                            cam.HttpPort = mediaData.MediaPort;
                            cam.DataPort = mediaData.ContrPort;
                            cam.UserID   = mediaData.User;
                            cam.UserPwd  = mediaData.Pwd;
                            cam.Channel  = mediaData.Channel;
                            cameraDb.Add(cam);
                        }
                    }
                });
                try
                {
                    //保存设施摄像机
                    cameraDb.ForEach(c =>
                    {
                        //await _facilityCameraService.AddFacilityCamera(c);
                        FacilityCameraDto camera = null;
                        if (_redis.Exists("facilityCamera") == 1)
                        {
                            camera = _redis.Smember <FacilityCameraDto>("facilityCamera", DataType.Protobuf).Find(fc => fc.Serialnum.EqualIgnoreCase(c.Serialnum));
                        }
                        if (camera != null)
                        {
                            _redis.Srem("facilityCamera", camera, DataType.Protobuf);
                        }
                        _redis.Sadd("facilityCamera", camera, DataType.Protobuf);
                    });
                }
                catch (Exception ex)
                {
                    return(ResultHelper.CreateMessage("", ErrorType.InternalError, null, ex));
                }
            }

            return(null);
        }
示例#22
0
        /// <summary>
        /// 处理传感器采集数据
        /// </summary>
        /// <param name="sensorDatas"></param>
        public static XResponseMessage ProcessSensorData(IEnumerable <SensorData> sensorDatas)
        {
            if (sensorDatas == null)
            {
                throw new ArgumentNullException("sensorDatas");
            }

            var enumerable = sensorDatas as SensorData[] ?? sensorDatas.ToArray();

            if (enumerable.Any())
            {
                //首先检查是否有不在Redis缓存中的设备
                //  enumerable.Where(sd =>
                //       _redis.GetVals<DeviceDto>("device", DataType.Protobuf).Where(device =>
                //            device.Serialnum.EqualIgnoreCase(sd.DeviceCode)
                //           });
                //);
                //检查是否有不在数据库中的设备
                var deviceNotInDb = enumerable.Where(sd => _deviceService.GetDeviceByIdAsny(sd.DeviceCode) == null);
                var notInDb       = deviceNotInDb as IList <SensorData> ?? deviceNotInDb.ToList();
                if (notInDb.Any())
                {
                    return(ResultHelper.CreateMessage(notInDb.Select(sd => sd.DeviceCode).Join(","), ErrorType.DeviceNotExists));
                }
                enumerable.ForEach(async sd =>
                {
                    var device    = _redis.Smember <DeviceDto>("device", DataType.Protobuf).Find(d => d.Serialnum.EqualIgnoreCase(sd.DeviceCode));
                    DeviceDto dev = device != null ? device : await _deviceService.GetDeviceByIdAsny(sd.DeviceCode);
                    dev.Remark    = sd.BatchNum;
                    if (dev != null)
                    {
                        if (device == null)
                        {
                            _redis.Sadd("device", dev, DataType.Protobuf);//加入到缓存中去
                        }
                        //更新设备实时数据
                        ProcessDevice(sd.Value, sd.ShowValue, sd.Time);

                        //  数据分析、统计、存储

                        //实时数据处理
                        //dev.ProcessDeviceDataInfo();
                        _dataInfoQueue.Enqueue(dev);

                        //添加数据异常记录
                        //dev.ProcessDeviceDataExceptionLog();
                        _deviceDataExceptionLogQueue.Enqueue(dev);

                        //添加设备运行记录
                        _deviceRunLogQueue.Enqueue(dev);

                        //诊断信息
                        //dev.ProcessDiagnotics();
                        //_processDiagnoticsQueue.Enqueue(dev);

                        //分时数据处理
                        //dev.ProcessStatistics(15);
                        //dev.ProcessStatistics(60);
                        _processStatisticsQueue.Enqueue(dev);

                        //设备统计
                        _deviceRunningStatisticsQueue.Enqueue(dev);
                    }
                });
            }
            return(ResultHelper.CreateMessage("无传感器数据需要处理", ErrorType.NoError));
        }
示例#23
0
        /// <summary>
        /// 处理设备更新数据
        /// </summary>
        /// <param name="device">设备更新数据</param>
        /// <returns></returns>
        public async Task <XResponseMessage> ProcessAsync(DeviceModel device)
        {
            var d = await _deviceService.GetDeviceByIdAsny(device.Serialnum);

            if (d == null)
            {
                return(ResultHelper.CreateMessage("设备不存在", ErrorType.DeviceNotExists));
            }
            var deviceType = await _deviceTypeService.GetByIdAsync(device.DeviceTypeSerialnum);

            if (deviceType == null)
            {
                return(ResultHelper.CreateMessage("设备类型不存在", ErrorType.DeviceTypeNotExists));
            }
            var item = await _deviceService.GetDeviceByIdAsny(device.Serialnum);

            //数据库中不存在该设备并且更新时间大于最新的更新时间
            if (item == null || device.UpdateTime < item.UpdateTime)
            {
                return(null);
            }
            item.Serialnum           = device.Serialnum;
            item.Name                = device.Name;
            item.DeviceTypeSerialnum = device.DeviceTypeSerialnum;
            item.FacilitySerialnum   = device.FacilitySerialnum;
            item.UpdateTime          = device.UpdateTime;
            item.Unit                = device.Unit;
            item.ProcessedValue      = device.ProcessedValue;
            item.ShowValue           = device.ShowValue;
            item.RelayType           = device.RelayType;

            var deviceset = await _deviceExceptionSet.GetDeviceExceptionSetByDeviceIdAsny(device.Serialnum);

            //创建设备异常区间
            var set = new DeviceExceptionSetDto
            {
                Max             = device.Max,
                Min             = device.Min,
                DeviceSerialnum = device.Serialnum,
                Status          = true,
                CreateTime      = device.UpdateTime,
                UpdateTime      = device.UpdateTime
            };

            if (deviceset == null)
            {
                set.Serialnum = Guid.NewGuid().ToString();
                await _deviceExceptionSet.AddDeviceExceptionSet(set);
            }
            else
            {
                set.Serialnum = deviceset.Serialnum;
                await _deviceExceptionSet.UpdateAsny(set);
            }
            try
            {
                var result = await _deviceService.UpdateDevice(item);

                LogHelper.Trace("[设备]设备{0}{1}更新{2}", device.Name, device.Serialnum, result);
                return(ResultHelper.CreateMessage($"更新设备{(result ? "成功" : "失败")}",
                                                  result ? ErrorType.NoError : ErrorType.InternalError));
            }
            catch (AggregateException ex)
            {
                LogHelper.Error(ex.ToString());
                return(ResultHelper.CreateExceptionMessage(ex, "更新设备失败"));
            }
        }