Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.62 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using CocosQueue;
  6. using CocosSimonsVossHandler;
  7. using CocosSmartIntegoHandler;
  8. using CoCoSCallback;
  9. using CocosApiConnector;
  10. using cocosgateway;
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Linq;
  13. using CoCosLog;
  14. using System.Text.RegularExpressions;
  15. using System.Diagnostics;
  16. using System.Runtime.InteropServices;
  17. using Microsoft.Win32.SafeHandles;
  18. using CoCoSTagHandler;
  19. using CoCoSStatus;
  20.  
  21. namespace CoCoSdevices
  22. {
  23. public class Device
  24. {
  25. public string id { get; set; }
  26. public string parent { get; set; }
  27. public string type { get; set; }
  28. public string name { get; set; }
  29. public string prefix { get; set; }
  30. public string prefixName { get; set; }
  31. public string state { get; set; }
  32. public string ipAddress { get; set; }
  33.  
  34. [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  35. public int portNumber;
  36.  
  37.  
  38. public string addressing { get; set; }
  39. public string hasChilds { get; set; }
  40. public string logError { get; set; }
  41. public string logWarning { get; set; }
  42. public string logInfo { get; set; }
  43. public string logDebug { get; set; }
  44. public string status { get; set; }
  45. public string deviceState { get; set; }
  46. public string timestamp { get; set; }
  47.  
  48. [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  49. public int pollingCycle { get; set; }
  50.  
  51. [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  52. public int maxReconnects = 0;
  53. [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  54. public int reconnectInterval = 2000;
  55. [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  56. public int idleTimeoutFrequency = 40000;
  57.  
  58. public string filterPolicy { get; set; }
  59. [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  60. public bool connected { get; set; }
  61. [JsonIgnore]
  62. public List<string> filters = new List<string>();
  63.  
  64. [JsonIgnore]
  65. public string idTagDeviceInit;
  66.  
  67. public int reboot;
  68.  
  69. public int pingOutput;
  70.  
  71. public int simulate;
  72.  
  73. public string comPort { get; set; }
  74.  
  75. private const string STATE_CONNECTING = "connecting";
  76. private const string STATE_CONNECTED = "connected";
  77. private const string STATE_RECONNECTING = "reconnecting";
  78. private const string STATE_DISCONNECTED = "disconnected";
  79. private const string STATE_SIMULATE = "simulate";
  80. private const string STATE_ERROR = "error";
  81.  
  82.  
  83. private int _sendQueueSleep = 20;
  84. public Queue SendQueue;
  85. public ApiConnector _apiConnector = GateWay.cocosApi;
  86.  
  87. [JsonIgnore]
  88. public int deviceStatus = 0;
  89.  
  90. [JsonIgnore]
  91. public Tag statusTag = null;
  92.  
  93. private Log _log = new Log();
  94. private string _deviceId;
  95. private bool _stopThreads = false;
  96. public List<Thread> threads = new List<Thread>();
  97. public Func<bool> reconnectFuntion;
  98. public Statusses DeviceStatus;
  99.  
  100.  
  101. bool disposed = false;
  102. SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
  103.  
  104. public Device(string deviceId, string deviceAddr)
  105. {
  106. deviceId = id;
  107. addressing = deviceAddr;
  108.  
  109. Random r = new Random();
  110. SendQueue = new Queue(200, "sndQueue-" + addressing + "::" + r.Next());
  111. DeviceStatus = new Statusses(this);
  112. if(this.idleTimeoutFrequency <= 10000)
  113. {
  114. this.idleTimeoutFrequency = 10000;
  115. }
  116. }
  117.  
  118.  
  119.  
  120. public void modifyDeviceTag(string deviceID, string tagName, string data)
  121. {
  122. Thread thread = Thread.CurrentThread;
  123. string[,] options = new string[,] { { "idDevice=" + deviceID }, { "tag=" + tagName }, { "value=" + data } };
  124. _apiConnector.patch("system", "deviceTag", null, null, options, null, deviceID);
  125. }
  126. public string getDeviceId()
  127. {
  128. return id;
  129. }
  130.  
  131. public void toggleSimMode()
  132. {
  133. simulate = simulate ^ 1;
  134. if (simulate == 1)
  135. {
  136. _log.logInfoToApi("Going in simulate modus", "", id);
  137. }
  138. else
  139. {
  140. _log.logInfoToApi("Going in live modus", "", id);
  141. }
  142. }
  143. public string getDeviceAddr()
  144. {
  145. return addressing;
  146. }
  147. public string getDeviceType()
  148. {
  149. return type;
  150. }
  151.  
  152. public void logConnectedToApi()
  153. {
  154. if (state != STATE_CONNECTED)
  155. {
  156. connected = true;
  157. state = STATE_CONNECTED;
  158. string[,] options = new string[,] { { "state=" + STATE_CONNECTED } };
  159. _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
  160.  
  161. /*
  162. if(statusTag != null)
  163. {
  164. var dataList = new Dictionary<string, string>();
  165. dataList.Add("value", STATE_CONNECTED);
  166.  
  167. _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
  168. }
  169. */
  170. }
  171. }
  172. public void logStatusToApi()
  173. {
  174. if (state.Length > 0)
  175. {
  176. if (statusTag != null)
  177. {
  178. var dataList = new Dictionary<string, string>();
  179. dataList.Add("value", state);
  180.  
  181. // _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
  182. }
  183. }
  184. }
  185. public void sendHandlerStart()
  186. {
  187. threads.Add(new Thread(() => { sendHandler(); }));
  188.  
  189. foreach (Thread thread in threads)
  190. {
  191. thread.Start();
  192. }
  193. }
  194.  
  195. public void logConnectingToApi()
  196. {
  197. if (state != STATE_CONNECTING)
  198. {
  199. state = STATE_CONNECTING;
  200. connected = false;
  201. string[,] options = new string[,] { { "state=" + STATE_CONNECTING } };
  202. _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
  203. /*
  204. if (statusTag != null)
  205. {
  206. var dataList = new Dictionary<string, string>();
  207. dataList.Add("value", STATE_CONNECTING);
  208. _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
  209. }
  210. */
  211. }
  212. }
  213. public void logReconnectingToApi()
  214. {
  215. if (state != STATE_RECONNECTING)
  216. {
  217. state = STATE_RECONNECTING;
  218. connected = false;
  219. string[,] options = new string[,] { { "state=" + STATE_RECONNECTING } };
  220. _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
  221. /*
  222. if (statusTag != null)
  223. {
  224. var dataList = new Dictionary<string, string>();
  225. dataList.Add("value", STATE_RECONNECTING);
  226. _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
  227. }
  228. */
  229. }
  230. }
  231. public void logDisconnectedToApi()
  232. {
  233. if (state != STATE_DISCONNECTED)
  234. {
  235. state = STATE_DISCONNECTED;
  236. connected = false;
  237. string[,] options = new string[,] { { "state=" + STATE_DISCONNECTED } };
  238. _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
  239. /*
  240. if (statusTag.id != null)
  241. {
  242. var dataList = new Dictionary<string, string>();
  243. dataList.Add("value", STATE_DISCONNECTED);
  244. _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
  245. }*/
  246.  
  247. }
  248. }
  249. public void logSimulateToApi()
  250. {
  251. if (state != STATE_SIMULATE)
  252. {
  253. state = STATE_SIMULATE;
  254.  
  255. string[,] options = new string[,] { { "state=" + STATE_SIMULATE } };
  256. _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
  257. /*
  258. if (statusTag != null)
  259. {
  260. var dataList = new Dictionary<string, string>();
  261. dataList.Add("value", STATE_SIMULATE);
  262. _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
  263. }*/
  264.  
  265. }
  266. }
  267. public void logErrorToApi()
  268. {
  269. if (state != STATE_ERROR)
  270. {
  271. state = STATE_ERROR;
  272. string[,] options = new string[,] { { "state=" + STATE_ERROR } };
  273. _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
  274. }
  275. }
  276.  
  277.  
  278. public void pushToQueue(SmartIntegoHandler.LinkLayerData message, int priority = 3, Func<CallbackData, bool> callbackFunction = null, List<string> holdAll = null)
  279. {
  280. SendQueue.push(message, priority, callbackFunction, holdAll);
  281. }
  282. public void sendHandler()
  283. {
  284.  
  285. while (true)
  286. {
  287. QueueItem queueItem = SendQueue.pull();
  288. if (queueItem != null)
  289. {
  290. // Pause the queue directly after we got a message to send
  291. //
  292. SendQueue.pauseQueue();
  293. SimonsVossHandler.SendQueue.push(queueItem.getMessage(), queueItem.getPriority(), queueItem.getCallbackFunction(), queueItem.getCallbackHoldAll());
  294. }
  295. else
  296. {
  297. Thread.Sleep(_sendQueueSleep); //If sendQueue is empty wait _sendQueueSleep time in ms for new message.
  298. }
  299. }
  300. }
  301. public bool passMesage(string message)
  302. {
  303. try
  304. {
  305. int matches = 0;
  306.  
  307. foreach (string regex in this.filters)
  308. {
  309. Regex regexString = new Regex(@regex);
  310. Match match = regexString.Match(message);
  311. if (match.Success)
  312. {
  313. matches++;
  314. }
  315. }
  316.  
  317. switch (this.filterPolicy)
  318. {
  319. case "allowUnfiltered":
  320. if (matches > 0)
  321. {
  322. return false;
  323. }
  324. else
  325. {
  326. return true;
  327. }
  328. break;
  329. case "dropUnfiltered":
  330. if (matches > 0)
  331. {
  332. return true;
  333. }
  334. else
  335. {
  336. return false;
  337. }
  338. break;
  339. }
  340.  
  341. return true;
  342. }
  343. catch (Exception ex)
  344. {
  345. return true;
  346. }
  347.  
  348. }
  349. public void continueSendQueue()
  350. {
  351. SendQueue.continueQueue();
  352. }
  353. public void updateFilters(JObject data, Device device)
  354. {
  355. try
  356. {
  357. device.filters.Clear();
  358. if (data["filters"]["meta"]["total"] != null && Convert.ToInt16(data["filters"]["meta"]["total"]) > 0)
  359. {
  360. foreach (JToken deviceFilters in data["filters"]["data"])
  361. {
  362. if (Convert.ToInt16(deviceFilters["data"]["status"]) == 1)
  363. {
  364. device.filters.Add(deviceFilters["data"]["expression"].ToString());
  365. }
  366. }
  367. }
  368. }
  369. catch(Exception ex)
  370. {
  371. _log.logError(ex.ToString());
  372. }
  373. }
  374.  
  375. public void Dispose()
  376. {
  377. Dispose(true);
  378. }
  379.  
  380. protected virtual void Dispose(bool disposing)
  381. {
  382. if (disposed)
  383. return;
  384.  
  385. if (disposing)
  386. {
  387. handle.Dispose();
  388. // Free any other managed objects here.
  389. //
  390. }
  391.  
  392. // Free any unmanaged objects here.
  393. //
  394.  
  395. disposed = true;
  396. GC.Collect();
  397. }
  398.  
  399. }
  400. public class Devices
  401. {
  402.  
  403. private string _deviceId;
  404. public List<Device> deviceList = new List<Device>();
  405. public Devices()
  406. {
  407.  
  408. }
  409. public Device registerDevice(string id, string deviceaddr)
  410. {
  411. Device device = new Device(id, deviceaddr);
  412. _deviceId = device.id;
  413. deviceList.Add(device);
  414.  
  415. return device;
  416. }
  417. public Device registerDeviceByJson(JObject data)
  418. {
  419. try
  420. {
  421. var settings = new JsonSerializerSettings
  422. {
  423. NullValueHandling = NullValueHandling.Ignore,
  424. MissingMemberHandling = MissingMemberHandling.Ignore
  425.  
  426. };
  427.  
  428.  
  429. if (data["portNumber"].ToString() == "")
  430. {
  431. data["portNumber"] = 0;
  432. }
  433. if (data["pollingCycle"].ToString() == "")
  434. {
  435. data["pollingCycle"] = 100;
  436. }
  437. string jsonString = data.ToString(); //Convert jObject from newtonsoft.json.linq to a string so we can convert this to an object.
  438.  
  439. var device = JsonConvert.DeserializeObject<Device>(jsonString, settings);
  440.  
  441. if (!deviceList.Contains(device))
  442. {
  443. Device dev = JsonConvert.DeserializeObject<Device>(jsonString, settings);
  444. deviceList.Add(dev);
  445. device.updateFilters(data, dev);
  446.  
  447. }
  448. else
  449. {
  450. device.Dispose();
  451. }
  452. return device;
  453. }
  454. catch(Exception ex)
  455. {
  456. Console.WriteLine(ex.Message);
  457. return null;
  458. }
  459. }
  460.  
  461.  
  462. public Device getDeviceById(string deviceId)
  463. {
  464. int listLength = deviceList.Count;
  465.  
  466. for (int i = 0; i < listLength; i++)
  467. {
  468. Device device = deviceList[i];
  469. if (device.getDeviceId() == deviceId)
  470. {
  471. return device;
  472. }
  473. }
  474. return new Device(deviceId, "00000001");// this is shit..
  475. }
  476. public void modifyDeviceTag(string deviceID, string tagName, string data)
  477. {
  478. string[,] options = new string[,] { { "idDevice=" + deviceID }, { "tag=" + tagName }, { "value=" + data } };
  479. GateWay.cocosApi.patch("accesscontrol", "deviceTag", null, null, options, null, _deviceId);
  480.  
  481. }
  482. public Device getDeviceByType(string type)
  483. {
  484. int listLength = deviceList.Count;
  485.  
  486. for (int i = 0; i < listLength; i++)
  487. {
  488. Device device = deviceList[i];
  489. if (device.getDeviceType() == type)
  490. {
  491. return device;
  492. }
  493. }
  494. return new Device(type, "00000001");// this is shit..
  495. }
  496.  
  497. public Device getDeviceByAddr(string deviceAddr)
  498. {
  499. int listLength = deviceList.Count;
  500. for (int i = 0; i < listLength; i++)
  501. {
  502. Device device = deviceList[i];
  503. if (device.getDeviceAddr() == deviceAddr)
  504. {
  505. return device;
  506. }
  507. }
  508. return null;
  509. }
  510. public List<Device> getAllDevices()
  511. {
  512. return deviceList;
  513. }
  514. }
  515. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement