AIController.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. using Microsoft.AspNetCore.Mvc;
  2. using Ropin.Inspection.Service;
  3. using System.Net.Http;
  4. using Ropin.Inspection.Common.Helper;
  5. using Microsoft.AspNetCore.Authorization;
  6. using Ropin.Inspection.Api.Common;
  7. using System.Threading.Tasks;
  8. using Ropin.Inspection.Model;
  9. using System.Collections.Generic;
  10. using System;
  11. using Newtonsoft.Json;
  12. using Microsoft.Extensions.Configuration;
  13. using Ropin.Inspection.Service.VMC.Interface;
  14. using Newtonsoft.Json.Linq;
  15. using System.IO;
  16. namespace Ropin.Inspection.Api.Controllers.Base
  17. {
  18. public class AIController : BaseController
  19. {
  20. private readonly IHttpClientFactory _httpClientFactory;
  21. private readonly AIProjectHelper aIHelper;
  22. private readonly ITsysMessageService _TsysMessageService;
  23. private readonly IPushMsgService _pushMsgService;
  24. private readonly IVmcCameraService _vmcCameraService;
  25. private string IsUpdateAI = "false";
  26. private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(AIController));
  27. public AIController(IHttpClientFactory httpClientFactory, ITsysMessageService tsysMessageService, IPushMsgService pushMsgService, IConfiguration configuration, IVmcCameraService vmcCameraService)
  28. {
  29. aIHelper = new AIProjectHelper(httpClientFactory);
  30. _TsysMessageService = tsysMessageService;
  31. _pushMsgService = pushMsgService;
  32. string IsUpdate = configuration.GetSection("AIIsUpdate")?.Value;
  33. IsUpdateAI = !string.IsNullOrEmpty(IsUpdate) ? IsUpdate : "false";
  34. _vmcCameraService = vmcCameraService;
  35. }
  36. /// <summary>
  37. /// AI会话
  38. /// </summary>
  39. /// <returns></returns>
  40. [HttpPost("AiConversation")]
  41. [AllowAnonymous]
  42. public async Task<object> AiConversation(AIConversationSearch search)
  43. {
  44. var meg = await aIHelper.AiConversation(search);
  45. return new ApiResult<object>(meg);
  46. }
  47. /// <summary>
  48. /// AI登录
  49. /// </summary>
  50. /// <returns></returns>
  51. [HttpGet("AiLogin")]
  52. [AllowAnonymous]
  53. public async Task<AILoginOutput> AiLogin()
  54. {
  55. var token = await aIHelper.GetToken();
  56. return token;
  57. }
  58. /// <summary>
  59. /// AI-获取历史报警记录
  60. /// </summary>
  61. /// <returns></returns>
  62. [HttpGet("AiHistoricAlmrecord/{Devno}/{Page}/{pageSize}")]
  63. [AllowAnonymous]
  64. public async Task<ApiResult<AISqlSugarPagedList<AlmRecordOutput>>> AiHistoricAlmrecord(string Devno, int Page = 1, int pageSize = 10, long? entityId = null)
  65. {
  66. var data = await aIHelper.GetHistoricAlmrecord(Devno, Page, pageSize, entityId);
  67. return new ApiResult<AISqlSugarPagedList<AlmRecordOutput>>(data, ReturnCode.Success);
  68. }
  69. /// <summary>
  70. /// AI-获取报警处理列表
  71. /// </summary>
  72. /// <returns></returns>
  73. [HttpGet("AiAlmDispose/{Devno}/{Page}/{pageSize}")]
  74. [AllowAnonymous]
  75. public async Task<ApiResult<AISqlSugarPagedList<AlmRecordOutput>>> AiAlmDispose(string Devno, int Page = 1, int pageSize = 10, long? entityId = null)
  76. {
  77. var data = await aIHelper.GetAlmDispose(Devno, Page, pageSize, entityId);
  78. return new ApiResult<AISqlSugarPagedList<AlmRecordOutput>>(data, ReturnCode.Success);
  79. }
  80. /// <summary>
  81. /// AI-报警数据保存到环保消息表数据
  82. /// </summary>
  83. /// <returns></returns>
  84. [HttpGet("AiAlmSaveMessage")]
  85. [AllowAnonymous]
  86. public async Task<ApiResult> AiAlmSaveMessage()
  87. {
  88. //40124884581189;33379713109829
  89. var data = await aIHelper.GetAlmDispose("", 1, 10, 40124884581189);
  90. //var data = await aIHelper.GetHistoricAlmrecord("", 1, 10, 40124884581189);
  91. if (data != null)
  92. {
  93. foreach (var item in data.Items)
  94. {
  95. if (item != null)
  96. {
  97. var textJson = new
  98. {
  99. PanoramaId = item.PanoramaId,
  100. PanoramaUrl = item.PanoramaUrl,
  101. RoiJson = item.RoiJson,
  102. NonRoiJson = item.NonRoiJson,
  103. DetectionFrameJson = item.DetectionFrameJson
  104. };
  105. var datas = JsonConvert.SerializeObject(textJson);
  106. MessageFile messageFile = new MessageFile();
  107. messageFile.Text = datas;
  108. messageFile.Type = "FILE_TYP_006";
  109. string msg = item.Event_Name;
  110. if (string.IsNullOrEmpty(msg))
  111. {
  112. msg = item.Event_Code;
  113. }
  114. TpushMsgModel model = new TpushMsgModel
  115. {
  116. C_DevStoreCode = "d705ceb5-7473-4b19-91dd-d3eff223f05b",
  117. C_MsgTypeCode = "MSG_TYPE_024",
  118. Subject = item.Device_TypeName + "报警",
  119. Msg = msg,
  120. UserName = "AI盒子",
  121. UserMobile = "",
  122. CreateOn = item.StartTime?.ToString("yyyy-MM-dd HH:mm:ss"),
  123. GenerationType = 1,
  124. msgStatus = 1,
  125. FileList = new List<MessageFile> { messageFile }
  126. };
  127. bool bol = await _pushMsgService.PushAlarmMsgAsync(model, model.Subject);
  128. if (bol && IsUpdateAI == "true")
  129. {
  130. DateTime updTime = DateTime.Now;
  131. var updData = new
  132. {
  133. Id = item.Id,
  134. ConfrimContent = "环保测试数据,自动确认",
  135. Mistake = false,
  136. Confirmed = true,
  137. ConfirmTime = updTime,
  138. ConfirmUserName = "环保同步程序",
  139. Closed = true,
  140. CloseContent = "环保测试数据,自动关闭",
  141. EndTime = updTime,
  142. CloseUserName = "环保同步程序"
  143. };
  144. var dataStr = JsonConvert.SerializeObject(updData);
  145. bool result = await aIHelper.UpdateAlm(dataStr);
  146. //bool result = await aIHelper.UpdateAlmIsDelete(item.Id);
  147. }
  148. }
  149. }
  150. }
  151. //TsysMessageSearchModel searchModel = new TsysMessageSearchModel();
  152. //searchModel.IsPagination = true;
  153. //searchModel.C_MsgTypeCode = "MSG_TYPE_024";
  154. //var msgData = await _TsysMessageService.GetConditionAsync(searchModel);
  155. return new ApiResult(ReturnCode.Success);
  156. }
  157. [HttpPost]
  158. [AllowAnonymous]
  159. [Route("/device/business/generalApp/pushData/alarmData/{deviceNo}")]
  160. public async Task<ApiResultModel<object>> AlarmData([FromRoute] string deviceNo, [FromBody] JObject alarmDataModel)
  161. {
  162. try
  163. {
  164. string startupDirectory = Directory.GetCurrentDirectory();
  165. log.Info($"进入AI[/device/business/generalApp/pushData/alarmData/{deviceNo}]");
  166. AlarmDataModel alarmData = JsonConvert.DeserializeObject<AlarmDataModel>(alarmDataModel.ToString());
  167. log.Info("获取deviceNo="+ alarmData.deviceNo);
  168. var devIds = await _vmcCameraService.GetCameraByTDH(alarmData.deviceNo);
  169. log.Info($"获取到的设备ID:【{JsonConvert.SerializeObject(devIds)}】");
  170. var cameraModel = await _vmcCameraService.GetCameraEntity(alarmData.deviceNo);
  171. log.Info($"获取到的摄像头数据:【{JsonConvert.SerializeObject(cameraModel)}】");
  172. int row = 0;
  173. foreach (var x in devIds)
  174. {
  175. List<MessageFile> messageFiles = new List<MessageFile>();
  176. string fileRelativePath = "";
  177. if (!string.IsNullOrEmpty(alarmData.panoramaDataId))
  178. {
  179. try
  180. {
  181. byte[] dataBytes = Convert.FromBase64String(s: alarmData.panoramaDataId);
  182. var relativePath = Path.Combine("wwwroot/uploads/images/", DateTime.Now.ToString("yyyyMM"));
  183. var directoryPath = Path.Combine(startupDirectory, relativePath);
  184. string imgName = $"{alarmData.panoramaId}.png";
  185. fileRelativePath = "/" + Path.Combine(relativePath + "/", imgName);
  186. if (!Directory.Exists(directoryPath))
  187. {
  188. Directory.CreateDirectory(directoryPath);
  189. }
  190. var filePath = Path.Combine(directoryPath + "/", imgName);// 替换为你想要保存的文件路径及名称
  191. using FileStream fs = new FileStream(filePath, FileMode.Create);
  192. fs.Write(dataBytes, 0, dataBytes.Length);
  193. fs.Close();
  194. }
  195. catch (Exception ex)
  196. {
  197. fileRelativePath = "";
  198. log.Info("全景图异常:" + ex.Message);
  199. }
  200. }
  201. var textJson = new
  202. {
  203. PanoramaId = alarmData.panoramaId,
  204. PanoramaUrl = fileRelativePath,//alarmData.panoramaUrl,
  205. RoiJson = alarmData.roiJson,
  206. NonRoiJson = alarmData.nonRoiJson,
  207. DetectionFrameJson = alarmData.detectionFrameJson
  208. };
  209. var datas = JsonConvert.SerializeObject(textJson);
  210. MessageFile messageFile = new MessageFile();
  211. messageFile.Text = datas;
  212. messageFile.Type = "FILE_TYP_006";
  213. messageFiles.Add(messageFile);
  214. TpushMsgModel model = new TpushMsgModel
  215. {
  216. C_DevStoreCode = x,
  217. C_MsgTypeCode = "MSG_TYPE_024",
  218. Subject = cameraModel==null?"AI盒子报警": cameraModel.C_Name+"报警",
  219. Msg = alarmData.alarmTypeChineseName,
  220. UserName = cameraModel == null ? "AI盒子" : cameraModel.C_Name,
  221. UserMobile = "",
  222. CreateOn = alarmData.captureTime,
  223. GenerationType = 1,
  224. msgStatus = 1,
  225. FileList = messageFiles
  226. };
  227. bool bol = await _pushMsgService.PushAlarmMsgAsync(model, model.Subject);
  228. log.Info($"执行发送结果=[{bol}]");
  229. if (bol) { row++; }
  230. }
  231. return ApiResultModel<object>.GetSuccess(row);
  232. }
  233. catch (Exception ex)
  234. {
  235. log.Info("异常:"+ex.Message);
  236. return ApiResultModel<object>.GetSuccess(0);
  237. }
  238. //return await Task.FromResult(ApiResultModel<object>.GetSuccess(new object { }));
  239. }
  240. //[HttpPost]
  241. //[AllowAnonymous]
  242. //[Route("/device/business/generalApp/pushData/alarmData/{deviceNo}")]
  243. //public async Task<ApiResultModel<object>> AlarmData([FromRoute] string deviceNo, AlarmDataModel alarmDataModel)
  244. //{
  245. // Console.WriteLine("进入/device/business/generalApp/pushData/alarmData/" + deviceNo);
  246. // var devIds = await _vmcCameraService.GetCameraByTDH(alarmDataModel.deviceNo);
  247. // int row = 0;
  248. // foreach (var x in devIds)
  249. // {
  250. // List<MessageFile> messageFiles = new List<MessageFile>();
  251. // var textJson = new
  252. // {
  253. // PanoramaId = alarmDataModel.panoramaId,
  254. // PanoramaUrl = alarmDataModel.panoramaUrl,
  255. // RoiJson = alarmDataModel.roiJson,
  256. // NonRoiJson = alarmDataModel.nonRoiJson,
  257. // DetectionFrameJson = alarmDataModel.detectionFrameJson
  258. // };
  259. // var datas = JsonConvert.SerializeObject(textJson);
  260. // MessageFile messageFile = new MessageFile();
  261. // messageFile.Text = datas;
  262. // messageFile.Type = "FILE_TYP_006";
  263. // messageFiles.Add(messageFile);
  264. // TpushMsgModel model = new TpushMsgModel
  265. // {
  266. // C_DevStoreCode = x,
  267. // C_MsgTypeCode = "MSG_TYPE_024",
  268. // Subject = "AI盒子报警",
  269. // Msg = alarmDataModel.alarmType,
  270. // UserName = "AI盒子",
  271. // UserMobile = "",
  272. // CreateOn = alarmDataModel.captureTime,
  273. // GenerationType = 1,
  274. // msgStatus = 1,
  275. // FileList = messageFiles
  276. // };
  277. // bool bol = await _pushMsgService.PushAlarmMsgAsync(model, model.Subject);
  278. // log.Info($"执行发送结果=[{bol}]");
  279. // if (bol) { row++; }
  280. // }
  281. // return ApiResultModel<object>.GetSuccess(row);
  282. // //return await Task.FromResult(ApiResultModel<object>.GetSuccess(new object { }));
  283. //}
  284. /// <summary>
  285. /// 注册
  286. /// </summary>
  287. /// <param name="deviceNo">设备编号</param>
  288. /// <param name="registerModel"></param>
  289. /// <returns></returns>
  290. [HttpPost]
  291. [AllowAnonymous]
  292. [Route("/api/base/deviceServerSdk/register/{deviceNo}")]
  293. public async Task<ApiResultModel<object>> Register([FromRoute] string deviceNo, [FromBody] RegisterModel registerModel)
  294. {
  295. return await Task.FromResult(ApiResultModel<object>.GetSuccess(new object { }));
  296. }
  297. /// <summary>
  298. /// 状态变化
  299. /// </summary>
  300. /// <param name="deviceNo">设备编号</param>
  301. /// <param name="statusChangeModel"></param>
  302. /// <returns></returns>
  303. [HttpPost]
  304. [AllowAnonymous]
  305. [Route("/api/base/deviceServerSdk/statusChange/{deviceNo}")]
  306. public async Task<ApiResultModel<object>> StatusChange([FromRoute] string deviceNo, [FromBody] StatusChangeModel statusChangeModel)
  307. {
  308. return await Task.FromResult(ApiResultModel<object>.GetSuccess(new object { }));
  309. }
  310. /// <summary>
  311. /// 心跳
  312. /// </summary>
  313. /// <param name="heartbeatModel"></param>
  314. /// <returns></returns>
  315. [HttpPost]
  316. [AllowAnonymous]
  317. [Route("/api/base/deviceServerSdk/heartbeat")]
  318. public async Task<ApiResultModel<object>> Heartbeat([FromBody] HeartbeatModel heartbeatModel)
  319. {
  320. return await Task.FromResult(ApiResultModel<object>.GetSuccess(new object { }));
  321. }
  322. }
  323. public class RegisterModel
  324. {
  325. public string username { get; set; }
  326. public string password { get; set; }
  327. }
  328. public class StatusChangeModel
  329. {
  330. public int status { get; set; }
  331. }
  332. public class HeartbeatModel
  333. {
  334. public DateTime startTime { get; set; }
  335. }
  336. /// <summary>
  337. /// api结果模型
  338. /// </summary>
  339. public class ApiResultModel
  340. {
  341. /// <summary>
  342. /// api状态枚举
  343. /// </summary>
  344. public int Code { get; set; }
  345. /// <summary>
  346. /// 成功、错误消息
  347. /// </summary>
  348. public string? Msg { get; set; }
  349. }
  350. /// <summary>
  351. /// api结果模型,带着数据
  352. /// </summary>
  353. /// <typeparam name="T"></typeparam>
  354. public class ApiResultModel<T> : ApiResultModel where T : new()
  355. {
  356. /// <summary>
  357. /// 返回数据
  358. /// </summary>
  359. public T? Data { get; set; }
  360. /// <summary>
  361. /// 获取成功返回对象
  362. /// </summary>
  363. /// <param name="data">返回数据</param>
  364. /// <returns></returns>
  365. public static ApiResultModel<T> GetSuccess(T data)
  366. {
  367. ApiResultModel<T> apiResult = new ApiResultModel<T>();
  368. apiResult.Data = data;
  369. apiResult.Code = 0;
  370. apiResult.Msg = "成功";
  371. return apiResult;
  372. }
  373. }
  374. }