FanyiHelper.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Net.Http.Headers;
  7. using System.Runtime.ConstrainedExecution;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Xml.Linq;
  11. using JavaScriptEngineSwitcher.ChakraCore;
  12. using JavaScriptEngineSwitcher.Core;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.AspNetCore.Mvc.RazorPages;
  15. using Microsoft.AspNetCore.NodeServices;
  16. using Newtonsoft.Json;
  17. using Newtonsoft.Json.Linq;
  18. using static System.Net.Mime.MediaTypeNames;
  19. namespace Ropin.Inspection.Common.Helper
  20. {
  21. public class FanyiHelper
  22. {
  23. static IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
  24. static FanyiHelper()
  25. {
  26. //if (!engineSwitcher.EngineFactories.Any())
  27. //{
  28. engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
  29. engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
  30. //}
  31. }
  32. public static TokenResult GetToken(AccessUser accessUser)
  33. {
  34. var url = "https://fbox360.com/idserver/core/connect/token";
  35. TokenResult token;
  36. Dictionary<string, object> data = new Dictionary<string, object>();
  37. try
  38. {
  39. if (accessUser == null)
  40. {
  41. throw new Exception("参数为空");
  42. }
  43. else
  44. {
  45. Dictionary<string, string> dict = new Dictionary<string, string>();
  46. if (!string.IsNullOrEmpty(accessUser.refresh_token))
  47. {
  48. dict["grant_type"] = "refresh_token";
  49. dict["refresh_token"] = accessUser.refresh_token;
  50. }
  51. else
  52. {
  53. dict["grant_type"] = "client_credentials";
  54. dict["client_id"] = accessUser.client_id;
  55. dict["client_secret"] = accessUser.client_secret;
  56. dict["scope"] = "fbox";
  57. }
  58. using (HttpClient http = new HttpClient())
  59. {
  60. using (var content = new FormUrlEncodedContent(dict))
  61. {
  62. var msg = http.PostAsync(url, content);
  63. if (msg.IsFaulted)
  64. {
  65. return null;
  66. }
  67. else
  68. {
  69. var result = msg.Result.Content.ReadAsStringAsync().Result;
  70. token = JsonConvert.DeserializeObject<TokenResult>(result);
  71. }
  72. //return Content(result, "application/json");
  73. }
  74. }
  75. }
  76. return token;
  77. }
  78. catch (Exception ex)
  79. {
  80. return null;
  81. }
  82. }
  83. public static TokenResult tokenResult;
  84. public static DateTime tokenTime;
  85. public static async Task<string> GetWebScadaDevSpotHisData(string devId, List<string> names, List<string> groupnames)
  86. {
  87. string jResult = String.Empty;
  88. if (DateTime.Now >= tokenTime)
  89. {
  90. tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
  91. tokenTime = DateTime.Now.AddSeconds(7200);
  92. using (HttpClient client = new HttpClient())
  93. {
  94. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
  95. var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
  96. requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  97. var response = await client.SendAsync(requestt);
  98. string result = await response.Content.ReadAsStringAsync();
  99. if (response.StatusCode != HttpStatusCode.OK)
  100. {
  101. }
  102. else
  103. {
  104. //todo
  105. }
  106. }
  107. }
  108. using (HttpClient client = new HttpClient())
  109. {
  110. string[] idarr = { "224872398136431165" };
  111. string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
  112. {
  113. type = 0,
  114. ids = idarr,
  115. g = 0,
  116. begin = DateTime.Now.AddDays(-5).Ticks,
  117. end = DateTime.Now.Ticks,
  118. tr = 3,
  119. limit = -500,
  120. tz = "Asia/Shanghai"
  121. });
  122. using (var httpClient = new HttpClient())
  123. {
  124. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
  125. //httpClient.BaseAddress = new Uri("https://fbox360.com/api/v2/hdata/get");
  126. httpClient.BaseAddress = new Uri("http://fbhs1.fbox360.com/api/v2/hdata/get");
  127. //httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/hdata/get");
  128. httpClient.DefaultRequestHeaders.Accept.Clear();
  129. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  130. var jsonString = postData;
  131. HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
  132. if (esponse.IsSuccessStatusCode)
  133. {
  134. string json = await esponse.Content.ReadAsStringAsync();
  135. List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
  136. }
  137. }
  138. return await Task.FromResult(jResult);
  139. }
  140. }
  141. public static Dictionary<string, DeviceVlue> alarmDic = new Dictionary<string, DeviceVlue>();
  142. public static Dictionary<string, DeviceVlue> msgAlarmDic = new Dictionary<string, DeviceVlue>();
  143. public static async Task<string> GetWebScadaDevSpotValue(string devId, string boxNo, string storeCode, List<string> names, List<string> groupnames, List<string> calFormula, INodeServices services, List<List<CalFormula>> calFormulaList)
  144. {
  145. //Dictionary<string, DeviceVlue> msgAlarmDic = new Dictionary<string, DeviceVlue>();
  146. string jResult = String.Empty;
  147. if (DateTime.Now >= tokenTime)
  148. {
  149. tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
  150. tokenTime = DateTime.Now.AddSeconds(7200);
  151. using (HttpClient client = new HttpClient())
  152. {
  153. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
  154. var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
  155. requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  156. var response = await client.SendAsync(requestt);
  157. string result = await response.Content.ReadAsStringAsync();
  158. if (response.StatusCode != HttpStatusCode.OK)
  159. {
  160. }
  161. else
  162. {
  163. //todo
  164. }
  165. }
  166. }
  167. using (HttpClient client = new HttpClient())
  168. {
  169. string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
  170. {
  171. names = names,
  172. groupnames = groupnames,
  173. timeOut = 6000
  174. });
  175. using (var httpClient = new HttpClient())
  176. {
  177. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
  178. //httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
  179. httpClient.BaseAddress = new Uri("https://fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
  180. httpClient.DefaultRequestHeaders.Accept.Clear();
  181. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  182. var jsonString = postData;
  183. HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
  184. if (esponse.IsSuccessStatusCode)
  185. {
  186. string json = await esponse.Content.ReadAsStringAsync();
  187. List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
  188. List<decimal> li1 = new List<decimal>();
  189. var jarray = new JArray();
  190. var aljarray = new JArray();
  191. //aljarray.Add(new JObject { { "colour", "red" } });
  192. //aljarray.Add(new JObject { { "colour", "green" } });
  193. //aljarray.Add(new JObject { { "colour", "black" } });
  194. //aljarray.Add(new JValue("red") );
  195. //aljarray.Add(new JValue("green"));
  196. //aljarray.Add(new JValue("black"));
  197. for (int i = 0; i < deviceVueList.Count; i++)
  198. {
  199. if (null == deviceVueList[i])
  200. continue;
  201. deviceVueList[i].storeCode = storeCode;
  202. //JObject HS = new JObject { { "name" + i, deviceVueList[0]?.name }, { "value" + i, deviceVueList[i]?.value.ToString().Split('.')[0]} };
  203. //JObject HS = new JObject { { "name", deviceVueList[0]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { "mix", calFormula?[i].Split(',')?[1] }, { "max", calFormula?[i].Split(',')?[2] } };
  204. //List<string> args = new List<string>();
  205. //args.Add(calFormula?[i]?.Split(',')?[1]);
  206. //args.Add(calFormula?[i]?.Split(',')?[2]);
  207. //args.Add(deviceVueList[i]?.value.ToString());
  208. //JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] } };
  209. //JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { "colour", await services.InvokeAsync<string>(calFormula?[i].Split(',')?[0], args)} };
  210. if (null == calFormulaList)
  211. {
  212. JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] } };
  213. //HS.Add(jo);
  214. jarray.Add(HS);
  215. }
  216. if (null != calFormulaList)
  217. if (i < calFormulaList.Count && null != calFormulaList.ElementAt(i))
  218. {
  219. foreach (var item in calFormulaList[i])
  220. {
  221. List<string> calargs = item.Value.ToList();
  222. calargs.Add(deviceVueList[i]?.value.ToString());
  223. //JObject jo = new JObject { item.Name, await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs) };
  224. bool bAlarm = false;
  225. if (item.Name == "changecolour")
  226. {
  227. string alarmColour = string.Empty;
  228. //var basePath = AppDomain.CurrentDomain.BaseDirectory;
  229. IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
  230. engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
  231. engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
  232. using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
  233. {
  234. engine.ExecuteFile("./wwwroot/uploads/scripts/" + "changecolour.js");
  235. alarmColour = engine.CallFunction<string>("changecolour", String.Join(",", calargs).Trim(','));
  236. }
  237. //string alarmColour = await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs);
  238. bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
  239. JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { item.Name, alarmColour } };
  240. //HS.Add(jo);
  241. jarray.Add(HS);
  242. }
  243. else if (item.Name == "alarmlight")
  244. {
  245. string alarmColour = string.Empty;
  246. IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
  247. engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
  248. engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
  249. using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
  250. {
  251. engine.ExecuteFile("./wwwroot/uploads/scripts/" + "alarmlight.js");
  252. alarmColour = engine.CallFunction<string>("alarmlight", String.Join(",", calargs).Trim(','));
  253. }
  254. //string alarmColour = await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs);
  255. bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
  256. JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { item.Name, alarmColour } };
  257. //HS.Add(jo);
  258. jarray.Add(HS);
  259. JObject jo = new JObject { { "alarmcolour", alarmColour } };
  260. aljarray.Add(jo);
  261. }
  262. else if (item.Name == "noformula")
  263. {
  264. JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] } };
  265. //HS.Add(jo);
  266. jarray.Add(HS);
  267. }
  268. }
  269. }
  270. //jarray.Add(HS);
  271. }
  272. var deviceJObject = new JObject();
  273. deviceJObject.Add("device", jarray);
  274. deviceJObject.Add("alarmlight", aljarray);
  275. jResult = JsonConvert.SerializeObject(deviceJObject);
  276. }
  277. }
  278. }
  279. return jResult;
  280. }
  281. public static async Task<JObject> GetWebScadaDevSpotValue(string boxNo, string storeCode, List<string> names, List<string> unitNames, List<string> groupnames, List<string> calFormula, List<int> sort, List<string> runs,INodeServices services, List<List<CalFormula>> calFormulaList, List<string> devSpotCodes,List<string> publicList)
  282. {
  283. //Dictionary<string, DeviceVlue> msgAlarmDic = new Dictionary<string, DeviceVlue>();
  284. JObject jResult = null;
  285. if (DateTime.Now >= tokenTime)
  286. {
  287. tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
  288. tokenTime = DateTime.Now.AddSeconds(7200);
  289. using (HttpClient client = new HttpClient())
  290. {
  291. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
  292. var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
  293. requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  294. var response = await client.SendAsync(requestt);
  295. string result = await response.Content.ReadAsStringAsync();
  296. if (response.StatusCode != HttpStatusCode.OK)
  297. {
  298. }
  299. else
  300. {
  301. //todo
  302. }
  303. }
  304. }
  305. using (HttpClient client = new HttpClient())
  306. {
  307. string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
  308. {
  309. names = names,
  310. groupnames = groupnames,
  311. timeOut = 6000
  312. });
  313. using (var httpClient = new HttpClient())
  314. {
  315. if (boxNo == "02700124072500004875")//&& names.Contains("虚点")300223030347 02700124041100007872
  316. {
  317. int mydebug = 0;
  318. }
  319. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
  320. //httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
  321. if(boxNo.StartsWith("0270012")) //有人盒子,后期编号加youren
  322. //httpClient.BaseAddress = new Uri("http://www.dgt.net.cn:95/api/Value/GetDevicePointByAsync?boxNo=" + boxNo);
  323. httpClient.BaseAddress = new Uri("http://60.204.212.71:496/api/Value/GetDevicePointByAsync?boxNo=" + boxNo);
  324. else if(boxNo.StartsWith("8888"))//在线盒子,后期编号加zaixian
  325. httpClient.BaseAddress = new Uri("http://www.dgt.net.cn:2296/api/Value/GetDevicePointByAsync?boxNo=" + boxNo); //https://www.ropintechjxbooksys.com/DigitalEnvironmentallyLoRa/api/Value/GetDevicePointByAsync?boxNo=
  326. else
  327. httpClient.BaseAddress = new Uri("https://fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
  328. httpClient.DefaultRequestHeaders.Accept.Clear();
  329. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  330. var jsonString = postData;
  331. string json = string.Empty;
  332. HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
  333. if (esponse.IsSuccessStatusCode)
  334. {
  335. json = await esponse.Content.ReadAsStringAsync();
  336. if (!boxNo.StartsWith("0270012") && json.StartsWith("[null")&& json.EndsWith("null]"))
  337. {
  338. using (var httpClient2 = new HttpClient())
  339. {
  340. httpClient2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
  341. httpClient2.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
  342. httpClient2.DefaultRequestHeaders.Accept.Clear();
  343. httpClient2.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  344. esponse = await httpClient2.PostAsync(httpClient2.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
  345. if (esponse.IsSuccessStatusCode)
  346. {
  347. json = await esponse.Content.ReadAsStringAsync();
  348. }
  349. }
  350. }
  351. }
  352. if (esponse.IsSuccessStatusCode && !string.IsNullOrWhiteSpace(json)) // && !json.Contains("null")
  353. {
  354. if (json.Contains("error"))
  355. {
  356. return jResult;
  357. }
  358. //json = await esponse.Content.ReadAsStringAsync();
  359. if (json.Contains("null"))
  360. {
  361. bool bvirtualspot = false;
  362. for (int i = 0; i < calFormulaList.Count; i++)
  363. {
  364. foreach (var item in calFormulaList[i])
  365. {
  366. if (item.Name == "virtualspot")
  367. {
  368. bvirtualspot = true;
  369. }
  370. }
  371. }
  372. if(!bvirtualspot)
  373. return jResult;
  374. }
  375. //json.Replace("NULL","null");
  376. //json = @""
  377. List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
  378. List<decimal> li1 = new List<decimal>();
  379. var jarray = new JArray();
  380. var aljarray = new JArray();
  381. //aljarray.Add(new JObject { { "colour", "red" } });
  382. //aljarray.Add(new JObject { { "colour", "green" } });
  383. //aljarray.Add(new JObject { { "colour", "black" } });
  384. //aljarray.Add(new JValue("red") );
  385. //aljarray.Add(new JValue("green"));
  386. //aljarray.Add(new JValue("black"));
  387. //虚点
  388. for (int i = 0; i < deviceVueList.Count; i++)
  389. {
  390. if (null == deviceVueList[i])
  391. {
  392. deviceVueList[i] = new DeviceVlue() { id = null, name = names.ElementAt(i), value = "0", boxId = boxNo, connState = 1, dataType = 1, status = 1, connStateTimestamp = DateTime.Now.Ticks.ToString(), timestamp = DateTime.Now.Ticks.ToString() };
  393. deviceVueList[i].storeCode = storeCode;
  394. }
  395. //JObject HS = new JObject { { "id", deviceVueList[i]?.id }, { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { "unitName", unitNames[i] }, { "devSpotCode", devSpotCodes[i] } };
  396. //jarray.Add(HS);
  397. if (null != calFormulaList)
  398. if (i < calFormulaList.Count && null != calFormulaList.ElementAt(i))
  399. {
  400. foreach (var item in calFormulaList[i])
  401. {
  402. if (item.Name == "virtualspot")
  403. {
  404. //List<string> spotIds = item.SpotId.ToList();
  405. using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
  406. {
  407. //Queue<string> spotIdQu = new Queue<string>();
  408. //foreach (var spotId in spotIds)
  409. //{
  410. // spotIdQu.Enqueue(spotId);
  411. //}
  412. //spotIdQu.Enqueue("279771131174458561");
  413. //spotIdQu.Enqueue("279771131174458564");
  414. //item.SpotId = spotIdQu;
  415. Queue<string> spotValueQu = new Queue<string>();
  416. while (item.SpotId.Count != 0)
  417. {
  418. var spotId = item.SpotId.Dequeue();
  419. //var value = deviceVueList.Where(x => x.id == spotId).FirstOrDefault()? .value.ToString();
  420. //var devVue = deviceVueList.Where(x => x.name == spotId).FirstOrDefault();
  421. if (spotId == "一号温度")
  422. {
  423. int fiqi = 0;
  424. }
  425. var value = deviceVueList?.Where(item => item != null).ToList()?.Where(x => x.name == spotId).FirstOrDefault()?.value?.ToString();
  426. //var value = jarray.FirstOrDefault(x => x.Value<string>("devSpotCode") == spotId).Value<string>("value");
  427. spotValueQu.Enqueue(value);
  428. }
  429. string srule = @"function script(ar) {
  430. let arr = ar.split(',')
  431. var min = arr[0];
  432. var max = arr[1];
  433. var value = 3;
  434. if (parseInt(value) <= parseInt(min)) {
  435. return min;
  436. }
  437. if (parseInt(value) >= parseInt(max)) {
  438. return max;
  439. }
  440. return value;
  441. }";
  442. //item.Rule = srule;
  443. engine.Execute(item.Rule);
  444. string result = engine.CallFunction<string>("script", String.Join(",", spotValueQu.ToList()).Trim(','));
  445. //jarray.FirstOrDefault(x => x.Value<string>("devSpotCode") == devSpotCodes[i])["value"] = result;
  446. deviceVueList[i].value = result;
  447. }
  448. }
  449. }
  450. }
  451. }
  452. for (int i = 0; i < deviceVueList.Count; i++)
  453. {
  454. if (null == deviceVueList[i])
  455. continue;
  456. deviceVueList[i].storeCode = storeCode;
  457. //JObject HS = new JObject { { "name" + i, deviceVueList[0]?.name }, { "value" + i, deviceVueList[i]?.value.ToString().Split('.')[0]} };
  458. //JObject HS = new JObject { { "name", deviceVueList[0]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { "mix", calFormula?[i].Split(',')?[1] }, { "max", calFormula?[i].Split(',')?[2] } };
  459. //List<string> args = new List<string>();
  460. //args.Add(calFormula?[i]?.Split(',')?[1]);
  461. //args.Add(calFormula?[i]?.Split(',')?[2]);
  462. //args.Add(deviceVueList[i]?.value.ToString());
  463. //JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] } };
  464. //JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { "colour", await services.InvokeAsync<string>(calFormula?[i].Split(',')?[0], args)} };
  465. //if (null == calFormulaList)
  466. //{
  467. // JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { "unitName", unitNames[i] } };
  468. // //HS.Add(jo);
  469. // jarray.Add(HS);
  470. //}
  471. if (deviceVueList[i]?.value == null)
  472. deviceVueList[i].value = "null";
  473. JObject HS = new JObject { { "id", deviceVueList[i]?.id ?? devSpotCodes[i] }, { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToLower()=="null"? deviceVueList[i]?.value.ToLower() : Convert.ToDouble(deviceVueList[i]?.value).ToString("#0.###") }, { "unitName", unitNames[i] }, { "devSpotCode", devSpotCodes[i] }, { "sort", sort[i] }, { "run", runs[i] }, { "timestamp", deviceVueList[i]?.timestamp }, { "public", publicList[i] } };
  474. if (boxNo.StartsWith("0270012")|| boxNo.StartsWith("8888"))//网关设备掉线
  475. {
  476. DateTime dtvue;
  477. if (DateTime.TryParse(deviceVueList[i]?.timestamp, out dtvue))
  478. {
  479. }
  480. else
  481. {
  482. dtvue = new DateTime(long.Parse(deviceVueList[i]?.timestamp), DateTimeKind.Utc);
  483. }
  484. if (deviceVueList[i] == null || dtvue < DateTime.Now.AddMinutes(-10))
  485. {
  486. return jResult;
  487. }
  488. }
  489. else
  490. {
  491. if (deviceVueList[i] == null) // || deviceVueList[i]?.connState != 1
  492. {
  493. return jResult;
  494. }
  495. }
  496. if (null != calFormulaList)
  497. if (i < calFormulaList.Count && null != calFormulaList.ElementAt(i))
  498. {
  499. foreach (var item in calFormulaList[i])
  500. {
  501. if (item.Name == "virtualspot")
  502. {
  503. HS = new JObject { { "id", deviceVueList[i]?.id ?? devSpotCodes[i] }, { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToLower() == "null" ? deviceVueList[i]?.value.ToLower() : Convert.ToDouble(deviceVueList[i]?.value).ToString("#0.###") }, { "unitName", unitNames[i] }, { "devSpotCode", devSpotCodes[i] }, { "sort", sort[i] }, { "run", runs[i] }, { "timestamp", deviceVueList[i]?.timestamp }, { "public", publicList[i] } };
  504. continue;
  505. }
  506. List<string> calargs = item?.Value?.ToList();
  507. calargs.Add(deviceVueList[i]?.value?.ToString());
  508. //JObject jo = new JObject { item.Name, await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs) };
  509. bool bAlarm = false;
  510. if (item.Name == "changecolour")
  511. {
  512. string alarmColour = string.Empty;
  513. //var basePath = AppDomain.CurrentDomain.BaseDirectory;
  514. //IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
  515. //engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
  516. //engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
  517. using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
  518. {
  519. engine.ExecuteFile("./wwwroot/uploads/scripts/" + "changecolour.js");
  520. alarmColour = engine.CallFunction<string>("changecolour", String.Join(",", calargs).Trim(','));
  521. }
  522. //string alarmColour = await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs);
  523. bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
  524. //HS = new JObject { { "id", deviceVueList[i]?.id }, { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString("#0.###") }, { "unitName", unitNames[i] }, { "devSpotCode", devSpotCodes[i] }, { "effectiveRange", String.Join(",", calargs).Trim(',') }, { item.Name, alarmColour }, { "sort", sort[i] }, { "run", runs[i] } };
  525. HS.Add("effectiveRange", new JValue(String.Join(",", calargs).Trim(',')));
  526. HS.Add(item.Name, alarmColour);
  527. //HS.Add(jo);
  528. //jarray.Add(HS);
  529. }
  530. else if (item.Name == "alarmlight")
  531. {
  532. //HS.Add(jo);
  533. //jarray.Add(HS);
  534. string alarmColour = string.Empty;
  535. //IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
  536. //engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
  537. //engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
  538. using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
  539. {
  540. engine.ExecuteFile("./wwwroot/uploads/scripts/" + "alarmlight.js");
  541. alarmColour = engine.CallFunction<string>("alarmlight", String.Join(",", calargs).Trim(','));
  542. }
  543. //string alarmColour = await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs);
  544. bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
  545. //HS = new JObject { { "id", deviceVueList[i]?.id }, { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString("#0.###") }, { "unitName", unitNames[i] }, { "devSpotCode", devSpotCodes[i] }, { "changecolour", alarmColour }, { "sort", sort[i] }, { "run", runs[i] } };
  546. //HS.Add("changecolour", new JValue(alarmColour));
  547. JObject jo = new JObject { { "alarmcolour", alarmColour }, { "sort", 0 } };
  548. aljarray.Add(jo);
  549. }
  550. else if (item.Name == "virtualspot")
  551. {
  552. //HS = new JObject { { "id", deviceVueList[i]?.id }, { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToLower() == "null" ? deviceVueList[i]?.value.ToLower() : Convert.ToDouble(deviceVueList[i]?.value).ToString("#0.###") }, { "unitName", unitNames[i] }, { "devSpotCode", devSpotCodes[i] }, { "sort", sort[i] }, { "run", runs[i] }, { "timestamp", deviceVueList[i]?.timestamp }, { "public", publicList[i] } };
  553. //HS.Add(jo);
  554. //jarray.Add(HS);
  555. }
  556. else if (item.Name == "noformula")
  557. {
  558. //HS = new JObject { { "id", deviceVueList[i]?.id }, { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString("#0.###") }, { "unitName", unitNames[i] }, { "devSpotCode", devSpotCodes[i] }, { "sort", sort[i] }, { "run", runs[i] } };
  559. //HS.Add(jo);
  560. //jarray.Add(HS);
  561. }else if(item.Name == "minchangecolour")
  562. {
  563. string alarmColour = string.Empty;
  564. using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
  565. {
  566. engine.ExecuteFile("./wwwroot/uploads/scripts/" + "minchangecolour.js");
  567. alarmColour = engine.CallFunction<string>("minchangecolour", String.Join(",", calargs).Trim(','));
  568. }
  569. bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
  570. if(!HS.ContainsKey("name"))
  571. HS.Add("effectiveRange", new JValue(String.Join(",", calargs).Trim(',')));
  572. else
  573. {
  574. HS["effectiveRange"] = StringHelper.DelLastCommaStr(HS.GetValue("effectiveRange").ToString().Trim(',')) + " " + StringHelper.DelLastCommaStr(String.Join(",", calargs).Trim(','));
  575. }
  576. HS.Add(item.Name, alarmColour);
  577. }
  578. }
  579. }
  580. jarray.Add(HS);
  581. }
  582. JObject deviceJObject = new JObject();
  583. deviceJObject.Add("device", jarray);
  584. deviceJObject.Add("alarmlight", aljarray);
  585. //deviceJObject.Add("package", new JObject() { { "time",DateTime.Now} });
  586. jResult = deviceJObject;
  587. }
  588. }
  589. }
  590. return jResult;
  591. }
  592. public static async Task<List<DeviceVlue>> GetDevSpotValue(string boxNo, List<string> names, List<string> groupnames)
  593. {
  594. List<DeviceVlue> deviceVueList=null;
  595. if (DateTime.Now >= tokenTime)
  596. {
  597. tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
  598. tokenTime = DateTime.Now.AddSeconds(7200);
  599. using (HttpClient client = new HttpClient())
  600. {
  601. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
  602. var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
  603. requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  604. var response = await client.SendAsync(requestt);
  605. string result = await response.Content.ReadAsStringAsync();
  606. if (response.StatusCode != HttpStatusCode.OK)
  607. {
  608. }
  609. else
  610. {
  611. //todo
  612. }
  613. }
  614. }
  615. using (HttpClient client = new HttpClient())
  616. {
  617. string postData = JsonConvert.SerializeObject(new
  618. {
  619. names = names,
  620. groupnames = groupnames,
  621. timeOut = 6000
  622. });
  623. using (var httpClient = new HttpClient())
  624. {
  625. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
  626. //httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
  627. httpClient.BaseAddress = new Uri("https://fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
  628. httpClient.DefaultRequestHeaders.Accept.Clear();
  629. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  630. var jsonString = postData;
  631. HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
  632. if (esponse.IsSuccessStatusCode)
  633. {
  634. string json = await esponse.Content.ReadAsStringAsync();
  635. deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
  636. }
  637. }
  638. }
  639. return await Task.FromResult(deviceVueList) ;
  640. }
  641. public static bool AlarmByColour (string colour, DeviceVlue dv)
  642. {
  643. if (colour== "red")
  644. {
  645. DeviceVlue sValue;
  646. if(dv==null || dv.id == null) return false;
  647. if (alarmDic.TryGetValue(dv?.id, out sValue))
  648. {
  649. }
  650. else
  651. {
  652. alarmDic.Add(dv?.id, dv);//没有
  653. //msgAlarmDic.Add(dv?.id, dv);
  654. }
  655. if (msgAlarmDic.TryGetValue(dv?.id, out sValue))
  656. {
  657. }
  658. else
  659. {
  660. msgAlarmDic.Add(dv?.id, dv);
  661. }
  662. return true;
  663. }
  664. else
  665. {
  666. DeviceVlue sValue;
  667. if (dv == null || dv.id == null) return false;
  668. if (alarmDic.TryGetValue(dv?.id, out sValue))
  669. {
  670. alarmDic.Remove(dv?.id);
  671. }
  672. else
  673. {
  674. }
  675. return false;
  676. }
  677. }
  678. }
  679. public class AccessUser
  680. {
  681. public string client_id { get; set; }
  682. public string client_secret { get; set; }
  683. public string refresh_token { get; set; }
  684. }
  685. public class TokenResult
  686. {
  687. public string access_token { get; set; }
  688. /// <summary>
  689. /// 有效期
  690. /// </summary>
  691. public int expires_in { get; set; }
  692. public string refresh_token { get; set; }
  693. public string token_type { get; set; }
  694. /// <summary>
  695. /// invalid_grant过期
  696. /// </summary>
  697. public string error { get; set; }
  698. }
  699. public class DeviceVlue
  700. {
  701. public string storeCode { get; set; }
  702. public string id { get; set; }
  703. public string timestamp { get; set; }
  704. public int? dataType { get; set; }
  705. public string name { get; set; }
  706. public string? value { get; set; }
  707. public string boxId { get; set; }
  708. public int? status { get; set; }
  709. public int? connState { get; set; }
  710. public string connStateTimestamp { get; set; }
  711. }
  712. public class DeviceSpotData
  713. {
  714. public IEnumerable<DeviceSpot> device { get; set; }
  715. }
  716. public class DeviceSpot
  717. {
  718. public string id { get; set; }
  719. public string name { get; set; }
  720. public string value { get; set; }
  721. public string unitName { get; set; }
  722. public string devSpotCode { get; set; }
  723. public double sort { get; set; }
  724. }
  725. public class DevSpotCalFormula
  726. {
  727. public IList<CalFormula> CalFormula { get; set; }
  728. }
  729. public class CalFormula
  730. {
  731. public string Name { get; set; }
  732. public Queue<string> Value { get; set; }
  733. public Queue<string> SpotId { get; set; }
  734. public string Rule { get; set; }
  735. }
  736. }