Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading;
- using CocosQueue;
- using CocosSimonsVossHandler;
- using CocosSmartIntegoHandler;
- using CoCoSCallback;
- using CocosApiConnector;
- using cocosgateway;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using CoCosLog;
- using System.Text.RegularExpressions;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using Microsoft.Win32.SafeHandles;
- using CoCoSTagHandler;
- using CoCoSStatus;
- namespace CoCoSdevices
- {
- public class Device
- {
- public string id { get; set; }
- public string parent { get; set; }
- public string type { get; set; }
- public string name { get; set; }
- public string prefix { get; set; }
- public string prefixName { get; set; }
- public string state { get; set; }
- public string ipAddress { get; set; }
- [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
- public int portNumber;
- public string addressing { get; set; }
- public string hasChilds { get; set; }
- public string logError { get; set; }
- public string logWarning { get; set; }
- public string logInfo { get; set; }
- public string logDebug { get; set; }
- public string status { get; set; }
- public string deviceState { get; set; }
- public string timestamp { get; set; }
- [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
- public int pollingCycle { get; set; }
- [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
- public int maxReconnects = 0;
- [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
- public int reconnectInterval = 2000;
- [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
- public int idleTimeoutFrequency = 40000;
- public string filterPolicy { get; set; }
- [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
- public bool connected { get; set; }
- [JsonIgnore]
- public List<string> filters = new List<string>();
- [JsonIgnore]
- public string idTagDeviceInit;
- public int reboot;
- public int pingOutput;
- public int simulate;
- public string comPort { get; set; }
- private const string STATE_CONNECTING = "connecting";
- private const string STATE_CONNECTED = "connected";
- private const string STATE_RECONNECTING = "reconnecting";
- private const string STATE_DISCONNECTED = "disconnected";
- private const string STATE_SIMULATE = "simulate";
- private const string STATE_ERROR = "error";
- private int _sendQueueSleep = 20;
- public Queue SendQueue;
- public ApiConnector _apiConnector = GateWay.cocosApi;
- [JsonIgnore]
- public int deviceStatus = 0;
- [JsonIgnore]
- public Tag statusTag = null;
- private Log _log = new Log();
- private string _deviceId;
- private bool _stopThreads = false;
- public List<Thread> threads = new List<Thread>();
- public Func<bool> reconnectFuntion;
- public Statusses DeviceStatus;
- bool disposed = false;
- SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
- public Device(string deviceId, string deviceAddr)
- {
- deviceId = id;
- addressing = deviceAddr;
- Random r = new Random();
- SendQueue = new Queue(200, "sndQueue-" + addressing + "::" + r.Next());
- DeviceStatus = new Statusses(this);
- if(this.idleTimeoutFrequency <= 10000)
- {
- this.idleTimeoutFrequency = 10000;
- }
- }
- public void modifyDeviceTag(string deviceID, string tagName, string data)
- {
- Thread thread = Thread.CurrentThread;
- string[,] options = new string[,] { { "idDevice=" + deviceID }, { "tag=" + tagName }, { "value=" + data } };
- _apiConnector.patch("system", "deviceTag", null, null, options, null, deviceID);
- }
- public string getDeviceId()
- {
- return id;
- }
- public void toggleSimMode()
- {
- simulate = simulate ^ 1;
- if (simulate == 1)
- {
- _log.logInfoToApi("Going in simulate modus", "", id);
- }
- else
- {
- _log.logInfoToApi("Going in live modus", "", id);
- }
- }
- public string getDeviceAddr()
- {
- return addressing;
- }
- public string getDeviceType()
- {
- return type;
- }
- public void logConnectedToApi()
- {
- if (state != STATE_CONNECTED)
- {
- connected = true;
- state = STATE_CONNECTED;
- string[,] options = new string[,] { { "state=" + STATE_CONNECTED } };
- _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
- /*
- if(statusTag != null)
- {
- var dataList = new Dictionary<string, string>();
- dataList.Add("value", STATE_CONNECTED);
- _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
- }
- */
- }
- }
- public void logStatusToApi()
- {
- if (state.Length > 0)
- {
- if (statusTag != null)
- {
- var dataList = new Dictionary<string, string>();
- dataList.Add("value", state);
- // _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
- }
- }
- }
- public void sendHandlerStart()
- {
- threads.Add(new Thread(() => { sendHandler(); }));
- foreach (Thread thread in threads)
- {
- thread.Start();
- }
- }
- public void logConnectingToApi()
- {
- if (state != STATE_CONNECTING)
- {
- state = STATE_CONNECTING;
- connected = false;
- string[,] options = new string[,] { { "state=" + STATE_CONNECTING } };
- _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
- /*
- if (statusTag != null)
- {
- var dataList = new Dictionary<string, string>();
- dataList.Add("value", STATE_CONNECTING);
- _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
- }
- */
- }
- }
- public void logReconnectingToApi()
- {
- if (state != STATE_RECONNECTING)
- {
- state = STATE_RECONNECTING;
- connected = false;
- string[,] options = new string[,] { { "state=" + STATE_RECONNECTING } };
- _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
- /*
- if (statusTag != null)
- {
- var dataList = new Dictionary<string, string>();
- dataList.Add("value", STATE_RECONNECTING);
- _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
- }
- */
- }
- }
- public void logDisconnectedToApi()
- {
- if (state != STATE_DISCONNECTED)
- {
- state = STATE_DISCONNECTED;
- connected = false;
- string[,] options = new string[,] { { "state=" + STATE_DISCONNECTED } };
- _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
- /*
- if (statusTag.id != null)
- {
- var dataList = new Dictionary<string, string>();
- dataList.Add("value", STATE_DISCONNECTED);
- _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
- }*/
- }
- }
- public void logSimulateToApi()
- {
- if (state != STATE_SIMULATE)
- {
- state = STATE_SIMULATE;
- string[,] options = new string[,] { { "state=" + STATE_SIMULATE } };
- _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
- /*
- if (statusTag != null)
- {
- var dataList = new Dictionary<string, string>();
- dataList.Add("value", STATE_SIMULATE);
- _apiConnector.patch("system", "taglist", statusTag.id, null, null, dataList);
- }*/
- }
- }
- public void logErrorToApi()
- {
- if (state != STATE_ERROR)
- {
- state = STATE_ERROR;
- string[,] options = new string[,] { { "state=" + STATE_ERROR } };
- _apiConnector.patch("system", "devices", id, null, options, null, _deviceId);
- }
- }
- public void pushToQueue(SmartIntegoHandler.LinkLayerData message, int priority = 3, Func<CallbackData, bool> callbackFunction = null, List<string> holdAll = null)
- {
- SendQueue.push(message, priority, callbackFunction, holdAll);
- }
- public void sendHandler()
- {
- while (true)
- {
- QueueItem queueItem = SendQueue.pull();
- if (queueItem != null)
- {
- // Pause the queue directly after we got a message to send
- //
- SendQueue.pauseQueue();
- SimonsVossHandler.SendQueue.push(queueItem.getMessage(), queueItem.getPriority(), queueItem.getCallbackFunction(), queueItem.getCallbackHoldAll());
- }
- else
- {
- Thread.Sleep(_sendQueueSleep); //If sendQueue is empty wait _sendQueueSleep time in ms for new message.
- }
- }
- }
- public bool passMesage(string message)
- {
- try
- {
- int matches = 0;
- foreach (string regex in this.filters)
- {
- Regex regexString = new Regex(@regex);
- Match match = regexString.Match(message);
- if (match.Success)
- {
- matches++;
- }
- }
- switch (this.filterPolicy)
- {
- case "allowUnfiltered":
- if (matches > 0)
- {
- return false;
- }
- else
- {
- return true;
- }
- break;
- case "dropUnfiltered":
- if (matches > 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- break;
- }
- return true;
- }
- catch (Exception ex)
- {
- return true;
- }
- }
- public void continueSendQueue()
- {
- SendQueue.continueQueue();
- }
- public void updateFilters(JObject data, Device device)
- {
- try
- {
- device.filters.Clear();
- if (data["filters"]["meta"]["total"] != null && Convert.ToInt16(data["filters"]["meta"]["total"]) > 0)
- {
- foreach (JToken deviceFilters in data["filters"]["data"])
- {
- if (Convert.ToInt16(deviceFilters["data"]["status"]) == 1)
- {
- device.filters.Add(deviceFilters["data"]["expression"].ToString());
- }
- }
- }
- }
- catch(Exception ex)
- {
- _log.logError(ex.ToString());
- }
- }
- public void Dispose()
- {
- Dispose(true);
- }
- protected virtual void Dispose(bool disposing)
- {
- if (disposed)
- return;
- if (disposing)
- {
- handle.Dispose();
- // Free any other managed objects here.
- //
- }
- // Free any unmanaged objects here.
- //
- disposed = true;
- GC.Collect();
- }
- }
- public class Devices
- {
- private string _deviceId;
- public List<Device> deviceList = new List<Device>();
- public Devices()
- {
- }
- public Device registerDevice(string id, string deviceaddr)
- {
- Device device = new Device(id, deviceaddr);
- _deviceId = device.id;
- deviceList.Add(device);
- return device;
- }
- public Device registerDeviceByJson(JObject data)
- {
- try
- {
- var settings = new JsonSerializerSettings
- {
- NullValueHandling = NullValueHandling.Ignore,
- MissingMemberHandling = MissingMemberHandling.Ignore
- };
- if (data["portNumber"].ToString() == "")
- {
- data["portNumber"] = 0;
- }
- if (data["pollingCycle"].ToString() == "")
- {
- data["pollingCycle"] = 100;
- }
- string jsonString = data.ToString(); //Convert jObject from newtonsoft.json.linq to a string so we can convert this to an object.
- var device = JsonConvert.DeserializeObject<Device>(jsonString, settings);
- if (!deviceList.Contains(device))
- {
- Device dev = JsonConvert.DeserializeObject<Device>(jsonString, settings);
- deviceList.Add(dev);
- device.updateFilters(data, dev);
- }
- else
- {
- device.Dispose();
- }
- return device;
- }
- catch(Exception ex)
- {
- Console.WriteLine(ex.Message);
- return null;
- }
- }
- public Device getDeviceById(string deviceId)
- {
- int listLength = deviceList.Count;
- for (int i = 0; i < listLength; i++)
- {
- Device device = deviceList[i];
- if (device.getDeviceId() == deviceId)
- {
- return device;
- }
- }
- return new Device(deviceId, "00000001");// this is shit..
- }
- public void modifyDeviceTag(string deviceID, string tagName, string data)
- {
- string[,] options = new string[,] { { "idDevice=" + deviceID }, { "tag=" + tagName }, { "value=" + data } };
- GateWay.cocosApi.patch("accesscontrol", "deviceTag", null, null, options, null, _deviceId);
- }
- public Device getDeviceByType(string type)
- {
- int listLength = deviceList.Count;
- for (int i = 0; i < listLength; i++)
- {
- Device device = deviceList[i];
- if (device.getDeviceType() == type)
- {
- return device;
- }
- }
- return new Device(type, "00000001");// this is shit..
- }
- public Device getDeviceByAddr(string deviceAddr)
- {
- int listLength = deviceList.Count;
- for (int i = 0; i < listLength; i++)
- {
- Device device = deviceList[i];
- if (device.getDeviceAddr() == deviceAddr)
- {
- return device;
- }
- }
- return null;
- }
- public List<Device> getAllDevices()
- {
- return deviceList;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement