ValueController.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.Extensions.Caching.Memory;
  3. using Microsoft.Extensions.Logging;
  4. using MQTTnet;
  5. using MQTTnet.Protocol;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  8. using Ropin.IOT.MqttService.RequestModel;
  9. using Ropin.Inspection.Model;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Security.Cryptography;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. using System.Xml.Linq;
  17. namespace Ropin.IOT.MqttService.Controllers
  18. {
  19. [ApiController]
  20. [Route("api/[controller]")]
  21. public class ValueController : ControllerBase
  22. {
  23. private readonly ILogger<ValueController> _logger;
  24. private readonly MqttOptions _mqttOptions;
  25. public IMemoryCache _memoryCache;
  26. public ValueController(ILogger<ValueController> logger, IMemoryCache memoryCache, MqttOptions mqttOptions)
  27. {
  28. _logger = logger;
  29. _memoryCache = memoryCache;
  30. _mqttOptions = mqttOptions;
  31. }
  32. public class TdevDevicePointSearchModel
  33. {
  34. public string[] groupnames { get; set; }
  35. public string[] names { get; set; }
  36. public int timeOut { get; set; } = 600;
  37. }
  38. //public class DeviceCommandModel
  39. //{
  40. // public string Topic { get; set; }
  41. // public string Command { get; set; }
  42. // public int timeOut { get; set; } = 600;
  43. //}
  44. public class DevPointValue
  45. {
  46. public string id { get; set; }
  47. public string timestamp { get; set; }
  48. public string dataType { get; set; }
  49. public string name { get; set; }
  50. public string value { get; set; }
  51. public string status { get; set; }
  52. public string boxId { get; set; }
  53. public string connState { get; set; }
  54. public string connStateTimestamp { get; set; }
  55. }
  56. [HttpPost("GetDevicePointByAsync")]
  57. public async Task<IList<DevPointValue>> GetDevicePointByAsync([FromQuery] string boxNo, [FromBody]TdevDevicePointSearchModel searchModel)
  58. {
  59. //if (searchModel == null)
  60. //{
  61. // return new ApiResult(ReturnCode.ArgsError);
  62. //}
  63. //searchModel.IsPagination = false;
  64. if (MqttClientService._mqttDevicePointNameMappingDic == null || MqttClientService._mqttDevicePointDic == null)
  65. {
  66. return null;
  67. }
  68. IList< DevPointValue> devPoints = new List<DevPointValue>();
  69. try
  70. {
  71. for(int i =0;i< searchModel.names.Length;i++)
  72. {
  73. string name = searchModel.names[i];
  74. string groupname = searchModel.groupnames[i];
  75. if (!MqttClientService._mqttDevicePointNameMappingDic.ContainsKey(boxNo + groupname + name))
  76. {
  77. devPoints.Add(null);
  78. continue;
  79. }
  80. string englishname = MqttClientService._mqttDevicePointNameMappingDic[boxNo + groupname + name];
  81. MqttDevicePoint mqttDevicePoint;
  82. MqttClientService._mqttDevicePointDic.TryGetValue(englishname,out mqttDevicePoint);
  83. if (mqttDevicePoint!=null)
  84. devPoints.Add(new DevPointValue {
  85. id = mqttDevicePoint.Id,
  86. timestamp= mqttDevicePoint.UpLoadTime.ToString("yyyy-MM-dd HH:mm:ss"),
  87. dataType = mqttDevicePoint.DataType,
  88. name = mqttDevicePoint.ChineseName,
  89. value = mqttDevicePoint.Value,
  90. status = mqttDevicePoint.BoxStatus,
  91. boxId = mqttDevicePoint.BoxId,
  92. connState="1",
  93. connStateTimestamp = mqttDevicePoint.UpLoadTime.ToString("yyyy-MM-dd HH:mm:ss"),
  94. });
  95. }
  96. return devPoints;
  97. }
  98. catch (Exception ex)
  99. {
  100. //return new ApiResult(ReturnCode.GeneralError, ex.Message);
  101. return null;
  102. }
  103. }
  104. /// <summary>
  105. /// 发送命令到设备
  106. /// </summary>
  107. /// <param name="boxNo"></param>
  108. /// <param name="searchModel"></param>
  109. /// <returns></returns>
  110. [HttpPost("PublishDeviceCommandByAsync")]
  111. public async Task<bool> PublishDeviceCommandByAsync([FromQuery] string boxNo, [FromBody] DeviceCommandModel model)
  112. {
  113. //if (searchModel == null)
  114. //{
  115. // return new ApiResult(ReturnCode.ArgsError);
  116. //}
  117. //searchModel.IsPagination = false;
  118. try
  119. {
  120. Task.Factory.StartNew(async () =>
  121. {
  122. var msg = new MqttApplicationMessage()
  123. {
  124. Topic = model.Topic,
  125. Payload = Encoding.UTF8.GetBytes(model.Command),
  126. QualityOfServiceLevel =
  127. (MqttQualityOfServiceLevel)
  128. Enum.Parse(typeof(MqttQualityOfServiceLevel), MqttQualityOfServiceLevel.AtLeastOnce.ToString()),
  129. Retain = false
  130. };
  131. if (null != MqttClientService._mqttClient)
  132. {
  133. await MqttClientService._mqttClient.PublishAsync(msg);
  134. }
  135. });
  136. return await Task.FromResult(true);
  137. }
  138. catch (Exception ex)
  139. {
  140. //return new ApiResult(ReturnCode.GeneralError, ex.Message);
  141. return await Task.FromResult(false);
  142. }
  143. }
  144. [HttpPost("Get")]
  145. public object Get([FromQuery]string boxNo, [FromBody] QueryModel model)
  146. {
  147. _memoryCache.Set("001", "{\"boxId\": \"001\", \"data\": [ { \"name\": \"gzzs\", \"value\": \"DO1\" }, { \"name\": \"bj\", \"value\": \"DO2\" }, { \"name\": \"zs\", \"value\": \"AI1\" }, { \"name\": \"wd\", \"value\": \"AI2\" }, { \"name\": \"fcnd\", \"value\": \"AI3\" }, { \"name\": \"vocs\", \"value\": \"AI4\" }, { \"name\": \"fs\", \"value\": \"AI5\" }, { \"name\": \"sd\", \"value\": \"AI5\" } ] }");
  148. var jsonConfigs=JsonConvert.DeserializeObject<List<JsonConfig>>(_mqttOptions.JsonConfig);
  149. var message= _memoryCache.Get(boxNo)?.ToString();
  150. if (!string.IsNullOrEmpty(message))
  151. {
  152. MqttMessage mqttMessage = JsonConvert.DeserializeObject<MqttMessage>(message);
  153. var queryAble= jsonConfigs.Join(mqttMessage.Data, a => a.Name, b => b.Name, (a, b) => new { a, b })
  154. //.Where(x => x.a.BoxId == boxNo)
  155. .Select(x => new
  156. {
  157. x.a.Group,
  158. BoxId=boxNo,
  159. x.a.Name,
  160. x.a.DataType,
  161. x.b.Value,
  162. }).AsQueryable();
  163. if (model.Names.Any())
  164. {
  165. queryAble = queryAble.Where(x => model.Names.Contains(x.Name));
  166. }
  167. if (model.Groupnames.Any())
  168. {
  169. queryAble = queryAble.Where(x => model.Groupnames.Contains(x.Group));
  170. }
  171. var result=queryAble.ToList();
  172. return result;
  173. }
  174. return new object();
  175. }
  176. }
  177. }