Compare commits

..

21 Commits

Author SHA1 Message Date
yanghongwei 90b3bc70ec 细节调整 2025-09-20 17:21:03 +08:00
yanghongwei e479ee3337 bug调整 2025-09-20 16:29:21 +08:00
yanghongwei a61dfeddb0 细节调整 2025-09-11 00:51:53 +08:00
yanghongwei 5fb29db7e9 细节调整 2025-09-11 00:12:48 +08:00
yanghongwei 1175c776bf 设备状态调整 2025-09-11 00:01:46 +08:00
yanghongwei a474ded6a1 设备列表加入是否在线 2025-08-27 22:06:49 +08:00
yanghongwei 5122193a28 白名单 调整 2025-08-27 21:46:05 +08:00
yanghongwei 9653eb6f18 细节调整 2025-08-26 15:12:26 +08:00
yanghongwei 1c9a4afcbc 细节调整,上传批次按sn来 分组 2025-08-24 16:32:14 +08:00
yanghongwei 48b4d35672 细节调整 2025-08-23 01:33:25 +08:00
yanghongwei 25b9d20cb3 细节调整 2025-08-23 01:32:07 +08:00
yanghongwei 7574049a3f 细节调整 2025-08-23 01:28:34 +08:00
yanghongwei 6fab2df9fb 细节调整 2025-08-23 01:06:19 +08:00
yanghongwei b8279ad728 细节调整,预警列表,字段新加白名单,预警等级 2025-08-22 16:50:41 +08:00
yanghongwei dceaf4e424 细节调整 2025-08-20 22:46:00 +08:00
yanghongwei 83df6abc46 首页缓存计算时长调整 2025-08-16 17:33:02 +08:00
yanghongwei f94bdcc506 细节调整 2025-08-16 15:34:19 +08:00
yanghongwei 97b9cc06dc 0换成1 2025-08-16 15:32:57 +08:00
yanghongwei b389dcbf30 细节调整 2025-07-21 17:33:13 +08:00
yanghongwei 965f987086 分页细节调整 2025-07-21 17:32:05 +08:00
yanghongwei 45c19fcdf9 白名单调整 2025-07-09 20:47:01 +08:00
18 changed files with 103 additions and 252 deletions

23
Common/DateTimeHelper.cs Normal file
View File

@ -0,0 +1,23 @@
namespace LY.App.Common
{
/// <summary>
/// 日期时间帮助类
/// </summary>
public static class DateTimeHelper
{
/// <summary>
/// //当前剩余秒数
/// </summary>
/// <returns></returns>
public static int GetRemainSeconds()
{
// 当前时间
DateTime now = DateTime.Now;
// 当天结束时间23:59:59.999
DateTime endOfDay = now.Date.AddDays(1).AddTicks(-1);
int remainSeconds = (int)(endOfDay - DateTime.Now).TotalSeconds;
return remainSeconds;
}
}
}

View File

@ -56,13 +56,5 @@
{
return $"white_list{sn}";
}
/// <summary>
/// 所有用户位置
/// </summary>
/// <returns></returns>
public static string UserLocation(long userId)
{
return $"user_locationbyid_{userId}";
}
}
}

View File

