Пример #1
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            // Check settings
            if (!PackageHost.ContainsSetting("Token") || !PackageHost.ContainsSetting("UserId"))
            {
                PackageHost.WriteError("Settngs are missing, the package can't start ! Please review the API token & User Id in the package's settings");
                throw new InvalidOperationException();
            }

            // Check service
            var validateRequest = this.DoRequest <PushoverResponse>("users/validate.json", new Dictionary <string, string> {
                ["user"] = PackageHost.GetSettingValue("UserId")
            });

            if (validateRequest == null || validateRequest.Status == false)
            {
                PackageHost.WriteError($"The package can't start ! Unable to call the Pushover service" + validateRequest != null ? " : " + string.Join(", ", validateRequest.Errors) : "");
                throw new InvalidOperationException();
            }

            // Check limits
            this.DoRequest <string>("apps/limits.json?token=" + PackageHost.GetSettingValue("Token"), method: WebRequestMethods.Http.Get);

            // Ready!
            PackageHost.WriteInfo("Package started !");
        }
Пример #2
0
    /// <summary>
    /// Counts the specified table.
    /// </summary>
    public int Count(string table)
    {
        string query = "SELECT Count(*) FROM " + table;
        int    Count = -1;

        this.OpenConnection();
        try
        {
            if (this.status == "connected")
            {
                //Create Mysql Command
                MySqlCommand cmd = new MySqlCommand(query, connection);

                //ExecuteScalar will return one value (count query)
                Count = int.Parse(cmd.ExecuteScalar() + "");
                PackageHost.WriteInfo("Query succesfull ");
                PackageHost.WriteInfo(query);
                //close Connection
                this.CloseConnection();
                return(Count);
            }
            else
            {
                this.CloseConnection();
                return(Count);
            }
        }
        catch (MySqlException ex)
        {
            this.CloseConnection();
            PackageHost.WriteError($"Error number {ex.Number}");
            PackageHost.WriteError(ex.Message);
            return(-1);
        }
    }
Пример #3
0
    /// <summary>
    /// Opens the connection.
    /// </summary>
    public void OpenConnection()
    {
        try
        {
            connection.Open();
            PackageHost.WriteInfo("MySQL server connected");
            this.status = "connected"; //Set status to connected
        }
        catch (MySqlException ex)      //Show error number + most common error advice
        {
            PackageHost.WriteInfo(ex.Number);
            this.status = "disconnected";
            switch (ex.Number)
            {
            case 0:
                PackageHost.WriteError("Cannot connect to server.  Contact administrator");
                break;

            case 1045:
                PackageHost.WriteError("Invalid username/password, please try again");
                break;

                PackageHost.WriteError($"Connection error = {ex.Number}");
                PackageHost.WriteError($"Connection error = {ex.Message}");
            }
        }
    }
Пример #4
0
    } //table = "tableinfo (name, age)"  values = "('John Smith', '33')"

    /// <summary>
    /// Updates a statement in a table
    /// </summary>
    public void Update(string table, string values, string condition) //table="nomtable (id1,id2,id3)" values="name='Joe', age='22'"  condition="name='John Smith'"
    {
        string query = "UPDATE " + table + " SET " + values + " WHERE " + condition;

        //open connection
        this.OpenConnection();
        try
        {
            if (this.status == "connected")
            {
                //create mysql command
                MySqlCommand cmd = new MySqlCommand();
                //Assign the query using CommandText
                cmd.CommandText = query;
                //Assign the connection using Connection
                cmd.Connection = connection;
                PackageHost.WriteInfo($"Query succesfull ", query);
                PackageHost.WriteInfo(query);
                //Execute query
                cmd.ExecuteNonQuery();

                //close connection
                this.CloseConnection();
            }
        }
        catch (MySqlException ex)
        {
            PackageHost.WriteError($"Error number {ex.Number}");
            PackageHost.WriteError(ex.Message);
        }
    }
Пример #5
0
    /// <summary>
    /// To enter an SQL request
    /// </summary>
    public void Request(string query)
    {
        //open connection
        this.OpenConnection();
        try
        {
            if (this.status == "connected")
            {
                //create mysql command
                MySqlCommand cmd = new MySqlCommand();
                //Assign the query using CommandText
                cmd.CommandText = query;
                //Assign the connection using Connection
                cmd.Connection = connection;

                //Execute query
                cmd.ExecuteNonQuery();
                PackageHost.WriteInfo($"Query succesfull ", query);
                PackageHost.WriteInfo(query);
                //close connection
                this.CloseConnection();
            }
        }
        catch (MySqlException ex)
        {
            PackageHost.WriteError($"Error number {ex.Number}");
            PackageHost.WriteError(ex.Message);
        }
    }
Пример #6
0
        /// <summary>
        /// Reads the M3U playlist from the specified URI.
        /// </summary>
        /// <param name="uri">The M3U URI.</param>
        /// <returns>Track's list</returns>
        public static List <string> Read(string uri)
        {
            var playlist = new List <string>();

            try
            {
                if (uri.StartsWith("http", StringComparison.InvariantCultureIgnoreCase))
                {
                    // Download the M3U and read all lines
                    playlist.AddRange(new WebClient().DownloadString(uri).Split('\n'));
                }
                else if (File.Exists(uri))
                {
                    // Open file and read all lines
                    playlist.AddRange(File.ReadAllLines(uri));
                }
                // Remove comments
                playlist = playlist.Where(u => !u.StartsWith("#")).ToList();
            }
            catch (Exception ex)
            {
                PackageHost.WriteError("Can't read the playlist '{0}' : {1}", uri, ex.ToString());
            }

            return(playlist);
        }
        public void SendKey(int id, SceneCommand command)
        {
            string         url     = this.GenerateUrl(id, command);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "POST";
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(url);
            request.ContentLength = byteArray.Length;
            request.ContentType   = @"application/json";
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            long length = 0;

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    length = response.ContentLength;
                    PackageHost.WriteInfo("Command send to Jeedom");
                }
            }
            catch (WebException ex)
            {
                PackageHost.WriteError(ex);
            }
        }
Пример #8
0
        private bool SetWindowCoveringAction(DeviceActionRequest request)
        {
            VeraNet.Objects.Devices.WindowCovering device = vera.Devices.FirstOrDefault(s => s.Id == request.DeviceID) as VeraNet.Objects.Devices.WindowCovering;
            if (device != null)
            {
                PackageHost.WriteInfo("Window Covering '{0}' {1} ({2})", request.Action.ToString(), device.Name, device.Id);

                switch (request.Action)
                {
                case WindowCoveringAction.UP:
                    device.Up();
                    break;

                case WindowCoveringAction.DOWN:
                    device.Down();
                    break;

                case WindowCoveringAction.STOP:
                    device.Stop();
                    break;

                default:
                    break;
                }

                return(true);
            }
            else
            {
                PackageHost.WriteError("The device #'{0}' not found !", request.DeviceID);
                return(false);
            }
        }
Пример #9
0
 private Response <TResult> GetResponse <TResult>(string path)
 {
     try
     {
         string AddressURL = ROOT_URI + path;
         using (WebClient webClient = new WebClient()
         {
             Encoding = Encoding.UTF8
         })
         {
             var result = webClient.DownloadString(AddressURL);
             return(JsonConvert.DeserializeObject <Response <TResult> >(result, new JsonSerializerSettings()
             {
                 Converters = new List <JsonConverter>()
                 {
                     new PropertyNamesMatchingConverter()
                 }
             }));
         }
     }
     catch (Exception ex)
     {
         PackageHost.WriteError($"Error on getting {path} : {ex.ToString()}");
         return(new Response <TResult>()
         {
             Error = ex.Message,
             HasError = true,
             Metadatas = new Metadata()
             {
                 ResponseDate = DateTime.Now.ToString(), RequestURI = path
             }
         });
     }
 }
Пример #10
0
 /// <summary>
 /// Authentificate to ZoneMinder.
 /// </summary>
 /// <returns>
 ///   <c>true</c> if access granted
 /// </returns>
 public override bool Authentificate()
 {
     try
     {
         string token = CalculateHashMD5(
             PackageHost.GetSettingValue("SecretHash") +
             PackageHost.GetSettingValue("Username") +
             PackageHost.GetSettingValue("PasswordHash") +
             DateTime.Now.Hour.ToString() +
             DateTime.Now.Day.ToString() +
             (DateTime.Now.Month - 1).ToString() +
             (DateTime.Now.Year - 1900).ToString());
         string response = this.DoZMRequest($"index.php?auth={token}");
         // Test API access (thrown 401 web exception if access denied)
         this.CheckAccess(this.AuthentificationToken == null);
         // Access granted
         this.AuthentificationToken = token;
         return(true);
     }
     catch (WebException ex)
     {
         PackageHost.WriteError($"Authentification failed : {ex.Message}");
     }
     return(false);
 }
Пример #11
0
 /// <summary>
 /// Called when the package is started.
 /// </summary>
 public override void OnStart()
 {
     Task.Factory.StartNew(async() =>
     {
         while (PackageHost.IsRunning)
         {
             try
             {
                 if (PackageHost.ContainsSetting("Monitoring"))
                 {
                     dynamic config = PackageHost.GetSettingAsJsonObject("Monitoring", true);
                     foreach (dynamic ressource in config)
                     {
                         string name = ressource.Name.Value;
                         if (monitoringChecks.ContainsKey(name) == false ||
                             DateTime.Now.Subtract(monitoringChecks[name]).TotalSeconds >= (ressource["Interval"] != null ? ressource.Interval.Value : DEFAULT_CHECK_INTERVAL))
                         {
                             this.CheckResource(name, ressource.Type.Value, ressource);
                             monitoringChecks[name] = DateTime.Now;
                         }
                     }
                 }
             }
             catch (Exception ex)
             {
                 PackageHost.WriteError("Monitor task error : " + ex.Message);
             }
             await Task.Delay(1000);
         }
     }, TaskCreationOptions.LongRunning);
 }
Пример #12
0
        public void RefreshAll()
        {
            PackageHost.WriteInfo("Refreshing Paradox system");
            try
            {
                for (int i = 1; i <= PackageHost.GetSettingValue <int>("numberofAreas"); i++)
                {
                    PackageHost.WriteInfo("Refreshing area " + i.ToString());
                    ParadoxManager.Instance.RequestArea((Area)i);
                    Thread.Sleep(10);
                    ParadoxManager.Instance.RequestAreaLabel((Area)i);
                    Thread.Sleep(10);
                }

                for (int i = 1; i <= PackageHost.GetSettingValue <int>("numberofUsers"); i++)
                {
                    PackageHost.WriteInfo("Refreshing User " + i.ToString());
                    ParadoxManager.Instance.RequestUserLabel(i);
                    Thread.Sleep(10);
                }

                for (int i = 1; i <= PackageHost.GetSettingValue <int>("numberofZones"); i++)
                {
                    PackageHost.WriteInfo("Refreshing zone " + i.ToString());
                    ParadoxManager.Instance.RequestZone((Zone)i);
                    Thread.Sleep(10);
                    ParadoxManager.Instance.RequestZoneLabel((Zone)i);
                    Thread.Sleep(10);
                }
            }
            catch (Exception ex)
            {
                PackageHost.WriteError("Error to RefreshAll : " + ex.ToString());
            }
        }
Пример #13
0
        private void PushItem <TItem>(int id, Action <TItem> updateAction = null) where TItem : BaseParadoxItem, new()
        {
            try
            {
                string identifiant = typeof(TItem).Name + id;
                TItem  item        = null;

                lock (syncLock)
                {
                    if (!items.ContainsKey(identifiant))
                    {
                        item = new TItem()
                        {
                            Id = id, LastActivity = DateTime.Now, Type = typeof(TItem).Name
                        };
                        this.items.Add(identifiant, item);
                    }

                    item = this.items[identifiant] as TItem;
                    updateAction?.Invoke(item);
                }

                PackageHost.PushStateObject(identifiant, item, "Paradox." + typeof(TItem).Name, new Dictionary <string, object>()
                {
                    { "Id", id },
                    { "Type", typeof(TItem).Name }
                });
            }
            catch (Exception ex)
            {
                PackageHost.WriteError("Error to push item : " + ex.ToString());
            }
        }
Пример #14
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);
            }
        }
Пример #15
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());
     }
 }
Пример #16
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            // Create the STB service
            this.orangeBox = new OrangeSetTopBox(PackageHost.GetSettingValue("Hostname"));
            // Attach the event notification
            this.orangeBox.EventNotificationReceived += (s, e) =>
            {
                if (PackageHost.GetSettingValue <bool>("Verbose"))
                {
                    PackageHost.WriteInfo($"Event from {this.orangeBox.CurrentState.MacAddress} : {e.Notification.EventType}");
                }
                // Update the current state
                PackageHost.PushStateObject("State", this.orangeBox.CurrentState);
            };
            this.orangeBox.StateUpdated += (s, e) => PackageHost.PushStateObject("State", this.orangeBox.CurrentState);
            // Get the current state
            var task = this.orangeBox.GetCurrentState();

            if (task.Wait(10000) && task.IsCompleted && !task.IsFaulted)
            {
                // Listening events
                this.orangeBox.StartListening(async(error) =>
                {
                    PackageHost.WriteError(error.ToString());
                    await Task.Delay(2000);
                });
                // Read!
                PackageHost.WriteInfo($"Connected to {task.Result.FriendlyName} ({task.Result.MacAddress})");
            }
            else
            {
                throw new Exception("Unable to connect to your Orange set-top box! Check your configuration & network");
            }
        }
