Beispiel #1
0
        /// <summary>
        /// 更新通道
        /// </summary>
        /// <param name="deviceContext">数据库实例</param>
        /// <param name="updateChannel">更新的通道</param>
        /// <returns>更新成功时返回true,如果未找到通道返回false</returns>
        public static bool UpdateChannel(DensityContext deviceContext, DensityChannel updateChannel)
        {
            DensityChannel channel = deviceContext.Channels
                                     .Include(c => c.Regions)
                                     .SingleOrDefault(c => c.ChannelId == updateChannel.ChannelId);

            if (channel == null)
            {
                return(false);
            }
            else
            {
                channel.ChannelName  = updateChannel.ChannelName;
                channel.ChannelType  = updateChannel.ChannelType;
                channel.ChannelIndex = updateChannel.ChannelIndex;
                channel.RtspUser     = updateChannel.RtspUser;
                channel.RtspPassword = updateChannel.RtspPassword;
                channel.RtspProtocol = updateChannel.RtspProtocol;
                channel.IsLoop       = updateChannel.IsLoop;
                channel.CrossingId   = updateChannel.CrossingId;
                channel.RoadCrossing = null;
                channel.Regions      = updateChannel.Regions;

                deviceContext.Channels.Update(channel);
                return(true);
            }
        }
Beispiel #2
0
 /// <summary>
 /// 入库处理函数
 /// </summary>
 /// <param name="data">交通事件</param>
 protected override void Handle(TrafficEvent data)
 {
     using (IServiceScope serviceScope = _serviceProvider.CreateScope())
     {
         using (DensityContext context = serviceScope.ServiceProvider.GetRequiredService <DensityContext>())
         {
             try
             {
                 TrafficEvent dbData = context.Events.SingleOrDefault(e =>
                                                                      e.DataId == data.DataId && e.DateTime == data.DateTime);
                 if (dbData == null)
                 {
                     Failed += 1;
                     _logger.LogWarning((int)LogEvent.事件数据块, "交通事件更新失败");
                 }
                 else
                 {
                     dbData.EndTime = data.EndTime;
                     context.SaveChanges();
                     Success += 1;
                 }
             }
             catch (Exception ex)
             {
                 _logger.LogError((int)LogEvent.事件数据块, ex, "事件数据更新异常");
                 Failed += 1;
             }
         }
     }
 }
Beispiel #3
0
 public static void ResetDatabase(IServiceProvider serviceProvider)
 {
     using (DensityContext context = serviceProvider.CreateScope().ServiceProvider.GetRequiredService <DensityContext>())
     {
         context.Database.EnsureDeleted();
         context.Database.EnsureCreated();
     }
 }
Beispiel #4
0
        /// <summary>
        /// 检查通道添加错误原因
        /// </summary>
        /// <param name="deviceContext">数据库实例</param>
        /// <param name="channel">通道</param>
        /// <returns>数据校验结果</returns>
        private static ModelStateDictionary CheckInsertError(DensityContext deviceContext, DensityChannel channel)
        {
            ModelStateDictionary modelState = CheckUpdateError(deviceContext, channel);

            if (deviceContext.Channels.Count(c => c.ChannelId == channel.ChannelId) > 0)
            {
                modelState.AddModelError("ChannelId", $"通道编号重复 {channel.ChannelId}");
            }

            return(modelState);
        }
Beispiel #5
0
        /// <summary>
        /// 添加若干个相同间隔时间和持续时间的拥堵事件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="region"></param>
        /// <param name="time"></param>
        /// <param name="durationMinutes"></param>
        /// <param name="count"></param>
        /// <param name="intervalMinutes"></param>
        /// <returns></returns>
        private DateTime AddInterval(DensityContext context, TrafficRegion region, DateTime time, int durationMinutes, int count, int intervalMinutes)
        {
            DateTime temp = time;

            for (int i = 0; i < count; ++i)
            {
                AddDuration(context, region, temp, durationMinutes);
                temp = temp.AddMinutes(durationMinutes + intervalMinutes);
            }
            return(temp.AddMinutes(-intervalMinutes));
        }
Beispiel #6
0
        /// <summary>
        /// 添加一个持续时长拥堵事件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="region"></param>
        /// <param name="time"></param>
        /// <param name="durationMinutes"></param>
        /// <returns></returns>
        private DateTime AddDuration(DensityContext context, TrafficRegion region, DateTime time, int durationMinutes)
        {
            TrafficEvent trafficEvent = new TrafficEvent
            {
                DataId   = region.DataId,
                DateTime = time,
                EndTime  = time.AddMinutes(durationMinutes)
            };

            context.Events.Add(trafficEvent);
            return(time.AddMinutes(durationMinutes));
        }
