AIController.cs 16 KB

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