Пример #17
0
        public override void OnStart()
        {
            PackageHost.WriteInfo("Coucou :3 IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected);
            if (PackageHost.IsConnected == false)
            {
                PackageHost.WriteError("Euh, y'a quelqu'un ?????");
                PackageHost.WriteWarn("Je me sens seul :'(");
            }

            else
            {
                PackageHost.WriteInfo("Youpi youpi je suis connecté :D");
            }

            Random rnd = new Random();

            Task.Factory.StartNew(async() =>
            {
                while (PackageHost.IsRunning)
                {
                    var myData = new TempHumdi()
                    {
                        Temperature = rnd.Next(0, 50),
                        Humidity    = rnd.Next(10, 90)
                    };
                    PackageHost.PushStateObject("TemperatureHumidity", myData, lifetime: 15);
                    await Task.Delay(PackageHost.GetSettingValue <Int32>("Interval"));
                }
            });
        }
Пример #18
0
        public PushoverResponse PushNotification(string message, string title = null, Url url = null, string user = null, string[] devices = null, Sound sound = Sound.Pushover, Priority priority = Priority.Normal, int timestamp = 0, EmergencyOptions emergencyOptions = null)
        {
            var parameters = new Dictionary <string, string>
            {
                ["user"]    = user ?? PackageHost.GetSettingValue("UserId"),
                ["message"] = message
            };

            if (parameters.Any(p => string.IsNullOrEmpty(p.Value)))
            {
                return(new PushoverResponse()
                {
                    Errors = new string[] { "Some arguments are missing !" }
                });
            }
            else
            {
                if (title != null)
                {
                    parameters["title"] = title;
                }
                if (devices != null)
                {
                    parameters["device"] = string.Join(",", devices);
                }
                if (sound != Sound.Pushover)
                {
                    parameters["sound"] = sound.ToString().ToLower();
                }
                if (priority != Priority.Normal)
                {
                    parameters["priority"] = ((int)priority).ToString();
                    if (priority == Priority.Emergency)
                    {
                        parameters["retry"]  = emergencyOptions != null && emergencyOptions.Retry > 0 ? emergencyOptions.Retry.ToString() : PackageHost.GetSettingValue("DefaultEmergencyRetry");
                        parameters["expire"] = emergencyOptions != null && emergencyOptions.Expire > 0 ? emergencyOptions.Expire.ToString() : PackageHost.GetSettingValue("DefaultEmergencyExpiration");
                    }
                }
                if (timestamp > 0)
                {
                    parameters["timestamp"] = timestamp.ToString();
                }
                if (url != null && !string.IsNullOrEmpty(url.URL))
                {
                    parameters["url"] = url.URL;
                    if (!string.IsNullOrEmpty(url.Title))
                    {
                        parameters["url_title"] = url.Title;
                    }
                }

                PushoverResponse response = this.DoRequest <PushoverResponse>("messages.json", parameters);
                if (!response.Status)
                {
                    PackageHost.WriteError("Unable to send the notificaiton ", string.Join(", ", response.Errors));
                }
                return(response);
            }
        }
Пример #19
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            Dictionary <string, BatteryState> batteries = new Dictionary <string, BatteryState>();

            Task.Factory.StartNew(() =>
            {
                while (PackageHost.IsRunning)
                {
                    try
                    {
                        ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Battery");
                        ManagementObjectSearcher searcher     = new ManagementObjectSearcher(query);
                        ManagementObjectCollection collection = searcher.Get();

                        foreach (ManagementObject mo in collection)
                        {
                            // Register new battery
                            string deviceID = BitConverter.ToString(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(mo["DeviceID"].ToString()))).Replace("-", "");
                            if (!batteries.ContainsKey(deviceID))
                            {
                                batteries.Add(deviceID, new BatteryState()
                                {
                                    Name = mo["Name"].ToString().Trim(), DeviceID = mo["DeviceID"].ToString().Trim()
                                });
                            }

                            // Get current properties
                            int estimatedChargeRemaining = Convert.ToInt32(mo["EstimatedChargeRemaining"].ToString());
                            int estimatedRunTime         = Convert.ToInt32(mo["EstimatedRunTime"].ToString());
                            int statusCode = Convert.ToInt32(mo["BatteryStatus"].ToString());
                            string state   = mo["Status"].ToString().Trim();

                            // If changes
                            if (batteries[deviceID].EstimatedChargeRemaining != estimatedChargeRemaining ||
                                batteries[deviceID].EstimatedRunTime != estimatedRunTime ||
                                batteries[deviceID].State != state ||
                                batteries[deviceID].StatusCode != statusCode)
                            {
                                // Update
                                batteries[deviceID].EstimatedChargeRemaining = estimatedChargeRemaining;
                                batteries[deviceID].EstimatedRunTime         = estimatedRunTime;
                                batteries[deviceID].State      = state;
                                batteries[deviceID].StatusCode = statusCode;
                                // Push to Constellation
                                PackageHost.PushStateObject(deviceID, batteries[deviceID]);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        PackageHost.WriteError("Critical error : " + ex.ToString());
                    }

                    Thread.Sleep(PackageHost.GetSettingValue <int>("RefreshInterval"));
                }
            });

            PackageHost.WriteInfo("Ready!");
        }
Пример #20
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            // Create and start thread to retrieve calendars
            this.timer = new Timer(new TimerCallback((o) =>
            {
                int numberOfDaysToInclude = PackageHost.GetSettingValue <int>("NumberOfDaysToInclude");
                foreach (var accountName in PackageHost.GetSettingValue <string>("CalendarAccounts").Split(';'))
                {
                    try
                    {
                        int atIndex = accountName.IndexOf('@');
                        if (atIndex <= 0)
                        {
                            PackageHost.WriteError("Invalid account: " + accountName);
                        }
                        else
                        {
                            var mailboxName = accountName.Substring(0, atIndex);
                            // Find appointements
                            var calendarFolderId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(accountName));
                            var calendarView     = new CalendarView(DateTime.Now, DateTime.Now.AddDays(numberOfDaysToInclude));
                            var appointments     = this.CreateExchangeService().FindAppointments(calendarFolderId, calendarView).Items.Select(item => new Appointment()
                            {
                                Id      = item.Id.UniqueId,
                                Subject = item.Subject,
                                //Body = item.Body.Text,
                                Start    = item.Start,
                                End      = item.End,
                                Location = item.Location,
                                Duration = item.Duration
                            }).ToList();
                            // Push appointements list
                            PackageHost.PushStateObject("Appointments4" + mailboxName, appointments,
                                                        lifetime: (int)TimeSpan.FromMinutes(PackageHost.GetSettingValue <int>("RefreshInterval")).TotalSeconds * 2,
                                                        metadatas: new Dictionary <string, object>()
                            {
                                { "StartDate", calendarView.StartDate },
                                { "EndDate", calendarView.EndDate },
                                { "Mailbox", accountName }
                            });
                            // And log ...
                            PackageHost.WriteInfo("Calendar of '{0}' pushed into the Constellation for the next {1} day(s) ({2} appointement(s)).", accountName, numberOfDaysToInclude, appointments.Count);
                        }
                    }
                    catch (Exception ex)
                    {
                        PackageHost.WriteError("Error while getting the calendar of '{0}' : {1}", accountName, ex.ToString());
                    }
                }
            }), null, 0, (int)TimeSpan.FromMinutes(PackageHost.GetSettingValue <int>("RefreshInterval")).TotalMilliseconds);

            // Update settings callback
            PackageHost.SettingsUpdated += (s, e) =>
            {
                // Update timer interval
                this.timer.Change(0, (int)TimeSpan.FromMinutes(PackageHost.GetSettingValue <int>("RefreshInterval")).TotalMilliseconds);
            };
        }
Пример #21
0
        /// <summary>
        /// Get equipement values then save it to Constellation
        /// </summary>
        private void SaveEquipement(string mac)
        {
            Response read            = null;
            Type     modelType       = null;
            Type     modelReportType = null;
            dynamic  model           = null;
            dynamic  modelReport     = null;

            //// Try to get setting based on equipement SID
            if (!PackageHost.TryGetSettingValue <string>(mac, out name))
            {
                name = mac;
            }

            try
            {
                //// Get response from read function
                read = this.ReadEquipement(mac);

                //// Create instance of model class
                modelType = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.GetCustomAttribute <Response.XiaomiEquipementAttribute>()?.Model == read.Model);

                if (modelType == null)
                {
                    PackageHost.WriteError("{0} type not found !", read.Model);
                    return;
                }

                model = Activator.CreateInstance(modelType);

                //// Create report instance of model class
                modelReportType = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.GetCustomAttribute <Response.XiaomiEquipementAttribute>()?.Model == read.Model + "_report");

                if (modelReportType == null)
                {
                    PackageHost.WriteError("{0}_report type not found !", read.Model);
                    return;
                }

                modelReport = Activator.CreateInstance(modelReportType);
            }
            catch (Exception ex)
            {
                PackageHost.WriteError("Error ReadEquipement : {0}", ex);
                return;
            }

            //// Deserialize data part of the report
            dynamic data = JsonConvert.DeserializeObject(Convert.ToString(read.Data), modelReportType);

            //// Add informations to Report class
            model.BatteryLevel = System.Convert.ToInt32(System.Math.Floor((data.Voltage - 2800) * 0.33));
            model.Sid          = mac;
            model.Report       = data;

            //// Pushing the SO
            PackageHost.PushStateObject <dynamic>(name, model);
        }