Beispiel #7
0
    public DensityContext density()
    {
        DensityContext _localctx = new DensityContext(_ctx, State);

        EnterRule(_localctx, 4, RULE_density);
        int _la;

        try {
            EnterOuterAlt(_localctx, 1);
            {
                State = 32; term();
                State = 37;
                _errHandler.Sync(this);
                _la = _input.La(1);
                while (_la == PLUS || _la == MINUS)
                {
                    {
                        {
                            State = 33;
                            _la   = _input.La(1);
                            if (!(_la == PLUS || _la == MINUS))
                            {
                                _errHandler.RecoverInline(this);
                            }
                            else
                            {
                                if (_input.La(1) == TokenConstants.Eof)
                                {
                                    matchedEOF = true;
                                }

                                _errHandler.ReportMatch(this);
                                Consume();
                            }
                            State = 34; term();
                        }
                    }
                    State = 39;
                    _errHandler.Sync(this);
                    _la = _input.La(1);
                }
            }
        }
        catch (RecognitionException re) {
            _localctx.exception = re;
            _errHandler.ReportError(this, re);
            _errHandler.Recover(this, re);
        }
        finally {
            ExitRule();
        }
        return(_localctx);
    }
Beispiel #8
0
        public static void Cleanup()
        {
            using (FlowContext context = ServiceProvider.GetRequiredService <FlowContext>())
            {
                context.Database.EnsureDeleted();
            }

            using (DensityContext context = ServiceProvider.GetRequiredService <DensityContext>())
            {
                context.Database.EnsureDeleted();
            }
        }
Beispiel #9
0
        /// <summary>
        /// 检查通道更新错误原因
        /// </summary>
        /// <param name="deviceContext">数据库实例</param>
        /// <param name="channel">通道</param>
        /// <returns>数据校验结果</returns>
        public static ModelStateDictionary CheckUpdateError(DensityContext deviceContext, DensityChannel channel)
        {
            ModelStateDictionary modelState = new ModelStateDictionary();

            if (channel.CrossingId.HasValue)
            {
                if (deviceContext.RoadCrossings.Count(d => d.CrossingId == channel.CrossingId) == 0)
                {
                    modelState.AddModelError("CrossingId", $"不存在路口编号 {channel.CrossingId}");
                }
            }

            return(modelState);
        }
 protected override void ChangeDatabase(IServiceProvider serviceProvider, string tableName)
 {
     using (DensityContext context = serviceProvider.GetRequiredService <DensityContext>())
     {
         try
         {
             context.ChangeDatabase(tableName);
             _logger.LogInformation((int)LogEvent.分支切换, $"切换密度数据表成功 {tableName}");
         }
         catch (MySqlException ex)
         {
             _logger.LogError((int)LogEvent.分支切换, ex, "切换密度数据表失败");
         }
     }
 }
Beispiel #11
0
 /// <summary>
 /// 入库处理函数
 /// </summary>
 /// <param name="data">交通事件</param>
 protected override void Handle(TrafficEvent data)
 {
     using (IServiceScope serviceScope = _serviceProvider.CreateScope())
     {
         using (DensityContext context = serviceScope.ServiceProvider.GetRequiredService <DensityContext>())
         {
             try
             {
                 context.Events.Add(data);
                 context.SaveChanges();
                 Success += 1;
             }
             catch (Exception ex)
             {
                 _logger.LogError((int)LogEvent.事件数据块, ex, "事件数据入库异常");
                 Failed += 1;
             }
         }
     }
 }
Beispiel #12
0
 protected override void Handle(TrafficDensity[] datas)
 {
     using (IServiceScope serviceScope = _serviceProvider.CreateScope())
     {
         using (DensityContext context = serviceScope.ServiceProvider.GetRequiredService <DensityContext>())
         {
             if (datas[0].DateLevel == DateTimeLevel.Minute)
             {
                 try
                 {
                     context.Densities_One.AddRange(datas.Select(data => new TrafficDensity_One
                     {
                         DataId   = data.DataId,
                         DateTime = data.DateTime,
                         Value    = data.Value
                     }));
                     context.BulkSaveChanges(options => options.BatchSize = datas.Length);
                     Success_One += datas.Length;
                 }
                 catch (Exception ex)
                 {
                     _logger.LogError((int)LogEvent.高点数据块, ex, "一分钟密度数据入库异常");
                     Failed_One += datas.Length;
                 }
             }
             else if (datas[0].DateLevel == DateTimeLevel.FiveMinutes)
             {
                 try
                 {
                     context.Densities_Five.AddRange(datas.Select(data => new TrafficDensity_Five
                     {
                         DataId   = data.DataId,
                         DateTime = data.DateTime,
                         Value    = data.Value
                     }));
                     context.BulkSaveChanges(options => options.BatchSize = datas.Length);
                     Success_Five += datas.Length;
                 }
                 catch (Exception ex)
                 {
                     _logger.LogError((int)LogEvent.高点数据块, ex, "五分钟密度数据入库异常");
                     Failed_Five += datas.Length;
                 }
             }
             else if (datas[0].DateLevel == DateTimeLevel.FifteenMinutes)
             {
                 try
                 {
                     context.Densities_Fifteen.AddRange(datas.Select(data => new TrafficDensity_Fifteen
                     {
                         DataId   = data.DataId,
                         DateTime = data.DateTime,
                         Value    = data.Value
                     }));
                     context.BulkSaveChanges(options => options.BatchSize = datas.Length);
                     Success_Fifteen += datas.Length;
                 }
                 catch (Exception ex)
                 {
                     _logger.LogError((int)LogEvent.高点数据块, ex, "十五分钟密度数据入库异常");
                     Failed_Fifteen += datas.Length;
                 }
             }
             else if (datas[0].DateLevel == DateTimeLevel.Hour)
             {
                 try
                 {
                     context.Densities_hour.AddRange(datas.Select(data => new TrafficDensity_Hour
                     {
                         DataId   = data.DataId,
                         DateTime = data.DateTime,
                         Value    = data.Value
                     }));
                     context.BulkSaveChanges(options => options.BatchSize = datas.Length);
                     Success_Sixty += datas.Length;
                 }
                 catch (Exception ex)
                 {
                     _logger.LogError((int)LogEvent.高点数据块, ex, "一小时密度数据入库异常");
                     Failed_Sixty += datas.Length;
                 }
             }
         }
     }
 }
Beispiel #13
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="context">数据库示例</param>
 /// <param name="memoryCache">缓存</param>
 public EventsController(DensityContext context, IMemoryCache memoryCache)
 {
     _context     = context;
     _memoryCache = memoryCache;
 }
Beispiel #14
0
 /// <summary>
 /// 添加通道
 /// </summary>
 /// <param name="deviceContext">数据库上下文</param>
 /// <param name="newChannel">新通道</param>
 public static void AddChannel(DensityContext deviceContext, DensityChannel newChannel)
 {
     newChannel.ChannelStatus = (int)DeviceStatus.异常;
     newChannel.RoadCrossing  = null;
     deviceContext.Channels.Add(newChannel);
 }
Beispiel #15
0
        public static Dictionary <TrafficEvent, int> CreateData(IServiceProvider serviceProvider, List <DensityDevice> devices, DateTime startDate, DateTime endDate, DataCreateMode mode, bool initDatabase = false)
        {
            if (initDatabase)
            {
                ResetDatabase(serviceProvider);
            }

            using (IServiceScope serviceScope = serviceProvider.CreateScope())
            {
                using (DensityContext context = serviceScope.ServiceProvider.GetRequiredService <DensityContext>())
                {
                    Dictionary <TrafficEvent, int> result = new Dictionary <TrafficEvent, int>();
                    Random random = new Random();

                    int hours = Convert.ToInt32((endDate - startDate).TotalHours + 24);
                    foreach (DensityDevice device in devices)
                    {
                        foreach (var relation in device.DensityDevice_DensityChannels)
                        {
                            foreach (TrafficRegion region in relation.Channel.Regions)
                            {
                                if (mode == DataCreateMode.Fixed)
                                {
                                    for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
                                    {
                                        for (int h = 0; h < 24; ++h)
                                        {
                                            TrafficEvent trafficEvent1 = new TrafficEvent
                                            {
                                                DataId   = region.DataId,
                                                DateTime = date.AddHours(h),
                                                EndTime  = date.AddHours(h).AddMinutes(1)
                                            };
                                            context.Events.Add(trafficEvent1);
                                            TrafficEvent trafficEvent2 = new TrafficEvent
                                            {
                                                DataId   = region.DataId,
                                                DateTime = date.AddHours(h).AddMinutes(30),
                                                EndTime  = date.AddHours(h).AddMinutes(30).AddMinutes(1)
                                            };
                                            context.Events.Add(trafficEvent2);
                                        }
                                    }
                                }
                                else if (mode == DataCreateMode.Random)
                                {
                                    int value = random.Next(1, hours);
                                    result.Add(new TrafficEvent
                                    {
                                        DataId = region.DataId
                                    }, value);
                                    for (int h = 0; h < value; ++h)
                                    {
                                        TrafficEvent trafficEvent = new TrafficEvent
                                        {
                                            DataId   = region.DataId,
                                            DateTime = startDate.AddHours(h),
                                            EndTime  = startDate.AddHours(h).AddMinutes(1)
                                        };
                                        context.Events.Add(trafficEvent);
                                    }
                                }
                            }
                        }
                    }

                    context.BulkSaveChanges(options => options.BatchSize = 1000);
                    return(result);
                }
            }
        }
Beispiel #16
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="context">数据库实例</param>
 /// <param name="memoryCache">缓存</param>
 public DensitiesManager(DensityContext context, IMemoryCache memoryCache)
 {
     _context     = context;
     _memoryCache = memoryCache;
 }
