Exemplo n.º 1
0
 private void SendData(object data)
 {
     try
     {
         // Serialize data to JSON
         string json = JsonConvert.SerializeObject(data);
         // Get UTF8 bytes
         byte[] sendBytes = Encoding.UTF8.GetBytes(json + Environment.NewLine);
         // Send to emitters
         this.emitters.ForEach(emiter =>
         {
             try
             {
                 emiter(sendBytes);
             }
             catch (Exception ex)
             {
                 PackageHost.WriteDebug(ex.ToString());
             }
         });
     }
     catch (Exception e)
     {
         PackageHost.WriteError(e.ToString());
     }
 }
Exemplo n.º 2
0
        public override void OnStart()
        {
            PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected);
            int interval = PackageHost.GetSettingValue <int>("Interval") * 60;

            while (PackageHost.IsRunning)
            {
                try
                {
                    using (var wc = new WebClient())
                    {
                        var     json         = wc.DownloadString("https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR");
                        var     currentTrade = JsonConvert.DeserializeObject <KrakenRootObject>(json);
                        decimal currentTradePrice;
                        if (decimal.TryParse(currentTrade?.result?.XXBTZEUR?.c?.First(), NumberStyles.Currency, CultureInfo.InvariantCulture, out currentTradePrice))
                        {
                            PackageHost.WriteDebug("BitcoinCurrentTradePrice {0}", currentTradePrice);
                            PackageHost.PushStateObject("BitcoinCurrentTradePrice", currentTradePrice, lifetime: interval);
                        }
                        else
                        {
                            PackageHost.WriteWarn("Unable to retrieve value in {0}", json);
                        }
                    }
                }
                catch (Exception ex)
                {
                    PackageHost.WriteError(ex);
                }
                Thread.Sleep(interval * 1000);
            }
        }
Exemplo n.º 3
0
 private void PushStateObject <TObject>(Func <TObject> func, bool withLifetime = true)
 {
     try
     {
         PackageHost.PushStateObject(typeof(TObject).Name, func(), lifetime: withLifetime ? (PackageHost.GetSettingValue <int>("RefreshInterval") / 1000) * 2 : 0);
     }
     catch (Exception ex)
     {
         PackageHost.WriteDebug($"Unable to push {typeof(TObject).FullName} : {ex}");
     }
 }