@ -10,7 +10,6 @@ namespace LY.App.Common.Redis
public class RedisService
{
private readonly IDatabase _db;
private readonly IServer _redis;
/// <summary>
/// 构造函数
@ -39,82 +38,44 @@ namespace LY.App.Common.Redis
string jsonData = await _db.StringGetAsync(key);
return jsonData is not null ? JsonSerializer.Deserialize<T>(jsonData) : default;
}
/// <summary>
/// 模糊 查询所有 Key
/// 删除 Key
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
public Task<List<RedisKey>> GetAllKeysAsync(string pattern)
public async Task<bool> DeleteAsync(string key)
{
var redis = _db.Multiplexer;
var keys = new List<RedisKey>();
foreach (var endPoint in redis.GetEndPoints())
{
var server = redis.GetServer(endPoint);
if (!server.IsConnected)
continue;
// 使用 SCAN 获取匹配的 key避免 KEYS 阻塞
var scanKeys = server.Keys(pattern: pattern, pageSize: 1000);
keys.AddRange(scanKeys);
}
return Task.FromResult(keys);
//var result = new Dictionary<string, string>();
//if (keys.Count > 0)
//{
// // 一次批量获取 value
// var values = await _db.StringGetAsync(keys.ToArray());
// for (int i = 0; i < keys.Count; i++)
// {
// if (values[i].HasValue)
// {
// result[keys[i]] = values[i];
// }
// }
//}
//return result;
return await _db.KeyDeleteAsync(key);
}
/// <summary>
/// 删除 Key
/// </summary>
public async Task<bool> DeleteAsync(string key)
{
return await _db.KeyDeleteAsync(key);
}
/// <summary>
/// 检查 Key 是否存在
/// </summary>
public async Task<bool> ExistsAsync(string key)
/// <summary>
/// 检查 Key 是否存在
/// </summary>
public async Task<bool> ExistsAsync(string key)
{
return await _db.KeyExistsAsync(key);
}
/// <summary>
/// 获取数据,如果不存在则从数据源获取并存入 Redis
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="key">Redis Key</param>
/// <param name="factory">数据源方法</param>
/// <param name="expiry">可选的过期时间</param>
/// <returns>获取到的值</returns>
public async Task<T?> GetOrSetAsync<T>(string key, Func<Task<T>> factory, TimeSpan? expiry = null)
{
var value = await GetAsync<T>(key);
if (value is not null)
{
return await _db.KeyExistsAsync(key);
}
/// <summary>
/// 获取数据,如果不存在则从数据源获取并存入 Redis
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="key">Redis Key</param>
/// <param name="factory">数据源方法</param>
/// <param name="expiry">可选的过期时间</param>
/// <returns>获取到的值</returns>
public async Task<T?> GetOrSetAsync<T>(string key, Func<Task<T>> factory, TimeSpan? expiry = null)
{
var value = await GetAsync<T>(key);
if (value is not null)
{
return value;
}
value = await factory();
if (value is not null)
{
await SetAsync(key, value, expiry);
}
return value;
}
value = await factory();
if (value is not null)
{
await SetAsync(key, value, expiry);
}
return value;
}
}
}

View File

@ -28,8 +28,9 @@ namespace LY.App.Controllers
var result = await _alarmService.CreateHistoryPage(input);
return Ok(result);
}
/// <summary>
///列表快速分页
///列表
/// </summary>
/// <param name="input"></param>
/// <returns></returns>

View File

@ -1,11 +1,10 @@
using LY.App.Common.Redis;
using LY.App.Common;
using LY.App.Common.Redis;
using LY.App.Device;
using LY.App.Model;
using LY.App.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;
using System.Reactive.Joins;
namespace LY.App.Controllers
{
@ -50,58 +49,17 @@ namespace LY.App.Controllers
var positions = await _positionService.Index();
var alarmCount = await _redisService.GetOrSetAsync(RedisKeyList.index_data(),
async () => await _alarmService.IndexCount(),
TimeSpan.FromSeconds(GetLeftTime()));
TimeSpan.FromSeconds(DateTimeHelper.GetRemainSeconds()));
var weather = await _redisService.GetOrSetAsync(RedisKeyList.Index_Weather,
async () => await _weatherService.GetWeather(),
TimeSpan.FromHours(3));
var data = await GetUserLocation();
TimeSpan.FromHours(3));
result.data = new
{
positions,
alarmCount,
weather,
userLocation = data
weather
};
return Ok(result);
}
private int GetLeftTime() {
DateTime now = DateTime.Now;
// 今天的结束时间 23:59:59
DateTime endOfDay = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
// 相差时间
TimeSpan remaining = endOfDay - now;
// 剩余秒数
return (int)remaining.TotalSeconds;
}
private async Task<List<SyncLocation>> GetUserLocation()
{
var keys = await _redisService.GetAllKeysAsync("user_locationbyid_*");
List<SyncLocation> result = new List<SyncLocation>();
if (keys.Count > 0)
{
foreach (var item in keys)
{
result.Add(await _redisService.GetAsync<SyncLocation>(item));
}
}
return result;
}
/// <summary>
/// 同步移动端位置信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost("syncLocation")]
public async Task<IActionResult> SyncLocation(SyncLocation input)
{
string key = RedisKeyList.UserLocation(input.userId);
await _redisService.SetAsync(key, new SyncLocation() { userId = input.userId, lat = input.lat, lon = input.lon }, TimeSpan.FromMinutes(1));
return Ok(new ApiResult());
}
}
}

View File

@ -1,5 +1,4 @@
using GraphQL;
using LY.App.Model;
using LY.App.Model;
using LY.App.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@ -24,18 +23,7 @@ namespace LY.App.Controllers
[HttpGet("list")]
public async Task<IActionResult> Get([FromQuery] PositionQueryInput input)
{
var positions = await _positionService.GetList(input);
return Ok(positions);
}
/// <summary>
/// 登陆 后获取当前防区
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpPost("Details")]
public async Task<IActionResult> detail(IEnumerable<long> ids)
{
var positions = await _positionService.Detail(ids);
var positions =await _positionService.GetList(input);
return Ok(positions);
}
/// <summary>

View File

@ -331,7 +331,7 @@ namespace LY.App.Device
private async Task HandleDeviceConnection(Device device)
{
int retryDelay = 1000; // 初始重连间隔1秒
int retryDelay = 10000; // 初始重连间隔1秒
int maxDelay = 30000; // 最大重连间隔30秒
var _log = ServiceLocator.Instance.GetService<LogService>();
await _log?.AddLog(new AddLog { Message = $"设备 {device.Id} 掉线,重新连接中...", Parameters = "", StackTrace = "", url = "" });

View File

@ -51,12 +51,6 @@ namespace LY.App.Model
[SugarColumn(ColumnName = "is_whitelist", ColumnDescription = "是否白名单")]
public bool IsWhitelist { get; set; }
/// <summary>
/// 白名单id
/// </summary>
[JsonConverter(typeof(ValueToStringConverter))]
[SugarColumn(IsIgnore = true)]
public long WhiteListId { get; set; }
/// <summary>
/// ,#东向速度
/// </summary>
public double speed_E { get; set; }

View File

@ -37,7 +37,6 @@
/// 每页条数
/// </summary>
public int pageSize { get; set; } = 10;
public long? positionId { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using LY.App.Device;
using GraphQL;
using LY.App.Device;
using Newtonsoft.Json;
using SqlSugar;
@ -75,6 +76,8 @@ namespace LY.App.Model
[SugarColumn(ColumnName = "is_move", ColumnDescription = "是否移动设备", IsNullable = true)]
public bool isMove { get; set; }
[SugarColumn(IsIgnore = true)]
public bool online { get; set; }
}

View File

@ -1,20 +0,0 @@
namespace LY.App.Model
{
/// <summary>
/// 移动端同步坐标信息
/// </summary>
public class SyncLocation
{
public long userId { get; set; }
public double lon { get; set; }
public double lat { get; set; }
}
/// <summary>
/// web 端同步坐标信息
/// </summary>
public class Location
{
public double lon { get; set; }
public double lat { get; set; }
}
}

View File

@ -41,16 +41,6 @@ namespace LY.App.Model
/// 是否管理员,如果不是管理员,不可操作
/// </summary>
public bool IsAdmin { get; set; }
/// <summary>
/// 用户关键防区数组
/// </summary>
[SugarColumn(ColumnName = "position_id", ColumnDescription = "阵地ids", IsJson = true)]
public List<string> positionId { get; set; }
[SugarColumn(IsIgnore = true)]
/// <summary>
/// 用户关键防区名称数组
/// </summary>
public List<string> positionName { get; set; }
}
public class AddUser
{
@ -66,9 +56,8 @@ namespace LY.App.Model
/// 是否管理员,如果不是管理员,不可操作
/// </summary>
public bool IsAdmin { get; set; }
public List<long> positionId { get; set; }
}
public class UpdateUser : AddUser
public class UpdateUser:AddUser
{
public long Id { get; set; }
}

