123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Runtime.ConstrainedExecution;
- using System.Text;
- using System.Threading.Tasks;
- using System.Xml.Linq;
- using JavaScriptEngineSwitcher.ChakraCore;
- using JavaScriptEngineSwitcher.Core;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc.RazorPages;
- using Microsoft.AspNetCore.NodeServices;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using static System.Net.Mime.MediaTypeNames;
- namespace Ropin.Inspection.Common.Helper
- {
- public class FanyiHelper
- {
- static IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
- static FanyiHelper()
- {
- //if (!engineSwitcher.EngineFactories.Any())
- //{
- engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
- engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
- //}
- }
- public static TokenResult GetToken(AccessUser accessUser)
- {
- var url = "https://fbox360.com/idserver/core/connect/token";
- TokenResult token;
- Dictionary<string, object> data = new Dictionary<string, object>();
- try
- {
- if (accessUser == null)
- {
- throw new Exception("参数为空");
- }
- else
- {
- Dictionary<string, string> dict = new Dictionary<string, string>();
- if (!string.IsNullOrEmpty(accessUser.refresh_token))
- {
- dict["grant_type"] = "refresh_token";
- dict["refresh_token"] = accessUser.refresh_token;
- }
- else
- {
- dict["grant_type"] = "client_credentials";
- dict["client_id"] = accessUser.client_id;
- dict["client_secret"] = accessUser.client_secret;
- dict["scope"] = "fbox";
- }
- using (HttpClient http = new HttpClient())
- {
- using (var content = new FormUrlEncodedContent(dict))
- {
- var msg = http.PostAsync(url, content);
- if (msg.IsFaulted)
- {
- return null;
- }
- else
- {
- var result = msg.Result.Content.ReadAsStringAsync().Result;
- token = JsonConvert.DeserializeObject<TokenResult>(result);
- }
- //return Content(result, "application/json");
- }
- }
- }
- return token;
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- public static TokenResult tokenResult;
- public static DateTime tokenTime;
- public static async Task<string> GetWebScadaDevSpotHisData(string devId, List<string> names, List<string> groupnames)
- {
- string jResult = String.Empty;
- if (DateTime.Now >= tokenTime)
- {
- tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
- tokenTime = DateTime.Now.AddSeconds(7200);
- using (HttpClient client = new HttpClient())
- {
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
- var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
- requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var response = await client.SendAsync(requestt);
- string result = await response.Content.ReadAsStringAsync();
- if (response.StatusCode != HttpStatusCode.OK)
- {
- }
- else
- {
- //todo
- }
- }
- }
- using (HttpClient client = new HttpClient())
- {
- string[] idarr = { "224872398136431165" };
- string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
- {
- type = 0,
- ids = idarr,
- g = 0,
- begin = DateTime.Now.AddDays(-5).Ticks,
- end = DateTime.Now.Ticks,
- tr = 3,
- limit = -500,
- tz = "Asia/Shanghai"
- });
- using (var httpClient = new HttpClient())
- {
- httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
- //httpClient.BaseAddress = new Uri("https://fbox360.com/api/v2/hdata/get");
- httpClient.BaseAddress = new Uri("http://fbhs1.fbox360.com/api/v2/hdata/get");
- //httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/hdata/get");
- httpClient.DefaultRequestHeaders.Accept.Clear();
- httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var jsonString = postData;
- HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
- if (esponse.IsSuccessStatusCode)
- {
- string json = await esponse.Content.ReadAsStringAsync();
- List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
- }
- }
- return await Task.FromResult(jResult);
- }
- }
- public static Dictionary<string, DeviceVlue> alarmDic = new Dictionary<string, DeviceVlue>();
- public static Dictionary<string, DeviceVlue> msgAlarmDic = new Dictionary<string, DeviceVlue>();
- 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)
- {
- //Dictionary<string, DeviceVlue> msgAlarmDic = new Dictionary<string, DeviceVlue>();
- string jResult = String.Empty;
- if (DateTime.Now >= tokenTime)
- {
- tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
- tokenTime = DateTime.Now.AddSeconds(7200);
- using (HttpClient client = new HttpClient())
- {
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
- var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
- requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var response = await client.SendAsync(requestt);
- string result = await response.Content.ReadAsStringAsync();
- if (response.StatusCode != HttpStatusCode.OK)
- {
- }
- else
- {
- //todo
- }
- }
- }
- using (HttpClient client = new HttpClient())
- {
- string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
- {
- names = names,
- groupnames = groupnames,
- timeOut = 6000
- });
- using (var httpClient = new HttpClient())
- {
- httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
- //httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
- httpClient.BaseAddress = new Uri("https://fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
- httpClient.DefaultRequestHeaders.Accept.Clear();
- httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var jsonString = postData;
- HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
- if (esponse.IsSuccessStatusCode)
- {
- string json = await esponse.Content.ReadAsStringAsync();
- List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
- List<decimal> li1 = new List<decimal>();
- var jarray = new JArray();
- var aljarray = new JArray();
- //aljarray.Add(new JObject { { "colour", "red" } });
- //aljarray.Add(new JObject { { "colour", "green" } });
- //aljarray.Add(new JObject { { "colour", "black" } });
- //aljarray.Add(new JValue("red") );
- //aljarray.Add(new JValue("green"));
- //aljarray.Add(new JValue("black"));
- for (int i = 0; i < deviceVueList.Count; i++)
- {
- if (null == deviceVueList[i])
- continue;
- deviceVueList[i].storeCode = storeCode;
- //JObject HS = new JObject { { "name" + i, deviceVueList[0]?.name }, { "value" + i, deviceVueList[i]?.value.ToString().Split('.')[0]} };
- //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] } };
- //List<string> args = new List<string>();
- //args.Add(calFormula?[i]?.Split(',')?[1]);
- //args.Add(calFormula?[i]?.Split(',')?[2]);
- //args.Add(deviceVueList[i]?.value.ToString());
- //JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] } };
- //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)} };
- if (null == calFormulaList)
- {
- JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] } };
- //HS.Add(jo);
- jarray.Add(HS);
- }
- if (null != calFormulaList)
- if (i < calFormulaList.Count && null != calFormulaList.ElementAt(i))
- {
- foreach (var item in calFormulaList[i])
- {
- List<string> calargs = item.Value.ToList();
- calargs.Add(deviceVueList[i]?.value.ToString());
- //JObject jo = new JObject { item.Name, await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs) };
- bool bAlarm = false;
- if (item.Name == "changecolour")
- {
- string alarmColour = string.Empty;
- //var basePath = AppDomain.CurrentDomain.BaseDirectory;
- IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
- engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
- engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
- using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
- {
- engine.ExecuteFile("./wwwroot/uploads/scripts/" + "changecolour.js");
- alarmColour = engine.CallFunction<string>("changecolour", String.Join(",", calargs).Trim(','));
- }
- //string alarmColour = await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs);
- bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
- JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { item.Name, alarmColour } };
- //HS.Add(jo);
- jarray.Add(HS);
- }
- else if (item.Name == "alarmlight")
- {
- string alarmColour = string.Empty;
- IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
- engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
- engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
- using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
- {
- engine.ExecuteFile("./wwwroot/uploads/scripts/" + "alarmlight.js");
- alarmColour = engine.CallFunction<string>("alarmlight", String.Join(",", calargs).Trim(','));
- }
- //string alarmColour = await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs);
- bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
- JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { item.Name, alarmColour } };
- //HS.Add(jo);
- jarray.Add(HS);
- JObject jo = new JObject { { "alarmcolour", alarmColour } };
- aljarray.Add(jo);
- }
- else if (item.Name == "noformula")
- {
- JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] } };
- //HS.Add(jo);
- jarray.Add(HS);
- }
- }
- }
- //jarray.Add(HS);
- }
- var deviceJObject = new JObject();
- deviceJObject.Add("device", jarray);
- deviceJObject.Add("alarmlight", aljarray);
- jResult = JsonConvert.SerializeObject(deviceJObject);
- }
- }
- }
- return jResult;
- }
-
- 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)
- {
-
- //Dictionary<string, DeviceVlue> msgAlarmDic = new Dictionary<string, DeviceVlue>();
- JObject jResult = null;
- if (DateTime.Now >= tokenTime)
- {
- tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
- tokenTime = DateTime.Now.AddSeconds(7200);
- using (HttpClient client = new HttpClient())
- {
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
- var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
- requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var response = await client.SendAsync(requestt);
- string result = await response.Content.ReadAsStringAsync();
- if (response.StatusCode != HttpStatusCode.OK)
- {
- }
- else
- {
- //todo
- }
- }
- }
- using (HttpClient client = new HttpClient())
- {
- string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
- {
- names = names,
- groupnames = groupnames,
- timeOut = 6000
- });
- using (var httpClient = new HttpClient())
- {
- if (boxNo == "02700124072500004875")//&& names.Contains("虚点")300223030347 02700124041100007872
- {
- int mydebug = 0;
- }
- httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
- //httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
- if(boxNo.StartsWith("0270012")) //有人盒子,后期编号加youren
- //httpClient.BaseAddress = new Uri("http://www.dgt.net.cn:95/api/Value/GetDevicePointByAsync?boxNo=" + boxNo);
- httpClient.BaseAddress = new Uri("http://60.204.212.71:496/api/Value/GetDevicePointByAsync?boxNo=" + boxNo);
- else if(boxNo.StartsWith("8888"))//在线盒子,后期编号加zaixian
- httpClient.BaseAddress = new Uri("http://www.dgt.net.cn:2296/api/Value/GetDevicePointByAsync?boxNo=" + boxNo); //https://www.ropintechjxbooksys.com/DigitalEnvironmentallyLoRa/api/Value/GetDevicePointByAsync?boxNo=
- else
- httpClient.BaseAddress = new Uri("https://fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
- httpClient.DefaultRequestHeaders.Accept.Clear();
- httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var jsonString = postData;
- string json = string.Empty;
- HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
- if (esponse.IsSuccessStatusCode)
- {
- json = await esponse.Content.ReadAsStringAsync();
- if (!boxNo.StartsWith("0270012") && json.StartsWith("[null")&& json.EndsWith("null]"))
- {
- using (var httpClient2 = new HttpClient())
- {
- httpClient2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
- httpClient2.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
- httpClient2.DefaultRequestHeaders.Accept.Clear();
- httpClient2.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- esponse = await httpClient2.PostAsync(httpClient2.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
- if (esponse.IsSuccessStatusCode)
- {
- json = await esponse.Content.ReadAsStringAsync();
- }
- }
- }
- }
- if (esponse.IsSuccessStatusCode && !string.IsNullOrWhiteSpace(json)) // && !json.Contains("null")
- {
- if (json.Contains("error"))
- {
- return jResult;
- }
- //json = await esponse.Content.ReadAsStringAsync();
- if (json.Contains("null"))
- {
- bool bvirtualspot = false;
- for (int i = 0; i < calFormulaList.Count; i++)
- {
- foreach (var item in calFormulaList[i])
- {
- if (item.Name == "virtualspot")
- {
- bvirtualspot = true;
- }
- }
- }
- if(!bvirtualspot)
- return jResult;
- }
- //json.Replace("NULL","null");
- //json = @""
- List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
- List<decimal> li1 = new List<decimal>();
- var jarray = new JArray();
- var aljarray = new JArray();
- //aljarray.Add(new JObject { { "colour", "red" } });
- //aljarray.Add(new JObject { { "colour", "green" } });
- //aljarray.Add(new JObject { { "colour", "black" } });
- //aljarray.Add(new JValue("red") );
- //aljarray.Add(new JValue("green"));
- //aljarray.Add(new JValue("black"));
- //虚点
- for (int i = 0; i < deviceVueList.Count; i++)
- {
- if (null == deviceVueList[i])
- {
- 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() };
- deviceVueList[i].storeCode = storeCode;
- }
-
-
- //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] } };
- //jarray.Add(HS);
- if (null != calFormulaList)
- if (i < calFormulaList.Count && null != calFormulaList.ElementAt(i))
- {
- foreach (var item in calFormulaList[i])
- {
- if (item.Name == "virtualspot")
- {
- //List<string> spotIds = item.SpotId.ToList();
- using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
- {
- //Queue<string> spotIdQu = new Queue<string>();
- //foreach (var spotId in spotIds)
- //{
- // spotIdQu.Enqueue(spotId);
- //}
- //spotIdQu.Enqueue("279771131174458561");
- //spotIdQu.Enqueue("279771131174458564");
- //item.SpotId = spotIdQu;
- Queue<string> spotValueQu = new Queue<string>();
- while (item.SpotId.Count != 0)
- {
- var spotId = item.SpotId.Dequeue();
- //var value = deviceVueList.Where(x => x.id == spotId).FirstOrDefault()? .value.ToString();
- //var devVue = deviceVueList.Where(x => x.name == spotId).FirstOrDefault();
- if (spotId == "一号温度")
- {
- int fiqi = 0;
- }
- var value = deviceVueList?.Where(item => item != null).ToList()?.Where(x => x.name == spotId).FirstOrDefault()?.value?.ToString();
- //var value = jarray.FirstOrDefault(x => x.Value<string>("devSpotCode") == spotId).Value<string>("value");
- spotValueQu.Enqueue(value);
- }
- string srule = @"function script(ar) {
- let arr = ar.split(',')
- var min = arr[0];
- var max = arr[1];
- var value = 3;
- if (parseInt(value) <= parseInt(min)) {
- return min;
- }
- if (parseInt(value) >= parseInt(max)) {
- return max;
- }
- return value;
- }";
- //item.Rule = srule;
- engine.Execute(item.Rule);
- string result = engine.CallFunction<string>("script", String.Join(",", spotValueQu.ToList()).Trim(','));
- //jarray.FirstOrDefault(x => x.Value<string>("devSpotCode") == devSpotCodes[i])["value"] = result;
- deviceVueList[i].value = result;
- }
- }
- }
- }
- }
- for (int i = 0; i < deviceVueList.Count; i++)
- {
- if (null == deviceVueList[i])
- continue;
- deviceVueList[i].storeCode = storeCode;
- //JObject HS = new JObject { { "name" + i, deviceVueList[0]?.name }, { "value" + i, deviceVueList[i]?.value.ToString().Split('.')[0]} };
- //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] } };
- //List<string> args = new List<string>();
- //args.Add(calFormula?[i]?.Split(',')?[1]);
- //args.Add(calFormula?[i]?.Split(',')?[2]);
- //args.Add(deviceVueList[i]?.value.ToString());
- //JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] } };
- //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)} };
- //if (null == calFormulaList)
- //{
- // JObject HS = new JObject { { "name", deviceVueList[i]?.name }, { "value", deviceVueList[i]?.value.ToString().Split('.')[0] }, { "unitName", unitNames[i] } };
- // //HS.Add(jo);
- // jarray.Add(HS);
- //}
- if (deviceVueList[i]?.value == null)
- deviceVueList[i].value = "null";
- 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] } };
- if (boxNo.StartsWith("0270012")|| boxNo.StartsWith("8888"))//网关设备掉线
- {
- DateTime dtvue;
- if (DateTime.TryParse(deviceVueList[i]?.timestamp, out dtvue))
- {
-
- }
- else
- {
- dtvue = new DateTime(long.Parse(deviceVueList[i]?.timestamp), DateTimeKind.Utc);
- }
-
- if (deviceVueList[i] == null || dtvue < DateTime.Now.AddMinutes(-10))
- {
- return jResult;
- }
- }
- else
- {
- if (deviceVueList[i] == null) // || deviceVueList[i]?.connState != 1
- {
- return jResult;
- }
- }
- if (null != calFormulaList)
- if (i < calFormulaList.Count && null != calFormulaList.ElementAt(i))
- {
- foreach (var item in calFormulaList[i])
- {
- if (item.Name == "virtualspot")
- {
- 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] } };
- continue;
- }
-
- List<string> calargs = item?.Value?.ToList();
- calargs.Add(deviceVueList[i]?.value?.ToString());
- //JObject jo = new JObject { item.Name, await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs) };
- bool bAlarm = false;
- if (item.Name == "changecolour")
- {
- string alarmColour = string.Empty;
- //var basePath = AppDomain.CurrentDomain.BaseDirectory;
- //IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
- //engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
- //engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
- using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
- {
- engine.ExecuteFile("./wwwroot/uploads/scripts/" + "changecolour.js");
- alarmColour = engine.CallFunction<string>("changecolour", String.Join(",", calargs).Trim(','));
- }
- //string alarmColour = await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs);
- bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
- //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] } };
-
- HS.Add("effectiveRange", new JValue(String.Join(",", calargs).Trim(',')));
- HS.Add(item.Name, alarmColour);
- //HS.Add(jo);
- //jarray.Add(HS);
- }
- else if (item.Name == "alarmlight")
- {
- //HS.Add(jo);
- //jarray.Add(HS);
- string alarmColour = string.Empty;
- //IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
- //engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
- //engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
- using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
- {
- engine.ExecuteFile("./wwwroot/uploads/scripts/" + "alarmlight.js");
- alarmColour = engine.CallFunction<string>("alarmlight", String.Join(",", calargs).Trim(','));
- }
- //string alarmColour = await services.InvokeAsync<string>("./wwwroot/uploads/scripts/" + item.Name, calargs);
- bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
- //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] } };
- //HS.Add("changecolour", new JValue(alarmColour));
- JObject jo = new JObject { { "alarmcolour", alarmColour }, { "sort", 0 } };
- aljarray.Add(jo);
- }
- else if (item.Name == "virtualspot")
- {
- //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] } };
- //HS.Add(jo);
- //jarray.Add(HS);
- }
- else if (item.Name == "noformula")
- {
- //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] } };
- //HS.Add(jo);
- //jarray.Add(HS);
- }else if(item.Name == "minchangecolour")
- {
- string alarmColour = string.Empty;
- using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
- {
- engine.ExecuteFile("./wwwroot/uploads/scripts/" + "minchangecolour.js");
- alarmColour = engine.CallFunction<string>("minchangecolour", String.Join(",", calargs).Trim(','));
- }
- bAlarm = AlarmByColour(alarmColour, deviceVueList[i]);
- if(!HS.ContainsKey("name"))
- HS.Add("effectiveRange", new JValue(String.Join(",", calargs).Trim(',')));
- else
- {
- HS["effectiveRange"] = StringHelper.DelLastCommaStr(HS.GetValue("effectiveRange").ToString().Trim(',')) + " " + StringHelper.DelLastCommaStr(String.Join(",", calargs).Trim(','));
- }
- HS.Add(item.Name, alarmColour);
- }
- }
- }
- jarray.Add(HS);
- }
- JObject deviceJObject = new JObject();
- deviceJObject.Add("device", jarray);
- deviceJObject.Add("alarmlight", aljarray);
- //deviceJObject.Add("package", new JObject() { { "time",DateTime.Now} });
- jResult = deviceJObject;
- }
- }
- }
- return jResult;
- }
-
- public static async Task<List<DeviceVlue>> GetDevSpotValue(string boxNo, List<string> names, List<string> groupnames)
- {
- List<DeviceVlue> deviceVueList=null;
- if (DateTime.Now >= tokenTime)
- {
- tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
- tokenTime = DateTime.Now.AddSeconds(7200);
- using (HttpClient client = new HttpClient())
- {
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
- var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
- requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var response = await client.SendAsync(requestt);
- string result = await response.Content.ReadAsStringAsync();
- if (response.StatusCode != HttpStatusCode.OK)
- {
- }
- else
- {
- //todo
- }
- }
- }
- using (HttpClient client = new HttpClient())
- {
- string postData = JsonConvert.SerializeObject(new
- {
- names = names,
- groupnames = groupnames,
- timeOut = 6000
- });
- using (var httpClient = new HttpClient())
- {
- httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
- //httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
- httpClient.BaseAddress = new Uri("https://fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo);
- httpClient.DefaultRequestHeaders.Accept.Clear();
- httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var jsonString = postData;
- HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));
- if (esponse.IsSuccessStatusCode)
- {
- string json = await esponse.Content.ReadAsStringAsync();
- deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
- }
- }
- }
- return await Task.FromResult(deviceVueList) ;
- }
- public static bool AlarmByColour (string colour, DeviceVlue dv)
- {
- if (colour== "red")
- {
- DeviceVlue sValue;
- if(dv==null || dv.id == null) return false;
- if (alarmDic.TryGetValue(dv?.id, out sValue))
- {
- }
- else
- {
- alarmDic.Add(dv?.id, dv);//没有
- //msgAlarmDic.Add(dv?.id, dv);
- }
- if (msgAlarmDic.TryGetValue(dv?.id, out sValue))
- {
- }
- else
- {
- msgAlarmDic.Add(dv?.id, dv);
- }
- return true;
- }
- else
- {
- DeviceVlue sValue;
- if (dv == null || dv.id == null) return false;
- if (alarmDic.TryGetValue(dv?.id, out sValue))
- {
- alarmDic.Remove(dv?.id);
- }
- else
- {
- }
- return false;
- }
- }
- }
- public class AccessUser
- {
- public string client_id { get; set; }
- public string client_secret { get; set; }
- public string refresh_token { get; set; }
- }
- public class TokenResult
- {
- public string access_token { get; set; }
- /// <summary>
- /// 有效期
- /// </summary>
- public int expires_in { get; set; }
- public string refresh_token { get; set; }
- public string token_type { get; set; }
- /// <summary>
- /// invalid_grant过期
- /// </summary>
- public string error { get; set; }
- }
- public class DeviceVlue
- {
- public string storeCode { get; set; }
- public string id { get; set; }
- public string timestamp { get; set; }
- public int? dataType { get; set; }
- public string name { get; set; }
- public string? value { get; set; }
- public string boxId { get; set; }
- public int? status { get; set; }
- public int? connState { get; set; }
- public string connStateTimestamp { get; set; }
- }
- public class DeviceSpotData
- {
- public IEnumerable<DeviceSpot> device { get; set; }
- }
- public class DeviceSpot
- {
- public string id { get; set; }
- public string name { get; set; }
- public string value { get; set; }
- public string unitName { get; set; }
- public string devSpotCode { get; set; }
- public double sort { get; set; }
- }
- public class DevSpotCalFormula
- {
- public IList<CalFormula> CalFormula { get; set; }
- }
- public class CalFormula
- {
- public string Name { get; set; }
- public Queue<string> Value { get; set; }
- public Queue<string> SpotId { get; set; }
- public string Rule { get; set; }
- }
- }
|