Beispiel #17
0
        public void QueryVipRegions()
        {
            List <DensityDevice> devices = new List <DensityDevice>();
            int deviceCount       = 1;
            int channelCount      = 1;
            int regionCount       = 12;
            HashSet <string> vips = new HashSet <string>();
            //随机创建重点区域
            Random random = new Random();

            using (IServiceScope serviceScope = TestInit.ServiceProvider.CreateScope())
            {
                using (DensityContext context = serviceScope.ServiceProvider.GetRequiredService <DensityContext>())
                {
                    context.Database.EnsureDeleted();
                    context.Database.EnsureCreated();

                    int deviceId   = 1;
                    int crossingId = 1;
                    int regionId   = 1;
                    int channelId  = 1;
                    for (int i = 0; i < deviceCount; ++i)
                    {
                        DensityDevice densityDevice = new DensityDevice
                        {
                            DeviceId = deviceId++,
                            Ip       = "192.168.200.204",
                            Port     = 18000 + i
                        };
                        densityDevice.DeviceName = "设备" + densityDevice.Port;
                        densityDevice.DensityDevice_DensityChannels = new List <DensityDevice_DensityChannel>();
                        for (int j = 0; j < channelCount; ++j)
                        {
                            RoadCrossing roadCrossing = new RoadCrossing
                            {
                                CrossingId   = crossingId,
                                CrossingName = "路口" + crossingId
                            };
                            DensityChannel channel = new DensityChannel()
                            {
                                ChannelId    = channelId.ToString(),
                                ChannelName  = $"通道 {densityDevice.DeviceId} {j+1}",
                                ChannelIndex = j + 1,
                                CrossingId   = crossingId,
                                Regions      = new List <TrafficRegion>(),
                                RoadCrossing = roadCrossing
                            };
                            DensityDevice_DensityChannel relation = new DensityDevice_DensityChannel
                            {
                                ChannelId = channel.ChannelId,
                                DeviceId  = densityDevice.DeviceId,
                                Channel   = channel
                            };
                            channelId++;
                            crossingId++;
                            densityDevice.DensityDevice_DensityChannels.Add(relation);

                            for (int k = 0; k < regionCount; ++k)
                            {
                                int           value  = random.Next(1, 2);
                                TrafficRegion region = new TrafficRegion
                                {
                                    ChannelId   = channel.ChannelId,
                                    Channel     = channel,
                                    Region      = "1",
                                    RegionIndex = k + 1,
                                    RegionName  = "区域" + regionId++,
                                    IsVip       = value == 1
                                };
                                if (value == 1)
                                {
                                    vips.Add(region.DataId);
                                }
                                channel.Regions.Add(region);
                            }
                        }
                        context.Devices.Add(densityDevice);
                        devices.Add(densityDevice);
                    }
                    context.SaveChanges();
                }
                DensityDbSimulator.CreateData(TestInit.ServiceProvider, devices, DataCreateMode.Fixed, DateTime.Today, DateTime.Today);
                TestInit.RefreshDensityCache(devices);
                DensitiesManager manager = TestInit.ServiceProvider.GetRequiredService <DensitiesManager>();

                var v = manager.QueryVipRegions();
                foreach (TrafficDensity density in v)
                {
                    Assert.IsTrue(vips.Contains(density.DataId));
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// 初始化数据库
        /// </summary>
        private async void InitDb()
        {
            _logger.LogInformation((int)LogEvent.系统, "初始化数据库");

            DateTime minTime = TimePointConvert.CurrentTimePoint(BranchDbConvert.DateLevel);

            using (IServiceScope serviceScope = _serviceProvider.CreateScope())
            {
                using (DensityContext context = serviceScope.ServiceProvider.GetRequiredService <DensityContext>())
                {
                    if (context.Database.EnsureCreated())
                    {
                        #region 用户
                        _logger.LogInformation((int)LogEvent.系统, "创建管理员用户");
                        UserManager <IdentityUser> userManager = serviceScope.ServiceProvider.GetRequiredService <UserManager <IdentityUser> >();
                        await userManager.CreateAsync(new IdentityUser("admin"), "123456");

                        #endregion

                        #region 权限
                        _logger.LogInformation((int)LogEvent.系统, "创建权限");
                        IdentityUser adminUser = await userManager.FindByNameAsync("admin");

                        List <YumekoJabami.Models.Claim> claims = new List <YumekoJabami.Models.Claim>
                        {
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03000000", Descirption = "智慧高点视频检测系统"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03010000", Descirption = "设备管理"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03010100", Descirption = "设备信息维护"
                            },
                            //new YumekoJabami.Models.Claim{ Type = ClaimTypes.Webpage, Value = "03010200", Descirption = "设备位置维护"},
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03010300", Descirption = "国标网关设置"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03010400", Descirption = "设备运行状态"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03010500", Descirption = "视频信息维护"
                            },
                            //new YumekoJabami.Models.Claim{ Type = ClaimTypes.Webpage, Value = "03010600", Descirption = "视频位置维护"},
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03020000", Descirption = "数据分析"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03020100", Descirption = "交通密度查询"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03020200", Descirption = "交通密度分析"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03020300", Descirption = "拥堵事件统计"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03020400", Descirption = "拥堵事件排名"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03020500", Descirption = "拥堵高发时段"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03030000", Descirption = "系统设置"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03030100", Descirption = "路口维护"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03030300", Descirption = "用户管理"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03030400", Descirption = "角色管理"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03030600", Descirption = "字典管理"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03030700", Descirption = "参数管理"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03030800", Descirption = "日志查询"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03030900", Descirption = "系统监控"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03040000", Descirption = "状况监测"
                            },
                            new YumekoJabami.Models.Claim {
                                Type = ClaimTypes.Webpage, Value = "03040100", Descirption = "应用检测"
                            },
                        };
                        context.TrafficClaims.AddRange(claims);
                        foreach (YumekoJabami.Models.Claim claim in claims)
                        {
                            await userManager.AddClaimAsync(adminUser, new Claim(claim.Type, claim.Value));
                        }
                        #endregion

                        #region 字典
                        _logger.LogInformation((int)LogEvent.系统, "创建字典");

                        List <Code> densityCodes = new List <Code>
                        {
                            new Code
                            {
                                Key         = "DensityDateLevel",
                                Value       = (int)DateTimeLevel.FiveMinutes,
                                Description = "五分钟密度"
                            },
                            new Code
                            {
                                Key         = "DensityDateLevel",
                                Value       = (int)DateTimeLevel.FifteenMinutes,
                                Description = "十五分钟密度"
                            },
                            new Code
                            {
                                Key         = "DensityDateLevel",
                                Value       = (int)DateTimeLevel.Hour,
                                Description = "一小时密度"
                            },
                            new Code
                            {
                                Key         = "DensityDateLevel",
                                Value       = (int)DateTimeLevel.Day,
                                Description = "一天密度"
                            },
                            new Code
                            {
                                Key         = "DensityDateLevel",
                                Value       = (int)DateTimeLevel.Month,
                                Description = "一月密度"
                            }
                        };

                        densityCodes.AddRange(Enum.GetValues(typeof(ChannelType))
                                              .Cast <ChannelType>()
                                              .Select(e => new Code {
                            Key = typeof(ChannelType).Name, Value = (int)e, Description = e.ToString()
                        }));

                        densityCodes.AddRange(Enum.GetValues(typeof(DeviceModel))
                                              .Cast <DeviceModel>()
                                              .Select(e => new Code {
                            Key = typeof(DeviceModel).Name, Value = (int)e, Description = e.ToString()
                        }));

                        densityCodes.AddRange(Enum.GetValues(typeof(DeviceStatus))
                                              .Cast <DeviceStatus>()
                                              .Select(e => new Code {
                            Key = typeof(DeviceStatus).Name, Value = (int)e, Description = e.ToString()
                        }));

                        densityCodes.AddRange(Enum.GetValues(typeof(RtspProtocol))
                                              .Cast <RtspProtocol>()
                                              .Select(e => new Code {
                            Key = typeof(RtspProtocol).Name, Value = (int)e, Description = e.ToString()
                        }));

                        densityCodes.AddRange(Enum.GetValues(typeof(LogEvent))
                                              .Cast <LogEvent>()
                                              .Select(e => new Code {
                            Key = typeof(LogEvent).Name, Value = (int)e, Description = e.ToString()
                        }));

                        densityCodes.Add(new Code
                        {
                            Key         = "LogLevel",
                            Value       = (int)LogLevel.Debug,
                            Description = "调试"
                        });

                        densityCodes.Add(new Code
                        {
                            Key         = "LogLevel",
                            Value       = (int)LogLevel.Information,
                            Description = "消息"
                        });

                        densityCodes.Add(new Code
                        {
                            Key         = "LogLevel",
                            Value       = (int)LogLevel.Warning,
                            Description = "警告"
                        });

                        densityCodes.Add(new Code
                        {
                            Key         = "LogLevel",
                            Value       = (int)LogLevel.Error,
                            Description = "错误"
                        });
                        context.Codes.AddRange(densityCodes);

                        #endregion
                        context.Version.Add(new TrafficVersion
                        {
                            Version = Assembly.GetExecutingAssembly().GetName().Version.ToString()
                        });
                        context.SaveChanges();
                    }
                    else
                    {
                        context.SaveChanges();
                        try
                        {
                            TrafficDensity_One density = context.Densities_One.OrderByDescending(d => d.Id).FirstOrDefault();
                            if (density != null &&
                                TimePointConvert.CurrentTimePoint(BranchDbConvert.DateLevel, density.DateTime) != minTime)
                            {
                                context.ChangeDatabase(BranchDbConvert.GetTableName(density.DateTime));
                            }
                        }
                        catch (MySqlException)
                        {
                        }
                    }
                }
            }
        }
Beispiel #19
0
 /// <summary>
 /// 数据库实例
 /// </summary>
 /// <param name="context">数据库实例</param>
 public RegionsManager(DensityContext context)
 {
     _context = context;
 }
Beispiel #20
0
        public static List <DensityDevice> CreateDensityDevice(IServiceProvider serviceProvider, int deviceCount, int channelCount, int regionCount, string ip = "127.0.0.1", bool initDatabase = false)
        {
            List <DensityDevice> devices = new List <DensityDevice>();

            using (IServiceScope serviceScope = serviceProvider.CreateScope())
            {
                using (DensityContext context = serviceScope.ServiceProvider.GetRequiredService <DensityContext>())
                {
                    if (initDatabase)
                    {
                        context.Database.EnsureDeleted();
                        context.Database.EnsureCreated();
                    }

                    int deviceId   = 20000;
                    int crossingId = 20000;
                    int regionId   = 20000;
                    int port       = 17000;
                    for (int i = 0; i < deviceCount; ++i)
                    {
                        DensityDevice device = new DensityDevice
                        {
                            DeviceId    = deviceId,
                            DeviceModel = (int)DeviceModel.MO_AF_A11_04_4X,
                            Ip          = ip,
                            DataPort    = port,
                            Port        = port
                        };
                        device.DeviceName = "高点测试设备" + device.DataPort;
                        device.DensityDevice_DensityChannels = new List <DensityDevice_DensityChannel>();
                        for (int j = 0; j < channelCount; ++j)
                        {
                            RoadCrossing roadCrossing = new RoadCrossing
                            {
                                CrossingId   = crossingId,
                                CrossingName = "高点测试路口" + crossingId
                            };

                            DensityChannel channel = new DensityChannel()
                            {
                                ChannelId    = $"channel_{device.DeviceId}_{j + 1}",
                                ChannelName  = $"高点测试通道 { device.DeviceId} {j + 1}",
                                ChannelType  = (int)ChannelType.GB28181,
                                ChannelIndex = j + 1,
                                CrossingId   = crossingId,
                                Regions      = new List <TrafficRegion>(),
                                RoadCrossing = roadCrossing
                            };

                            DensityDevice_DensityChannel relation = new DensityDevice_DensityChannel
                            {
                                ChannelId = channel.ChannelId,
                                DeviceId  = device.DeviceId,
                                Channel   = channel
                            };
                            port++;
                            deviceId++;
                            crossingId++;
                            device.DensityDevice_DensityChannels.Add(relation);

                            for (int k = 0; k < regionCount; ++k)
                            {
                                channel.Regions.Add(new TrafficRegion
                                {
                                    ChannelId       = channel.ChannelId,
                                    Channel         = channel,
                                    RegionIndex     = k + 1,
                                    RegionName      = "高点测试区域" + regionId++,
                                    Region          = "[]",
                                    IsVip           = true,
                                    CarCount        = 1,
                                    DensityRange    = 1,
                                    Density         = 1,
                                    Frequency       = 1,
                                    Warning         = 1,
                                    Saturation      = 1,
                                    WarningDuration = 1
                                });
                            }
                        }
                        context.Devices.Add(device);
                        devices.Add(device);
                        context.SaveChanges();
                    }
                }
            }

            return(devices);
        }
Beispiel #21
0
        public static Dictionary <TrafficRegion, int> CreateData(IServiceProvider serviceProvider, List <DensityDevice> devices, List <DataCreateMode> modes, List <DateTime> startTimes, List <DateTime> endTimes, bool initDatabase = false)
        {
            if (initDatabase)
            {
                ResetDatabase(serviceProvider);
            }



            Dictionary <TrafficRegion, int> regions = new Dictionary <TrafficRegion, int>();

            for (int i = 0; i < startTimes.Count; ++i)
            {
                DateTime           minTime = TimePointConvert.CurrentTimePoint(BranchDbConvert.DateLevel, startTimes[i]);
                DateTime           maxTime = TimePointConvert.NextTimePoint(BranchDbConvert.DateLevel, minTime);
                DensityBranchBlock branch  = new DensityBranchBlock(serviceProvider);
                branch.Open(devices, minTime, maxTime);
                Random random = new Random();
                foreach (DensityDevice device in devices)
                {
                    foreach (var relation in device.DensityDevice_DensityChannels)
                    {
                        foreach (TrafficRegion region in relation.Channel.Regions)
                        {
                            int randomValue = random.Next(1, 1000);
                            if (modes[i] == DataCreateMode.Random)
                            {
                                regions[region] = randomValue;
                            }

                            int value = 1;
                            for (int m = 0; m < 1440; ++m)
                            {
                                DateTime dataTime = startTimes[i].AddMinutes(m);
                                if (dataTime > DateTime.Now)
                                {
                                    break;
                                }
                                if (dataTime >= startTimes[i] && dataTime < endTimes[i])
                                {
                                    TrafficDensity density;
                                    if (modes[i] == DataCreateMode.Fixed)
                                    {
                                        density = new TrafficDensity
                                        {
                                            MatchId  = $"{device.Ip}_{relation.Channel.ChannelIndex}_{region.RegionIndex}",
                                            DateTime = new DateTime(dataTime.Year, dataTime.Month, dataTime.Day, dataTime.Hour, dataTime.Minute, 0),
                                            Value    = 1
                                        };
                                    }
                                    else if (modes[i] == DataCreateMode.Sequence)
                                    {
                                        density = new TrafficDensity
                                        {
                                            MatchId  = $"{device.Ip}_{relation.Channel.ChannelIndex}_{region.RegionIndex}",
                                            DateTime = new DateTime(dataTime.Year, dataTime.Month, dataTime.Day, dataTime.Hour, dataTime.Minute, 0),
                                            Value    = value
                                        };
                                    }
                                    else
                                    {
                                        density = new TrafficDensity
                                        {
                                            MatchId  = $"{device.Ip}_{relation.Channel.ChannelIndex}_{region.RegionIndex}",
                                            DateTime = new DateTime(dataTime.Year, dataTime.Month, dataTime.Day, dataTime.Hour, dataTime.Minute, 0),
                                            Value    = randomValue
                                        };
                                    }
                                    branch.Post(density);
                                }
                                ++value;
                            }
                        }
                    }
                }

                branch.Close();
                if (i == startTimes.Count - 1)
                {
                    DateTime currentTime = TimePointConvert.CurrentTimePoint(BranchDbConvert.DateLevel);
                    if (minTime != currentTime)
                    {
                        using (DensityContext context = serviceProvider.GetRequiredService <DensityContext>())
                        {
                            context.ChangeDatabase(BranchDbConvert.GetTableName(minTime));
                        }
                        branch.SwitchBranch(maxTime, TimePointConvert.NextTimePoint(BranchDbConvert.DateLevel, maxTime));
                    }
                }
                else
                {
                    DateTime nextItem = TimePointConvert.CurrentTimePoint(BranchDbConvert.DateLevel, startTimes[i + 1]);
                    if (minTime != nextItem)
                    {
                        using (DensityContext context = serviceProvider.GetRequiredService <DensityContext>())
                        {
                            context.ChangeDatabase(BranchDbConvert.GetTableName(minTime));
                        }
                        branch.SwitchBranch(maxTime, TimePointConvert.NextTimePoint(BranchDbConvert.DateLevel, maxTime));
                    }
                }
            }

            return(regions);
        }
Beispiel #22
0
        /// <summary>
        /// 检查通道导入错误原因
        /// </summary>
        /// <param name="deviceContext">数据库实例</param>
        /// <param name="file">文件</param>
        /// <returns>数据校验结果</returns>
        private ModelStateDictionary CheckFileError(DensityContext deviceContext, IFormFile file)
        {
            ModelStateDictionary modelState = new ModelStateDictionary();

            if (file == null || file.Length == 0)
            {
                modelState.AddModelError("File", "文件为空");
            }
            else
            {
                string filePath = Path.GetTempFileName();
                using (FileStream stream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                FileInfo fileinfo = new FileInfo(filePath);
                using (ExcelPackage package = new ExcelPackage(fileinfo))
                {
                    if (package.Workbook.Worksheets.Count == 0)
                    {
                        modelState.AddModelError("File", "没有数据页");
                    }
                    else
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                        int            rowCount  = worksheet.Dimension.Rows;
                        if (worksheet.Dimension.Columns < 13)
                        {
                            modelState.AddModelError("File", "数据列少于14");
                        }
                        else
                        {
                            for (int row = 2; row <= rowCount; row++)
                            {
                                if (worksheet.Cells[row, 1].Value == null)
                                {
                                    modelState.AddModelError("ChannelName", $"{row},1 通道名称不能为空");
                                }

                                if (worksheet.Cells[row, 2].Value == null)
                                {
                                    modelState.AddModelError("ChannelId", $"{row},2 通道地址不能为空");
                                }
                                else
                                {
                                    if (deviceContext.Channels.Count(c => c.ChannelId == worksheet.Cells[row, 2].Value.ToString()) > 0)
                                    {
                                        modelState.AddModelError("ChannelId", $"通道编号重复{worksheet.Cells[row, 2].Value}");
                                    }
                                }

                                if (worksheet.Cells[row, 3].Value == null ||
                                    !int.TryParse(worksheet.Cells[row, 3].Value.ToString(), out _))
                                {
                                    modelState.AddModelError("ChannelType", $"{row},3 通道类型格式不正确");
                                }

                                if (worksheet.Cells[row, 4].Value != null && !int.TryParse(worksheet.Cells[row, 4].Value.ToString(), out _))
                                {
                                    modelState.AddModelError("SectionId", $"{row},4 路段编号格式不正确");
                                }

                                if (worksheet.Cells[row, 5].Value != null && !int.TryParse(worksheet.Cells[row, 5].Value.ToString(), out _))
                                {
                                    modelState.AddModelError("CrossingId", $"{row},5 路口编号格式不正确");
                                }

                                if (worksheet.Cells[row, 8].Value != null && !int.TryParse(worksheet.Cells[row, 8].Value.ToString(), out _))
                                {
                                    modelState.AddModelError("RtspProtocol", $"{row},8 Rtsp协议类型数据格式错误");
                                }
                            }
                        }
                    }
                }
            }

            return(modelState);
        }
Beispiel #23
0
 /// <summary>
 /// 数据库实例
 /// </summary>
 /// <param name="context">数据库实例</param>
 /// <param name="memoryCache">缓存</param>
 /// <param name="logger">日志</param>
 public ChannelsManager(DensityContext context, IMemoryCache memoryCache, ILogger <ChannelsManager> logger)
 {
     _context     = context;
     _memoryCache = memoryCache;
     _logger      = logger;
 }
Beispiel #24
0
        public void Incidence(int startYear, int startMonth, int startDay)
        {
            DateTime             startDate = new DateTime(startYear, startMonth, startDay);
            List <DensityDevice> devices   = DensityDbSimulator.CreateDensityDevice(TestInit.ServiceProvider, 1, 1, 1, "", true);

            TestInit.RefreshDensityCache(devices);
            EventsController service = new EventsController(TestInit.ServiceProvider.GetRequiredService <DensityContext>(),
                                                            TestInit.ServiceProvider.GetRequiredService <IMemoryCache>());

            EventDbSimulator.ResetDatabase(TestInit.ServiceProvider);


            using (DensityContext context = TestInit.ServiceProvider.GetRequiredService <DensityContext>())
            {
                foreach (DensityDevice device in devices)
                {
                    foreach (var relation in device.DensityDevice_DensityChannels)
                    {
                        foreach (TrafficRegion region in relation.Channel.Regions)
                        {
                            DateTime time = startDate;
                            //添加一个持续长度满足10分钟
                            AddDuration(context, region, time, 10);

                            //添加连续3次 总长
                            time = startDate.AddHours(1);
                            AddInterval(context, region, time, 5, 3, 3);

                            //10分钟关联前后5分钟
                            time = startDate.AddHours(2);
                            time = AddDuration(context, region, time, 5);
                            time = time.AddMinutes(3);
                            time = AddDuration(context, region, time, 10);
                            time = time.AddMinutes(3);
                            AddDuration(context, region, time, 5);

                            //交集 5分钟持续三次+10分钟
                            time = startDate.AddHours(3);
                            time = AddInterval(context, region, time, 5, 3, 3);
                            time = time.AddMinutes(3);
                            AddDuration(context, region, time, 10);
                        }
                    }
                }
                context.BulkSaveChanges(options => options.BatchSize = 1000);
                foreach (DensityDevice device in devices)
                {
                    foreach (var relation in device.DensityDevice_DensityChannels)
                    {
                        foreach (TrafficRegion region in relation.Channel.Regions)
                        {
                            var list = service.AnalysisIncidence(region.DataId, startDate, startDate);
                            Assert.AreEqual(startDate, list[0][0].DateTime);
                            Assert.AreEqual(startDate.AddMinutes(10), list[0][0].EndTime);

                            Assert.AreEqual(startDate.AddHours(1), list[0][1].DateTime);
                            Assert.AreEqual(startDate.AddHours(1).AddMinutes(5 * 3 + 3 * 2), list[0][1].EndTime);

                            Assert.AreEqual(startDate.AddHours(2), list[0][2].DateTime);
                            Assert.AreEqual(startDate.AddHours(2).AddMinutes(5 + 3 + 10 + 3 + 5), list[0][2].EndTime);

                            Assert.AreEqual(startDate.AddHours(3), list[0][3].DateTime);
                            Assert.AreEqual(startDate.AddHours(3).AddMinutes(5 * 3 + 3 * 2 + 3 + 10), list[0][3].EndTime);
                        }
                    }
                }
            }
        }
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="context">数据库实例</param>
 /// <param name="logger">日志</param>
 public RoadCrossingsManager(DensityContext context, ILogger <RoadCrossingsController> logger)
 {
     _context = context;
     _logger  = logger;
 }
Beispiel #26
0
 /// <summary>
 /// 数据库实例
 /// </summary>
 /// <param name="context">数据库实例</param>
 /// <param name="memoryCache">缓存</param>
 /// <param name="logger">日志</param>
 public DevicesManager(DensityContext context, IMemoryCache memoryCache, ILogger <DevicesManager> logger)
 {
     _context     = context;
     _memoryCache = memoryCache;
     _logger      = logger;
 }