修改开启算法

main
zhangbin 2025-12-16 13:54:22 +08:00
parent 504c3af0ad
commit 5a61125038
6 changed files with 267 additions and 35 deletions

View File

@ -1,10 +1,3 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Drawing;
using System.Dynamic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using Infrastructure.Cache;
using Infrastructure.CloudSdk;
@ -20,6 +13,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.BasicQueryService;
using OpenAuth.App.Interface;
@ -34,6 +28,15 @@ using OpenAuth.Repository.Domain;
using OpenAuth.WebApi;
using OpenAuth.WebApi.CloudSdk;
using SqlSugar;
using StackExchange.Redis;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Drawing;
using System.Dynamic;
using System.Net;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Directory = System.IO.Directory;
using RangeHeaderValue = System.Net.Http.Headers.RangeHeaderValue;
@ -2530,7 +2533,7 @@ namespace OpenAuth.App.ServiceApp
};
}
public async Task<Response<bool>> CallAiModel(CallAiModel req)
public async Task<Response<bool>> CallAiModelOld(CallAiModel req)
{
_logger.LogDebug("成功调用CallAIModel");
var task = await Repository
@ -2676,6 +2679,180 @@ namespace OpenAuth.App.ServiceApp
};
}
public async Task<Response<bool>> CallAiModel(CallAiModel req)
{
_logger.LogDebug("成功调用CallAIModel");
var task = await Repository
.ChangeRepository<SugarRepositiry<LasaTask>>()
.GetByIdAsync(req.TaskId);
using var db = Repository.AsSugarClient();
try
{
db.Ado.BeginTran();
if (task.FlightTaskType.Equals(1)) // 手飞任务
{
var aiInspection = new LasaAiInspection
{
Id = Guid.NewGuid().ToString(),
TaskId = req.TaskId,
AlgoInstanceId = req.AlgoInstanceId,
};
if (!string.IsNullOrEmpty(req.WarningContent))
{
aiInspection.WarningTitle = req.WarningTitle;
}
if (!string.IsNullOrEmpty(req.WarningContent))
{
aiInspection.WarningContent = req.WarningContent;
}
// 关于多次调用问题
var count = await db.Queryable<LasaAiInspection>().Where(x => x.TaskId == req.TaskId).CountAsync();
if (count == 0)
{
// 设置任务智能巡检标识
task.AIInspection = "true";
task.Status = 3; // 表示智能巡检中
await db.Updateable(task).ExecuteCommandAsync();
await db.Insertable(aiInspection).ExecuteCommandAsync();
}
}
else
{
// 计划任务
var aiInspection = await Repository
.ChangeRepository<SugarRepositiry<LasaAiInspection>>()
.AsQueryable().Where(x => x.TaskId == req.TaskId).FirstAsync();
req.AlgoInstanceId = aiInspection.AlgoInstanceId;
}
var algoInstances = await db
.Queryable<LasaAlgoInstance>()
.Where(x => x.Id == req.AlgoInstanceId)
.ToListAsync();
var tagsIds = algoInstances.Select(x => x.Tags).ToList();
// todo 关于存在多个算法的处理 查询多个算法
var algoIds = algoInstances.First().AlgoIds.Split(",").ToArray();
var algos = await db
.Queryable<LasaAlgorithmsRepository>()
.Where(x => algoIds.Contains(x.Id)).ToListAsync();
//创建多模型数据结构
var models = new List<ModelConfig>();
foreach (var algo in algos)
{
// 当前算法对应的 tag
var algoInstance = algoInstances.First(a => a.AlgoIds.Contains(algo.Id));
var tagIds = algoInstance.Tags.Split(",", StringSplitOptions.RemoveEmptyEntries);
var labels = await db.Queryable<LasaModelLabel>()
.Where(l => tagIds.Contains(l.Id) && l.PId == algo.Id)
.ToListAsync();
Dictionary<string, ModelTag> tags = new Dictionary<string, ModelTag>();
foreach (var label in labels)
{
tags[label.EnumValue.ToString()] = new ModelTag
{
name = label.Name,
reliability = label.Reliability,
select = true,
color = new[] { 0, 255, 0 }
};
}
var model = new ModelConfig
{
path = algo.Path,
encryption_key = algo.SecretKey,
tags = tags,
conf_thres = algo.ConfThres,
imgsz = algo.Imgsz,
device = "cuda:0",
line_width = 2,
enabled = algo.Enable
};
models.Add(model);
}
var x = SnowFlakeSingle.instance;
//var pushUrl = $"rtmp://box.wisestcity.com:1935/live/{x.NextId()}";
var config = ConfigHelper.GetConfigRoot();
var pushUrl = config["AIModelApi:PushUrl"];
// 取得无人机sn + 1
if (string.IsNullOrEmpty(req.UavSn))
{
var lasaDronePort = await Repository.AsSugarClient().Queryable<LasaDronePort>()
.LeftJoin<LasaUav>((a, b) => a.Id == b.PId)
.Where((a, b) => a.Id == task.TaskDronePort).Select<dynamic>(
(a, b) => new
{
UavSn = b.Sn,
b.TypeId
}
).FirstAsync();
pushUrl += lasaDronePort.UavSn + "1";
}
else
{
pushUrl += req.UavSn + 1;
}
var reqBody = new StartDetectionResp
{
rtmp_url = req.RtmpUrl,
push_url = pushUrl,
taskname = task.TaskName,
taskid = req.TaskId,
models = models
};
var taskRecord = new LasaTask()
{
Id = req.TaskId,
Status = 6, // 智能巡检状态
PushUrl = pushUrl,
AIInspection = "true",
};
await db.Updateable(taskRecord).IgnoreNullColumns().ExecuteCommandAsync();
_logger.LogDebug($"发送的json:{JsonConvert.SerializeObject(reqBody)}");
var content = new StringContent(JsonConvert.SerializeObject(reqBody), Encoding.UTF8, "application/json");
var url = config["AIModelApi:Url"];
using var httpClient = new HttpClient();
var response = await httpClient.PostAsync($"{url}/api/tasks/creat", content);
//var response = await httpClient.PostAsync("http://192.168.10.131:9025/start_detection", content);
if (response.IsSuccessStatusCode)//低一哦成功记录当前任务数据
{
var responseStr = await response.Content.ReadAsStringAsync();
var root = JsonNode.Parse(responseStr)?.AsObject();
var taskId = root?["data"]?["task_id"]?.ToString();
if (!string.IsNullOrEmpty(taskId))
{
_redisCacheContext.HashSetAsync($"ai:task:{taskId}", new[]{
new HashEntry("TaskId", taskId),
new HashEntry("Status", "running"),
new HashEntry("CreateTime", DateTime.Now.ToString("O"))
});
}
}
_logger.LogDebug($"成功调用{response.IsSuccessStatusCode}");
db.Ado.CommitTran();
}
catch (Exception ex)
{
db.Ado.RollbackTran();
throw ex;
//throw new Exception("调用智能巡检失败");
}
return new Response<bool>()
{
Result = true
};
}
public async Task<Response<dynamic>> EndHandFlyTask(string taskid)
{
var savedTask = await Repository.ChangeRepository<SugarRepositiry<LasaTask>>().AsQueryable()
@ -2919,7 +3096,9 @@ namespace OpenAuth.App.ServiceApp
var url = config["AIModelApi:Url"];
// 结束智能巡检
using var httpClient = new HttpClient();
await httpClient.PostAsync($"{url}/stop_detection", null);
//await httpClient.PostAsync($"{url}/stop_detection", null);
var pytaskid = _redisCacheContext.HashGet($"ai:task:{taskid}", "TaskId").ToString();
await httpClient.PostAsync($"{url}/api/tasks/{pytaskid}/cleanup", null);
db.Ado.CommitTran();
}
catch (Exception ex)

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenAuth.App.ServiceApp.Response
{
public class ModelConfig
{
public string path { get; set; }
public string encryption_key { get; set; }
public Dictionary<string, ModelTag> tags { get; set; }
public double conf_thres { get; set; }
public int imgsz { get; set; }
public string device { get; set; }
public int line_width { get; set; }
public bool enabled { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenAuth.App.ServiceApp.Response
{
public class ModelTag
{
public string name { get; set; }
public double reliability { get; set; }
public bool select { get; set; }
public int[] color { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenAuth.App.ServiceApp.Response
{
public class StartDetectionResp
{
public string rtmp_url { get; set; }
public string push_url { get; set; }
public string taskname { get; set; }
public string taskid { get; set; }
public List<ModelConfig> models { get; set; }
}
}

View File

@ -49,31 +49,31 @@ namespace OpenAuth.WebApi.Model
return;
}
var licensePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "license.lic");
if (File.Exists(licensePath))
{
var licenseManager = new LicenseManager();
if (!licenseManager.ValidateLicense(System.IO.File.ReadAllText(licensePath), out var error))
{
context.HttpContext.Response.StatusCode = 401;
context.Result = new JsonResult(new Response
{
Code = 401,
Message = error
});
return;
}
}
else
{
context.HttpContext.Response.StatusCode = 401;
context.Result = new JsonResult(new Response
{
Code = 401,
Message = "无授权文件"
});
return;
}
//var licensePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "license.lic");
//if (File.Exists(licensePath))
//{
// var licenseManager = new LicenseManager();
// if (!licenseManager.ValidateLicense(System.IO.File.ReadAllText(licensePath), out var error))
// {
// context.HttpContext.Response.StatusCode = 401;
// context.Result = new JsonResult(new Response
// {
// Code = 401,
// Message = error
// });
// return;
// }
//}
//else
//{
// context.HttpContext.Response.StatusCode = 401;
// context.Result = new JsonResult(new Response
// {
// Code = 401,
// Message = "无授权文件"
// });
// return;
//}
var dataAttr = description.MethodInfo.GetCustomAttribute<AllDataAttribute>();
if (dataAttr != null)

View File

@ -88,7 +88,7 @@
"JYMUrl": "E:/低空态势感知/资料/省对接/质检/LandCloud.CGDBPreCheckTool.exe"
},
"AIModelApi": {
"Url": "http://192.168.10.131:9025",
"Url": "http://123.132.248.154:9310",
"PushUrl": "rtmp://192.168.3.17:1935/live/",
"DronePortRtmp": "rtmp://175.27.168.120:6019/live/"
},