Пример #22
0
        public override void OnStart()
        {
            try
            {
                PerfCounterSection config = PackageHost.GetSettingAsConfigurationSection <PerfCounterSection>("PerfCounters");
                foreach (PerfCounter counter in config.PerfCounters)
                {
                    try
                    {
                        var perfCounter = new PerformanceCounter(counter.CategoryName, counter.CounterName, true);
                        if (!string.IsNullOrEmpty(counter.InstanceName))
                        {
                            perfCounter.InstanceName = counter.InstanceName;
                        }
                        if (!string.IsNullOrEmpty(counter.MachineName))
                        {
                            perfCounter.MachineName = counter.MachineName;
                        }
                        perfCounter.NextValue();
                        counters.Add(counter.ID, perfCounter);
                    }
                    catch (Exception ex)
                    {
                        PackageHost.WriteError($"Unable to add the counter {counter.CategoryName}:{counter.CounterName} : {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to initialize the package. Check package settings !", ex);
            }

            Task.Factory.StartNew(() =>
            {
                while (PackageHost.IsRunning)
                {
                    try
                    {
                        foreach (var counter in counters)
                        {
                            PackageHost.PushStateObject <float>(counter.Key, counter.Value.NextValue(), metadatas: new Dictionary <string, object>()
                            {
                                ["CategoryName"] = counter.Value.CategoryName,
                                ["CounterName"]  = counter.Value.CounterName,
                                ["InstanceName"] = counter.Value.InstanceName,
                                ["MachineName"]  = counter.Value.MachineName == "." ? Environment.MachineName : counter.Value.MachineName,
                            });
                        }

                        Thread.Sleep(PackageHost.GetSettingValue <int>("RefreshInterval"));
                    }
                    catch { }
                }
            }, TaskCreationOptions.LongRunning);

            PackageHost.WriteInfo($"{counters.Count} counter(s) loaded. Package started!");
        }
Пример #23
0
        private bool ExecuteCommand(string command, string param, int tries = 3)
        {
            string         payload = string.Format("{{ \"command\":\"{0}\",\"params\":{1} }}", command, param);
            HttpWebRequest request = null;

            try
            {
                request        = WebRequest.CreateHttp(string.Format(SDM_API_URI + ":executeCommand", PackageHost.GetSettingValue <string>("ProjectId"), PackageHost.GetSettingValue <string>("DeviceId")));
                request.Method = "POST";
                request.Headers.Add(string.Format("Authorization: Bearer {0}", AccessToken));
                request.ContentType = "application/json";
                request.Accept      = "*/*";
                request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);

                using (Stream requestBody = request.GetRequestStream())
                {
                    byte[] payloadData = UTF8Encoding.UTF8.GetBytes(payload);
                    requestBody.Write(payloadData, 0, payloadData.Length);
                    requestBody.Close();
                }

                var response = request.GetResponse() as HttpWebResponse;
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string line = null;
                        while ((null != (line = reader.ReadLine())))
                        {
                            if (!string.IsNullOrEmpty(line))
                            {
                                PackageHost.WriteInfo("POST '{1}' to '{0}'", command, param);
                            }
                        }
                    }

                return(response.StatusCode == HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                PackageHost.WriteError("Error on '{0}' : '{1}'", command, ex.ToString());
                if (tries-- > 0)
                {
                    return(this.ExecuteCommand(command, param, tries));
                }
                else
                {
                    return(false);
                }
            }
            finally
            {
                if (null != request)
                {
                    request.Abort();
                }
            }
        }
Пример #24
0
 public void SetVolume(float level)
 {
     if (level >= 0 && level <= 1)
     {
         this.outPlayer.Volume = level;
     }
     else
     {
         PackageHost.WriteError("SetVolume: Error, the level must be between 0.0 and 1.0");
     }
 }
Пример #25
0
        /// <summary>
        /// OnStart
        /// </summary>
        public override void OnStart()
        {
            PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected);

            if (PackageHost.TryGetSettingAsJsonObject <IEnumerable <TPLinkConfig> >("devices", out IEnumerable <TPLinkConfig> configs))
            {
                Task.Factory.StartNew(async() =>
                {
                    //pool to get devices informations
                    while (PackageHost.IsRunning)
                    {
                        int soLifeTime = Math.Max(PackageHost.GetSettingValue <int>("poolingInterval") * 2, 30000) / 1000;

                        foreach (TPLinkConfig config in configs)
                        {
                            try
                            {
                                if (config.Type == TPLink.SmartHome.SystemType.PlugWithEnergyMeter)
                                {
                                    TPLink.SmartHome.PlugWithEnergyMeterClient plug = new TPLink.SmartHome.PlugWithEnergyMeterClient(config.HostName);
                                    TPLink.SmartHome.ConsumptionInfo consumption    = await plug.GetConsumptionAsync();
                                    TPLink.SmartHome.SystemInfo systemInfos         = await plug.GetSystemInfoAsync();
                                    TPLink.SmartHome.OutputState state = await plug.GetOutputAsync();

                                    PlugWithEnergyMeterInformations plugInfos = PlugWithEnergyMeterInformations.CreateFromSystemInfosAndOutputStateAndConsumption(systemInfos, state, consumption);

                                    PackageHost.PushStateObject($"TPLink-{config.HostName}", plugInfos, lifetime: soLifeTime);
                                }
                                else if (config.Type == TPLink.SmartHome.SystemType.Plug)
                                {
                                    TPLink.SmartHome.PlugClient plug        = new TPLink.SmartHome.PlugClient(config.HostName);
                                    TPLink.SmartHome.SystemInfo systemInfos = await plug.GetSystemInfoAsync();
                                    TPLink.SmartHome.OutputState state      = await plug.GetOutputAsync();

                                    PlugInformations plugInfos = PlugInformations.CreateFromSystemInfosAndOutputState(systemInfos, state);

                                    PackageHost.PushStateObject($"TPLink-{config.HostName}", plugInfos, lifetime: soLifeTime);
                                }
                            }
                            catch (TimeoutException ex)
                            {
                                PackageHost.WriteError($"Connection timeout for TPLink device '{config?.HostName}' : {ex.Message}");
                            }
                            catch (Exception ex)
                            {
                                PackageHost.WriteError($"An unknown error has occurred for TPLink device '{config?.HostName}' : {ex}");
                            }
                        }

                        await Task.Delay(PackageHost.GetSettingValue <int>("poolingInterval"));
                    }
                }, TaskCreationOptions.LongRunning);
            }
        }