Exemplo n.º 4
0
        private string DoRequest(string path, string method = "GET", string payload = null)
        {
            try
            {
                HttpWebRequest request = WebRequest.CreateHttp(API_ROOT_URI + path);
                request.Method = method;
                request.Headers.Add("Access-Token", PackageHost.GetSettingValue("token"));
                if (method == "POST" && !string.IsNullOrEmpty(payload))
                {
                    byte[] payloadData = UTF8Encoding.UTF8.GetBytes(payload);
                    request.ContentType   = "application/json";
                    request.ContentLength = payloadData.Length;
                    using (Stream requestBody = request.GetRequestStream())
                    {
                        requestBody.Write(payloadData, 0, payloadData.Length);
                        requestBody.Close();
                    }
                }
                PackageHost.WriteDebug("{0} {1}", request.Method, request.RequestUri.ToString());

                WebResponse response = request.GetResponse();
                if (response.Headers.Contains("X-Ratelimit-Limit"))
                {
                    PackageHost.PushStateObject("RateLimit", new
                    {
                        Limit     = int.Parse(response.Headers["X-Ratelimit-Limit"]),
                        Remaining = int.Parse(response.Headers["X-Ratelimit-Remaining"]),
                        Reset     = int.Parse(response.Headers["X-Ratelimit-Reset"])
                    }, "PushBullet.RateLimits");
                }

                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return(reader.ReadToEnd());
                    }
            }
            catch (WebException ex)
            {
                try
                {
                    using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
                    {
                        PackageHost.WriteError("Response error: {0}", reader.ReadToEnd());
                    }
                }
                catch
                {
                    PackageHost.WriteError("Response error: {0}", ex.ToString());
                }
                return(string.Empty);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Package start
        /// </summary>
        public override void OnStart()
        {
            PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected);

            //parallel connection to the devices
            PackageHost.GetSettingAsJsonObject <IEnumerable <DeviceConfig> >("Devices").AsParallel().ForAll(dc =>
            {
                //create new device and connect
                Device device = new Device(dc.Hostname, dc.Port)
                {
                    Name = dc.Name
                };
                try
                {
                    if (device.Connect().Result)
                    {
                        PackageHost.WriteInfo($"Device {dc.Name} ({dc.Hostname}:{dc.Port}) connected");
                        device.OnNotificationReceived += (object sender, NotificationReceivedEventArgs e) =>
                        {
                            //updated device properties
                            PackageHost.PushStateObject(dc.Name, device.Properties);
                            PackageHost.WriteDebug(e.Result);
                        };

                        device.OnError += (object sender, UnhandledExceptionEventArgs e) =>
                        {
                            PackageHost.WriteError(e.ExceptionObject);
                        };

                        //initial device properties
                        PackageHost.PushStateObject(dc.Name, device.Properties);
                    }

                    _all.Add(dc.Name, device);
                }
                catch (Exception ex)
                {
                    PackageHost.WriteError($"Unable to connect to device {dc.Name} ({dc.Hostname}:{dc.Port}) : {ex.Message}");;
                }
            });

            //creation of groups
            foreach (DeviceGroupConfig gc in PackageHost.GetSettingAsJsonObject <IEnumerable <DeviceGroupConfig> >("Groups"))
            {
                DeviceGroup group = new DeviceGroup();
                foreach (Device device in gc.Devices.Select(x => _all.SingleOrDefault(d => d.Key == x).Value))
                {
                    group.Add(device);
                }

                _all.Add(gc.Name, group);
            }
        }
Exemplo n.º 6
0
        private void Events_ValueChanged(object sender, StateObjectChangedEventArgs e)
        {
            foreach (var event_ in e.NewState.DynamicValue)
            {
                //PackageHost.WriteInfo("{0} // {1}", DateTime.Parse(event_.DateDebut.ToString()) == DateTime.Parse(Alarm.DynamicValue.TimeFirstEvent.ToString()), TimeSpan.Parse(event_.TimeTrafficFromHouse.ToString()) != TimeSpan.Parse(Alarm.DynamicValue.TimeTraffic.ToString()));
                if (DateTime.Parse(event_.DateDebut.ToString()) > DateTime.Now && TimeSpan.Parse(event_.TimeTrafficFromHouse.ToString()) != TimeSpan.Parse(Alarm.DynamicValue.TimeTraffic.ToString()))
                {
                    // PackageHost.WriteInfo("{0},{1}", TimeSpan.Parse(event_.TimeTrafficFromHouse.ToString()), TimeSpan.Parse(Alarm.Value.DynamicValue.TimeTraffic.ToString()));
                    TimeSpan diff_traffic = TimeSpan.Parse(event_.TimeTrafficFromHouse.ToString()) - TimeSpan.Parse(Alarm.Value.DynamicValue.TimeTraffic.ToString()); //Nouveau temps - ancien temps
                    PackageHost.WriteInfo("Diff traffic {0}", diff_traffic);
                    TimeSpan BeforeAlarm = (DateTime.Parse(Alarm.DynamicValue.TimeFirstEvent.ToString()) - new TimeSpan(0, int.Parse(PackageHost.GetSettingValue("TpsPrep")), 0) - TimeSpan.Parse(event_.TimeTrafficFromHouse.ToString())).Subtract(DateTime.Now);
                    PackageHost.WriteDebug("Before alarm {0}", BeforeAlarm);
                    if (BeforeAlarm > diff_traffic)//Si le temps de trafic augmente on réveille plus tôt sans dépasser l'heure
                    {
                        Alarme newAlarm = new Alarme();
                        newAlarm.AlarmMinutes = int.Parse(Alarm.Value.DynamicValue.AlarmMinutes.ToString()) - diff_traffic.Minutes;
                        PackageHost.WriteDebug("AlarmMinutes {0}", newAlarm.AlarmMinutes);
                        if (newAlarm.AlarmMinutes > 60)
                        {
                            newAlarm.AlarmHour    = (int.Parse(Alarm.Value.DynamicValue.AlarmHour.ToString()) - diff_traffic.Hours + newAlarm.AlarmMinutes / 60) % 24;
                            newAlarm.AlarmMinutes = newAlarm.AlarmMinutes % 60;
                        }
                        if (newAlarm.AlarmMinutes < 0)
                        {
                            newAlarm.AlarmHour    = (int.Parse(Alarm.Value.DynamicValue.AlarmHour.ToString()) - diff_traffic.Hours + (newAlarm.AlarmMinutes - 60 / 60)) % 24;
                            newAlarm.AlarmMinutes = newAlarm.AlarmMinutes % 60;
                        }
                        else
                        {
                            newAlarm.AlarmHour = (int.Parse(Alarm.Value.DynamicValue.AlarmHour.ToString()) - diff_traffic.Hours) % 24;
                        }

                        newAlarm.IsRinging = false;
                        PackageHost.WriteDebug("Is ringing : {0}", newAlarm.IsRinging);
                        newAlarm.TimeFirstEvent = event_.DateDebut.ToString();
                        PackageHost.WriteDebug("Time 1st event {0}", newAlarm.TimeFirstEvent);
                        newAlarm.TimeTraffic = event_.TimeTrafficFromHouse.ToString();
                        PackageHost.WriteDebug("New time traffic {0}", newAlarm.TimeTraffic);
                        ChangeAlarm(newAlarm);
                        return;
                    }
                    return;
                }
            }
        }
Exemplo n.º 7
0
        private T DoRequest <T>(string path, Dictionary <string, string> parameters = null, string method = WebRequestMethods.Http.Post) where T : class
        {
            string strResponse = null;

            try
            {
                HttpWebRequest request = WebRequest.CreateHttp(API_ROOT_URI + path);
                request.Method = method;
                if (method == WebRequestMethods.Http.Post)
                {
                    if (parameters == null)
                    {
                        parameters = new Dictionary <string, string>();
                    }
                    parameters["token"] = PackageHost.GetSettingValue("Token");
                    byte[] payloadData = UTF8Encoding.UTF8.GetBytes(string.Join("&", parameters.Select(p => p.Key + "=" + HttpUtility.UrlEncode(p.Value)).ToArray()));
                    request.ContentType   = "application/x-www-form-urlencoded";
                    request.ContentLength = payloadData.Length;
                    using (Stream requestBody = request.GetRequestStream())
                    {
                        requestBody.Write(payloadData, 0, payloadData.Length);
                        requestBody.Close();
                    }
                }
                PackageHost.WriteDebug("{0} {1}", request.Method, request.RequestUri.ToString());

                WebResponse response = request.GetResponse();
                if (response.Headers.AllKeys.Contains("X-Limit-App-Limit"))
                {
                    PackageHost.PushStateObject("RateLimit", new
                    {
                        Limit     = int.Parse(response.Headers["X-Limit-App-Limit"]),
                        Remaining = int.Parse(response.Headers["X-Limit-App-Remaining"]),
                        Reset     = int.Parse(response.Headers["X-Limit-App-Reset"])
                    }, "Pushover.RateLimit");
                }

                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        strResponse = reader.ReadToEnd();
                    }
            }
            catch (WebException ex)
            {
                try
                {
                    using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
                    {
                        strResponse = reader.ReadToEnd();
                        PackageHost.WriteError("Response error: {0}", strResponse);
                    }
                }
                catch
                {
                    PackageHost.WriteError("Response error: {0}", ex.ToString());
                }
            }
            // Process response
            if (string.IsNullOrEmpty(strResponse))
            {
                return(default(T));
            }
            else
            {
                if (typeof(T) == typeof(string))
                {
                    return(strResponse as T);
                }
                else
                {
                    return(JsonConvert.DeserializeObject <T>(strResponse, PushoverContractResolver.Settings));
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            if (string.IsNullOrEmpty(PackageHost.GetSettingValue <string>("AccessToken")))
            {
                PackageHost.WriteError("AccesToken undefined. Please see documentation!");
                return;
            }

            Task.Factory.StartNew(() =>
            {
                bool authRevoked = false;
                while (PackageHost.IsRunning && !authRevoked)
                {
                    HttpWebRequest request = null;
                    try
                    {
                        PackageHost.WriteInfo("Connecting to Nest REST Streaming API ...");
                        request             = WebRequest.CreateHttp(NEST_ROOT_URI + "/?auth=" + PackageHost.GetSettingValue <string>("AccessToken"));
                        request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
                        request.Accept      = "text/event-stream";

                        WebResponse response = request.GetResponse();
                        using (Stream stream = response.GetResponseStream())
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                string line = null;
                                while (null != (line = reader.ReadLine()) && !authRevoked)
                                {
                                    if (line.Equals("event: auth_revoked"))
                                    {
                                        PackageHost.WriteError("The Access Token is revoked!");
                                        authRevoked = true;
                                        break;
                                    }
                                    else if (line.StartsWith("data:") && !line.EndsWith("null"))
                                    {
                                        dynamic nest = JsonConvert.DeserializeObject(line.Substring(5));
                                        // Devices
                                        JObject devices = nest.data.devices as JObject;
                                        foreach (var deviceType in devices)
                                        {
                                            foreach (JProperty device in deviceType.Value)
                                            {
                                                foreach (JObject deviceObject in device)
                                                {
                                                    PackageHost.PushStateObject(deviceObject.Property("name").Value.ToString(), deviceObject, "Nest." + deviceType.Key,
                                                                                new Dictionary <string, object>()
                                                    {
                                                        { "DeviceId", device.Name },
                                                        { "DeviceType", deviceType.Key },
                                                    });
                                                    Thread.Sleep(100);
                                                }
                                            }
                                        }
                                        // Structures
                                        JObject structures = nest.data.structures as JObject;
                                        foreach (var structure in structures)
                                        {
                                            JObject structureObject = structure.Value as JObject;
                                            PackageHost.PushStateObject(structureObject.Property("name").Value.ToString(), structureObject, "Nest.Structure",
                                                                        new Dictionary <string, object>()
                                            {
                                                { "StructureId", structure.Key }
                                            });
                                            Thread.Sleep(100);
                                        }
                                        // Done !
                                        PackageHost.WriteInfo("Nest StateObjects updated");
                                    }
                                    else if (!string.IsNullOrEmpty(line))
                                    {
                                        PackageHost.WriteDebug(line);
                                    }
                                }
                            }
                    }
                    catch (Exception ex)
                    {
                        PackageHost.WriteError(ex.Message);
                        Thread.Sleep(SLEEP_AFTER_ERROR);
                    }
                    finally
                    {
                        if (null != request)
                        {
                            request.Abort();
                        }
                    }
                }
            });

            // Started !
            PackageHost.WriteInfo("Nest package started!");
        }
Exemplo n.º 9
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            var config = PackageHost.GetSettingAsConfigurationSection <SnmpConfiguration>("snmpConfiguration");

            if (config != null)
            {
                foreach (Device device in config.Devices)
                {
                    PackageHost.WriteInfo($"Starting monitoring task for {device.Host}/{device.Community} (every {config.QueryInterval.TotalSeconds} sec)");
                    Task.Factory.StartNew(() =>
                    {
                        string snmpDeviceId     = $"{device.Host}/{device.Community}";
                        int stateObjectTimeout  = (int)config.QueryInterval.Add(STATEOBJECT_TIMEOUT).TotalSeconds;
                        var snmpDeviceMetadatas = new Dictionary <string, object>()
                        {
                            ["Host"]      = device.Host,
                            ["Community"] = device.Community
                        };
                        DateTime lastQuery = DateTime.MinValue;
                        while (PackageHost.IsRunning)
                        {
                            if (DateTime.Now.Subtract(lastQuery) >= config.QueryInterval)
                            {
                                try
                                {
                                    SnmpDevice snmpResult = SnmpScanner.ScanDevice(device.Host, device.Community);
                                    if (config.MultipleStateObjectsPerDevice)
                                    {
                                        // Push Description
                                        PackageHost.PushStateObject($"{snmpDeviceId}/Description", snmpResult.Description,
                                                                    lifetime: stateObjectTimeout,
                                                                    metadatas: snmpDeviceMetadatas);

                                        // Push Addresses
                                        foreach (var address in snmpResult.Addresses)
                                        {
                                            PackageHost.PushStateObject($"{snmpDeviceId}/Addresses/{address.Key}", address.Value,
                                                                        lifetime: stateObjectTimeout,
                                                                        metadatas: new Dictionary <string, object>(snmpDeviceMetadatas)
                                            {
                                                ["Key"] = address.Key
                                            });
                                        }

                                        // Push Network Interfaces
                                        foreach (var netInterface in snmpResult.Interfaces)
                                        {
                                            PackageHost.PushStateObject($"{snmpDeviceId}/Interfaces/{netInterface.Key}", netInterface.Value,
                                                                        lifetime: stateObjectTimeout,
                                                                        metadatas: new Dictionary <string, object>(snmpDeviceMetadatas)
                                            {
                                                ["Key"] = netInterface.Key
                                            });
                                        }

                                        // Push Host
                                        if (snmpResult.Host != null)
                                        {
                                            PackageHost.PushStateObject($"{snmpDeviceId}/Host", snmpResult.Host,
                                                                        lifetime: stateObjectTimeout,
                                                                        metadatas: snmpDeviceMetadatas);
                                        }

                                        // Push ProcessorsLoad
                                        if (snmpResult.ProcessorsLoad != null)
                                        {
                                            foreach (var proc in snmpResult.ProcessorsLoad)
                                            {
                                                PackageHost.PushStateObject($"{snmpDeviceId}/Processors/{proc.Key}", proc.Value,
                                                                            lifetime: stateObjectTimeout,
                                                                            metadatas: new Dictionary <string, object>(snmpDeviceMetadatas)
                                                {
                                                    ["Key"] = proc.Key
                                                });
                                            }
                                        }

                                        // Push Storages
                                        if (snmpResult.Storages != null)
                                        {
                                            foreach (var storage in snmpResult.Storages)
                                            {
                                                PackageHost.PushStateObject($"{snmpDeviceId}/Storages/{storage.Key}", storage.Value,
                                                                            lifetime: stateObjectTimeout,
                                                                            metadatas: new Dictionary <string, object>(snmpDeviceMetadatas)
                                                {
                                                    ["Key"] = storage.Key
                                                });
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // Push the full SNMP device
                                        PackageHost.PushStateObject(snmpDeviceId, snmpResult,
                                                                    lifetime: stateObjectTimeout,
                                                                    metadatas: snmpDeviceMetadatas);
                                    }
                                }
                                catch (MissingMemberException)
                                {
                                    // Device offline -> Send message "DeviceOffline" to the "SNMP" group
                                    PackageHost.CreateMessageProxy(MessageScope.ScopeType.Group, "SNMP").DeviceOffline(snmpDeviceId);
                                }
                                catch (Exception ex)
                                {
                                    PackageHost.WriteDebug($"Error while scanning {snmpDeviceId} : {ex.Message}");
                                }
                                lastQuery = DateTime.Now;
                            }
                            Thread.Sleep(1000);
                        }
                    }, TaskCreationOptions.LongRunning);
                }
            }
            PackageHost.WriteInfo("Package started!");
        }