View File

@ -25,14 +25,16 @@ namespace LY.App.Model
public List<long> positionId { get; set; }
[SugarColumn(IsIgnore = true)]
public List<string> positionIds { get; set; }
/// <summary>
/// 所属单位
/// </summary>
[SugarColumn(IsNullable = true)]
public string company { get; set; }
/// <summary>
/// 备注
/// </summary>
public string mark { get; set; }
/// <summary>
/// 创建人
/// </summary>
public string createBy { get; set; }
}
public class AddWhitelist
@ -69,6 +71,10 @@ namespace LY.App.Model
/// 备注
/// </summary>
public string mark { get; set; }
/// <summary>
/// 创建人
/// </summary>
public string createBy { get; set; }
}
public class UpdateWhitelist : AddWhitelist

View File

@ -7,7 +7,8 @@ using Mapster;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
using SqlSugar;
using System.ComponentModel.DataAnnotations;
using StackExchange.Redis;
using System.Text;
namespace LY.App.Service
{
@ -75,9 +76,7 @@ namespace LY.App.Service
item.PostionName = deviceinfo.PositionName;
item.Time = input.time;
item.distance = GisHelper.HaversineDistance(item.drone_lat, item.drone_lon, item.app_lat, item.app_lon);
var temp = await Iswhitlist(item.serial_number, item.drone_lat, item.drone_lon);
item.IsWhitelist = temp.Item1;
item.WhiteListId = temp.Item2;
item.IsWhitelist = await Iswhitlist(item.serial_number, item.drone_lat, item.drone_lon);
item.alarmLevel = item.IsWhitelist == true ? 0 : await GetAlarmLevel(deviceinfo.PositionId, item.drone_lon, item.drone_lat);
item.centerdistance = await GetCenterDistance(item.drone_lat, item.drone_lon, item.positionId);
}
@ -141,7 +140,7 @@ namespace LY.App.Service
/// <param name="lat"></param>
/// <param name="lon"></param>
/// <returns></returns>
private async Task<Tuple<bool, long>> Iswhitlist(string serial_number, double lat, double lon)
private async Task<bool> Iswhitlist(string serial_number, double lat, double lon)
{
string key = RedisKeyList.white_list(serial_number);
if (await _redisService.ExistsAsync(key))
@ -150,15 +149,14 @@ namespace LY.App.Service
//判断时间是否在区在
if (entity.allDay)
{
return new Tuple<bool, long>(true, entity.Id);
return true;
}
else
{
var has = entity.startTime <= DateTime.Now && DateTime.Now <= entity.endTime;
return new Tuple<bool, long>(has, has ? entity.Id : 0);
return entity.startTime <= DateTime.Now && DateTime.Now <= entity.endTime;
}
}
return new Tuple<bool, long>(false, 0); ;
return false;
}
static bool IsPointInGeoJson(double latitude, double longitude, string geoJson)
@ -361,49 +359,32 @@ namespace LY.App.Service
{
RefAsync<int> total = 0;
var items = await _db.Queryable<Alarm>().SplitTable()
.WhereIF(input.positionId.HasValue, st => st.positionId == input.positionId.Value)
// .WhereIF(input.Frequency.HasValue, st => st.freq == input.Frequency.Value)
.WhereIF(input.Frequency.HasValue, st => st.freq == input.Frequency.Value)
.WhereIF(!string.IsNullOrEmpty(input.sn), s => s.serial_number.Contains(input.sn))
.WhereIF(!string.IsNullOrEmpty(input.model), st => st.device_type == input.model)
.WhereIF(input.strartDate.HasValue, st => st.CreateTime >= input.strartDate.Value)
.WhereIF(input.endDate.HasValue, st => st.CreateTime <= input.endDate.Value.AddDays(1))
.OrderBy(s => s.BatchId, OrderByType.Desc)
.GroupBy(s => new { s.BatchId, s.serial_number, s.device_type })
.GroupBy(s => new { s.BatchId, s.serial_number, s.device_type, s.positionId, s.PostionName, s.freq })
.Select(st => new AlarmRepDto
{
batchId = st.BatchId.ToString(),
startTime = SqlFunc.AggregateMin(st.CreateTime),
endTime = SqlFunc.AggregateMax(st.CreateTime),
sn = st.serial_number,
Frequency = SqlFunc.AggregateMax(st.freq),
Frequency = st.freq,
duration = (SqlFunc.AggregateMax(st.CreateTime) - SqlFunc.AggregateMin(st.CreateTime)).TotalSeconds,
model = st.device_type,
positionId = SqlFunc.AggregateMax(st.positionId),
positionId = st.positionId,
positionName = st.PostionName
}).MergeTable()//合并查询
.ToPageListAsync(input.pageNum, input.pageSize, total);
var ids = items.Select(s => s.positionId).Distinct().ToList();
var positionNames = await _db.Queryable<PositionInfo>()
.Where(s => ids.Contains(s.Id))
.Select(s => new { s.Id, s.Name })
.ToListAsync();
foreach (var item in items)
{
var positionName = positionNames.FirstOrDefault(s => s.Id == item.positionId)?.Name;
if (!string.IsNullOrEmpty(positionName))
{
item.positionName = positionName;
}
}
return Tuple.Create(total.Value, items);
}
/// <summary>
/// 快速分页
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<ApiResult> CreateHistoryPage(AlarmReq input)
{
var tables = _db.SplitHelper<Alarm>().GetTables();
string coutsql = @" SELECT COUNT(*)
FROM (
SELECT batch_id
@ -422,15 +403,15 @@ namespace LY.App.Service
GROUP BY batch_id ORDER BY batch_id desc LIMIT {1},{2}
) AS CountTable ";
string tablesql = string.Join(" UNION ALL ", tables.Select(item => $"SELECT batch_id FROM {item.TableName} GROUP BY batch_id"));
string tablesql = string.Join(" UNION ALL ", tables.Select(item => $"SELECT batch_id FROM {item.TableName} GROUP BY batch_id "));
if (!string.IsNullOrEmpty(input.sn))
{
tablesql = string.Join(" UNION ALL ", tables.Select(item => $"SELECT batch_id FROM {item.TableName} where serial_number like '%{input.sn}%' GROUP BY batch_id"));
tablesql = string.Join(" UNION ALL ", tables.Select(item => $"SELECT batch_id FROM {item.TableName} where serial_number like '%{input.sn}%' GROUP BY batch_id"));
}
var pageitem = await _db.Ado.SqlQueryAsync<int, long>(string.Format(coutsql, tablesql) + string.Format(page, tablesql, (input.pageNum - 1) * input.pageSize, input.pageSize));
var temp = await _db.Queryable<Alarm>()
.Where(s => pageitem.Item2.Contains(s.BatchId)).SplitTable().Select(s => new { s.BatchId, s.freq, s.Id, s.positionId, s.PostionName, s.alarmLevel, s.device_type }).ToListAsync();
.Where(s => pageitem.Item2.Contains(s.BatchId)).SplitTable().Select(s => new { s.BatchId, s.freq, s.Id, s.positionId, s.PostionName, s.alarmLevel, s.device_type }).ToListAsync();
var query = await _db.Queryable<Alarm>()
@ -442,7 +423,6 @@ namespace LY.App.Service
startTime = SqlFunc.AggregateMin(st.CreateTime),
endTime = SqlFunc.AggregateMax(st.CreateTime),
sn = st.serial_number,
Frequency = 0,
duration = (SqlFunc.AggregateMax(st.CreateTime) - SqlFunc.AggregateMin(st.CreateTime)).TotalSeconds,
IsWhitelist = SqlFunc.AggregateMax(st.IsWhitelist),
}).OrderByDescending(s => s.batchId).ToListAsync();
@ -455,8 +435,7 @@ namespace LY.App.Service
s.positionName = temp.Where(m => m.BatchId == long.Parse(s.batchId)).OrderByDescending(o => o.Id).FirstOrDefault().PostionName;
s.alarmLevel = temp.Where(m => m.BatchId == long.Parse(s.batchId)).Any(o => o.alarmLevel == 1) ? 1 : 0;
s.model = temp.Where(m => m.BatchId == long.Parse(s.batchId)).OrderByDescending(o => o.Id).FirstOrDefault().device_type;
});
return new ApiResult()
}); return new ApiResult()
{
code = 0,
data = new

View File

@ -47,6 +47,10 @@ namespace LY.App.Service
.WhereIF(!string.IsNullOrEmpty(key), s => s.Name.Contains(key) || s.DeviceSN.Contains(key))
.OrderByDescending(s => s.Id)
.ToPageListAsync(pageNum, pageSize, total);
foreach (var item in items)
{
item.online = await _redisService.ExistsAsync(RedisKeyList.DeviceStatus(item.DeviceSN));
}
return new ApiResult()
{
data = new

View File

@ -109,27 +109,11 @@ namespace LY.App.Service
var entity = await _db.Queryable<PositionInfo>().FirstAsync(a => a.Id == id && a.IsDeleted != true);
if (entity != null)
{
entity.SetRegionJson();
return new ApiResult() { data = entity };
}
return new ApiResult(false, "未找到要获取的对象");
}
/// <summary>
/// Details
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<ApiResult> Detail(IEnumerable<long> ids)
{
var entity = await _db.Queryable<PositionInfo>()
.Where(a => ids.Contains(a.Id) && a.IsDeleted != true).ToListAsync();
entity.ForEach(a =>
{
a.SetRegionJson();
});
return new ApiResult() { data = entity };
}
/// <summary>
/// 获取列表
/// </summary>
/// <param name="input"></param>

View File

@ -142,17 +142,15 @@ namespace LY.App.Service
//加入redis
await _redisService.SetAsync<string>(RedisKeyList.TokenUser(input.username),
token, TimeSpan.FromSeconds(60 * 60 * 24 * 7));
var positionIds = entity.positionId?.Select(s => s.ToString()).ToList();
return new ApiResult()
{
code = 1,
data = new
{
token,
expires = DateTime.UtcNow.AddSeconds(60 * 60 * 24 * 7),
expires = DateTime.UtcNow.AddSeconds(60*60*24*7),
isAdmin = entity.IsAdmin,
userid = entity.Id.ToString(),
positionIds
userid = entity.Id.ToString()
}
};
}
@ -208,13 +206,6 @@ namespace LY.App.Service
.WhereIF(!string.IsNullOrEmpty(key), s => s.Name.Contains(key))
.OrderBy(s => s.Id)
.ToPageListAsync(pageNum, pageSize, total);
query.ForEach(s =>
{
if (s.positionId is not null && s.positionId.Any())
{
s.positionName = _db.Queryable<PositionInfo>().Where(p => s.positionId.Contains(p.Id.ToString())).Select(p => p.Name).ToList();
}
});
return new
{
total = total.Value,
@ -251,8 +242,7 @@ namespace LY.App.Service
var entity = input.Adapt<UserEntity>();
await _db.Updateable(entity).UpdateColumns(it => new
{
it.IsAdmin,
it.positionId
it.IsAdmin
}).ExecuteCommandAsync();
return null;
}

View File

@ -8,7 +8,7 @@
"log2db": true, //
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "server=110.42.35.89;port=13306;database=lyapp;user=root;password=dklymysql;Pooling=true;"
"DefaultConnection": "server=114.66.57.139;port=13306;database=lyapp;user=root;password=dklymysql;Pooling=true;"
},
"Token": {
"SecretKey": "HWLSNPM+OhlFe4wwEV/teSWsxGjrWbxKnHonxW5Z+mFlQq3zonv5",