颐和api

PLCAddrInfoController.cs 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.Extensions.Caching.Distributed;
  8. using Microsoft.Extensions.Logging;
  9. using MadRunFabric.Common;
  10. using PLCAutomationApi.IRepositories;
  11. using MadRunFabric.Model.PLCAutomationApi;
  12. using MongoDB.Driver;
  13. using PLCAutomationApi.Repositories;
  14. namespace PLCAutomationApi.Controllers
  15. {
  16. [Produces("application/json")]
  17. [Route("api/[controller]")]
  18. public class PLCAddrInfoController : BaseController
  19. {
  20. private readonly ILogger<PLCAddrInfoController> _logger;
  21. private readonly IPLCAddrRepository _plc_addrRepository;
  22. private readonly IDistributedCache _cache;
  23. private readonly IPLC_IPManageRepository _ipmanageRepository;
  24. private readonly IPLC_AccessRecordsRepository _plc_recordsRepository;
  25. public PLCAddrInfoController(ILogger<PLCAddrInfoController> logger, IPLCAddrRepository plc_addrRepository,
  26. IDistributedCache cache, IPLC_IPManageRepository ipmanageRepository, IPLC_AccessRecordsRepository plc_recordsRepository)
  27. {
  28. _logger = logger;
  29. _plc_addrRepository = plc_addrRepository;
  30. _cache = cache;
  31. _ipmanageRepository = ipmanageRepository;
  32. _plc_recordsRepository = plc_recordsRepository;
  33. }
  34. public IActionResult Index()
  35. {
  36. return Success("plc读取测试");
  37. //return View();
  38. }
  39. /// <summary>
  40. /// 上传文件并导入数据库
  41. /// </summary>
  42. /// <returns></returns>
  43. [HttpPost("importexcel")]
  44. public async Task<IActionResult> ImportExcel(int headrow = 0)
  45. {
  46. //if (string.IsNullOrEmpty(taskid))
  47. // return Error("任务id不能为空");
  48. Microsoft.AspNetCore.Http.IFormFile _upfile = Request.Form.Files[0];
  49. if (!_upfile.ContentType.Equals("application/vnd.ms-excel") && !_upfile.ContentType.Equals("application/x-xls") && !_upfile.ContentType.Equals("application/x-xlsx") && !_upfile.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !_upfile.ContentType.Equals("application/octet-stream"))
  50. return Error($"请正确上传Excel文件:file.ContentType={_upfile.ContentType}");
  51. NPOIHelper npoi = new NPOIHelper();
  52. var dtExcel = npoi.ExcelToTable1(_upfile, headrow);
  53. int num = dtExcel.Rows.Count;
  54. var cols = dtExcel.Columns;
  55. int colnum = cols.Count;
  56. string dbkeys = "equipnum,addr,type,isdelete,note";// _configuration["upload:acotdbkeys"].ToString();
  57. string[] dbcols = dbkeys.Split(",");
  58. string errmsg = string.Empty;
  59. if (num > 0)
  60. {
  61. int index = 1;
  62. foreach (System.Data.DataRow dr in dtExcel.Rows)
  63. {
  64. var model = new PLCAddr();
  65. /*model.taskid = taskid;
  66. //model.cusname = dr.cusname;
  67. //model.phone = dr.phone;
  68. //model.cusaddr = dr.cusaddr;
  69. model.createtime = DateTime.Now.ToLocalTime();
  70. model.deleteflag = 0;*/
  71. var dbcolslist = dbcols.ToList();
  72. Type t = model.GetType();
  73. PropertyInfo[] PropertyList = t.GetProperties();
  74. foreach (PropertyInfo item in PropertyList)
  75. {
  76. if (dbcolslist.Contains(item.Name))
  77. {
  78. object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
  79. item.SetValue(model, v, null);
  80. }
  81. }
  82. bool b = await _plc_addrRepository.Add(model);
  83. if (!b)
  84. {
  85. if (!string.IsNullOrEmpty(errmsg))
  86. {
  87. errmsg = errmsg + "\r\n第" + index + "行导入失败!";
  88. }
  89. else
  90. {
  91. errmsg = "第" + index + "行导入失败!";
  92. }
  93. }
  94. index++;
  95. }
  96. }
  97. else
  98. {
  99. return Error("文件中无数据");
  100. }
  101. if (!string.IsNullOrEmpty(errmsg))
  102. {
  103. //删除已导入的部分
  104. return Error(errmsg);
  105. }
  106. return Success("导入成功");
  107. }
  108. /// <summary>
  109. /// 从redis缓存中获取设备信息
  110. /// </summary>
  111. /// <param name="equipnum"></param>
  112. /// /// <param name="note"></param>
  113. /// <returns></returns>
  114. [HttpGet("getplcvalue")]
  115. public async Task<IActionResult> GetPLCValueAsync(string ipaddress, string macaddress,string equipnum = "",string note="")
  116. {
  117. #region 参数检查
  118. if (string.IsNullOrWhiteSpace(equipnum))
  119. return Error("设备编号是必需字段");
  120. #endregion
  121. #region 判断权限
  122. PLC_IPManage comodel = new PLC_IPManage();
  123. var list = new List<FilterDefinition<PLC_IPManage>>();
  124. var filterBuilder = Builders<PLC_IPManage>.Filter;
  125. list.Add(filterBuilder.Eq("ipaddress", ipaddress));
  126. list.Add(filterBuilder.Eq("macaddress", macaddress));
  127. var filter = Builders<PLC_IPManage>.Filter.And(list);
  128. var count = await _ipmanageRepository.CountAsync(filter);
  129. if (count > 0)
  130. {
  131. var dModel = await _ipmanageRepository.GetSingle(s => s.ipaddress.Equals(ipaddress) & s.macaddress == macaddress & s.deleteflag == 0, null);
  132. if (dModel.forbidread == 1)
  133. {
  134. #region 记录接口访问信息
  135. PLC_AccessRecords romodel = new PLC_AccessRecords();
  136. romodel.ipaddress = ipaddress;
  137. romodel.macaddress = macaddress;
  138. romodel.createtime = DateTime.Now;
  139. romodel.interfacename = "getplcvalue";
  140. romodel.flag = 0;
  141. bool b = await _plc_recordsRepository.Add(romodel);
  142. #endregion
  143. return Error("没有接口访问权限!");
  144. }
  145. }
  146. else
  147. {
  148. var model = new PLC_IPManage();
  149. model.ipaddress = ipaddress;
  150. model.macaddress = macaddress;
  151. model.createtime = DateTime.Now;
  152. model.forbidread = 0;
  153. model.forbidwrite = 0;
  154. model.deleteflag = 0;
  155. bool b = await _ipmanageRepository.Add(model);
  156. }
  157. #endregion
  158. #region 记录接口访问信息
  159. PLC_AccessRecords rmodel = new PLC_AccessRecords();
  160. rmodel.ipaddress = ipaddress;
  161. rmodel.macaddress = macaddress;
  162. rmodel.createtime = DateTime.Now;
  163. rmodel.interfacename = "getplcvalue";
  164. rmodel.flag = 1;
  165. bool r = await _plc_recordsRepository.Add(rmodel);
  166. #endregion
  167. string cvalue = "";
  168. #region 从Redis缓存中查询信息
  169. var locationStr = await _cache.GetStringAsync($"{equipnum}{note}");//($"{equipnum+note}")
  170. if (!string.IsNullOrWhiteSpace(locationStr))
  171. {
  172. cvalue = locationStr.ToObject<string>();
  173. }
  174. #endregion
  175. if (cvalue == "")
  176. return Error("获取数据失败");
  177. return Success("成功", cvalue);
  178. }
  179. //[Authorize]
  180. [HttpGet("getlistbypage")]
  181. public async Task<IActionResult> GetListsByPageAsync(string ipaddress, string stime, string etime, string macaddress, int pageindex = 1, int pagesize = 10)
  182. {
  183. try
  184. {
  185. //排序字段
  186. var sort = Builders<PLC_AccessRecords>.Sort.Descending("createtime");
  187. //根据条件查询集合
  188. var flist = new List<FilterDefinition<PLC_AccessRecords>>();
  189. flist.Add(Builders<PLC_AccessRecords>.Filter.Eq("deleteflag", 0));
  190. if (!string.IsNullOrWhiteSpace(ipaddress))
  191. flist.Add(Builders<PLC_AccessRecords>.Filter.Where(s => s.ipaddress.Equals(ipaddress)));
  192. if (!string.IsNullOrWhiteSpace(macaddress))
  193. flist.Add(Builders<PLC_AccessRecords>.Filter.Where(s => s.macaddress.Equals(macaddress)));
  194. if (!string.IsNullOrWhiteSpace(stime))
  195. {
  196. DateTime dt2 = new DateTime();
  197. if (DateTime.TryParse(stime.Trim(), out dt2))
  198. flist.Add(Builders<PLC_AccessRecords>.Filter.Gt("createtime", stime + " 00:00:00"));
  199. }
  200. if (!string.IsNullOrWhiteSpace(etime))
  201. {
  202. DateTime dt2 = new DateTime();
  203. if (DateTime.TryParse(etime.Trim(), out dt2))
  204. flist.Add(Builders<PLC_AccessRecords>.Filter.Lt("createtime", etime + " 23:59:59"));
  205. }
  206. var filter = Builders<PLC_AccessRecords>.Filter.And(flist);
  207. var list = await _plc_recordsRepository.GetByPage(filter, pageindex, pagesize, sort);
  208. var count = await _plc_recordsRepository.CountAsync(filter);
  209. var obj = new
  210. {
  211. state = "success",
  212. message = "根据条件获取分页数据成功",
  213. rows = list,
  214. total = count,
  215. };
  216. return Content(obj.ToJson());
  217. }
  218. catch (Exception ex)
  219. {
  220. _logger.LogError(ex, "根据条件获取分页数据异常");
  221. return Error("根据条件获取分页数据异常");
  222. }
  223. }
  224. }
  225. }