Пример #26
0
        /// <summary>
        /// On Start
        /// </summary>
        public override void OnStart()
        {
            PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected);

            string developerKey = PackageHost.GetSettingValue <string>("DeveloperKey");
            string login        = PackageHost.GetSettingValue <string>("Login");
            string password     = PackageHost.GetSettingValue <string>("Password");

            //register the developer key to be used by the API
            Net.RestHelper.RegisterDeveloperKey(developerKey);

            Task.Factory.StartNew(async() =>
            {
                while (PackageHost.IsRunning)
                {
                    try
                    {
                        dynamic auth = null;

                        if (!_connected)
                        {
                            //connection
                            auth = await BetaSeries.Net.Models.MEMBERS.Auth.Connect(login, password);

                            if (auth != null)
                            {
                                _connected = true;
                                _userToken = auth.user.id.ToString();
                                PackageHost.WriteInfo("Connection to BetaSeries established.");
                            }
                        }

                        if (_connected)
                        {
                            dynamic planning = GetPlanning();

                            if (planning != null)
                            {
                                //push state object
                                PackageHost.PushStateObject("Planning", planning);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        PackageHost.WriteError($"An error occurred while fetching BetaSeries planning : {ex.Message}");
                        PackageHost.WriteError(ex);
                    }

                    //wait
                    await Task.Delay(PackageHost.GetSettingValue <int>("PlanningPullInterval") * 60 * 1000);
                }
            }, TaskCreationOptions.LongRunning);
        }
Пример #27
0
 /// <summary>
 /// Send request to get id of items connected to gateway
 /// </summary>
 public void FindEquipementsList()
 {
     try
     {
         this.SendCommand(CommandType.GetIdList, null, null);
     }
     catch (Exception ex)
     {
         PackageHost.WriteError("Error FindEquipementList : {0}", ex);
     }
 }
Пример #28
0
 /// <summary>
 /// Send to gateway command to read one equipement
 /// </summary>
 /// <param name="sid">SID of the equipement.</param>
 public void ReadEquipement(string sid)
 {
     try
     {
         this.SendCommand(CommandType.Read, sid, null);
     }
     catch (Exception ex)
     {
         PackageHost.WriteError("Error ReadEquipement : {0}", ex);
     }
 }
Пример #29
0
 public void SetBrightness(int targetBrightness)
 {
     if (targetBrightness < 0 || targetBrightness > 100)
     {
         PackageHost.WriteError("Invalid value !");
     }
     else
     {
         WindowsBrightness.SetBrightness((byte)targetBrightness);
     }
 }
Пример #30
0
 public void PlayWaveIn(string name)
 {
     if (this.waveInPlayers.ContainsKey(name))
     {
         this.isInPlaylist = false;
         this.PlayWaveProvider(this.waveInPlayers[name]);
     }
     else
     {
         PackageHost.WriteError("PlayWaveIn error : '{0}' not exist", name);
     }
 }