ValueController.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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.Environmentally.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.Environmentally.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. IList< DevPointValue> devPoints = new List<DevPointValue>();
  65. try
  66. {
  67. for(int i =0;i< searchModel.names.Length;i++)
  68. {
  69. string name = searchModel.names[i];
  70. string groupname = searchModel.groupnames[i];
  71. string englishname = MqttClientService._mqttDevicePointNameMappingDic[boxNo + groupname + name];
  72. MqttDevicePoint mqttDevicePoint;
  73. MqttClientService._mqttDevicePointDic.TryGetValue(englishname,out mqttDevicePoint);
  74. if (mqttDevicePoint!=null)
  75. devPoints.Add(new DevPointValue {
  76. id = mqttDevicePoint.Id,
  77. timestamp= mqttDevicePoint.UpLoadTime.ToString("yyyy-MM-dd HH:mm:ss"),
  78. dataType = mqttDevicePoint.DataType,
  79. name = mqttDevicePoint.ChineseName,
  80. value = mqttDevicePoint.Value,
  81. status = mqttDevicePoint.BoxStatus,
  82. boxId = mqttDevicePoint.BoxId,
  83. connState="1",
  84. connStateTimestamp = mqttDevicePoint.UpLoadTime.ToString("yyyy-MM-dd HH:mm:ss"),
  85. });
  86. }
  87. return devPoints;
  88. }
  89. catch (Exception ex)
  90. {
  91. //return new ApiResult(ReturnCode.GeneralError, ex.Message);
  92. return null;
  93. }
  94. }
  95. /// <summary>
  96. /// 发送命令到设备
  97. /// </summary>
  98. /// <param name="boxNo"></param>
  99. /// <param name="searchModel"></param>
  100. /// <returns></returns>
  101. [HttpPost("PublishDeviceCommandByAsync")]
  102. public async Task<bool> PublishDeviceCommandByAsync([FromQuery] string boxNo, [FromBody] DeviceCommandModel model)
  103. {
  104. //if (searchModel == null)
  105. //{
  106. // return new ApiResult(ReturnCode.ArgsError);
  107. //}
  108. //searchModel.IsPagination = false;
  109. try
  110. {
  111. Task.Factory.StartNew(async () =>
  112. {
  113. var msg = new MqttApplicationMessage()
  114. {
  115. Topic = model.Topic,
  116. Payload = Encoding.UTF8.GetBytes(model.Command),
  117. QualityOfServiceLevel =
  118. (MqttQualityOfServiceLevel)
  119. Enum.Parse(typeof(MqttQualityOfServiceLevel), MqttQualityOfServiceLevel.AtLeastOnce.ToString()),
  120. Retain = false
  121. };
  122. if (null != MqttClientService._mqttClient)
  123. {
  124. await MqttClientService._mqttClient.PublishAsync(msg);
  125. }
  126. });
  127. return await Task.FromResult(true);
  128. }
  129. catch (Exception ex)
  130. {
  131. //return new ApiResult(ReturnCode.GeneralError, ex.Message);
  132. return await Task.FromResult(false);
  133. }
  134. }
  135. [HttpPost("Get")]
  136. public object Get([FromQuery]string boxNo, [FromBody] QueryModel model)
  137. {
  138. _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\" } ] }");
  139. var jsonConfigs=JsonConvert.DeserializeObject<List<JsonConfig>>(_mqttOptions.JsonConfig);
  140. var message= _memoryCache.Get(boxNo)?.ToString();
  141. if (!string.IsNullOrEmpty(message))
  142. {
  143. MqttMessage mqttMessage = JsonConvert.DeserializeObject<MqttMessage>(message);
  144. var queryAble= jsonConfigs.Join(mqttMessage.Data, a => a.Name, b => b.Name, (a, b) => new { a, b })
  145. //.Where(x => x.a.BoxId == boxNo)
  146. .Select(x => new
  147. {
  148. x.a.Group,
  149. BoxId=boxNo,
  150. x.a.Name,
  151. x.a.DataType,
  152. x.b.Value,
  153. }).AsQueryable();
  154. if (model.Names.Any())
  155. {
  156. queryAble = queryAble.Where(x => model.Names.Contains(x.Name));
  157. }
  158. if (model.Groupnames.Any())
  159. {
  160. queryAble = queryAble.Where(x => model.Groupnames.Contains(x.Group));
  161. }
  162. var result=queryAble.ToList();
  163. return result;
  164. }
  165. return new object();
  166. }
  167. }
  168. }