/// <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);
        }
        public string Requete(string command, string value = "", string value2 = "")
        {
            string         url     = string.Format("http://{0}/jsonrpc.js", PackageHost.GetSettingValue("ServerUrl"));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            if (PackageHost.TryGetSettingValue <string>("ServerUser", out string user))
            {
                if (PackageHost.TryGetSettingValue <string>("ServerPassword", out string password))
                {
                    string credentials = string.Format("{0}:{1}", PackageHost.GetSettingValue("ServerUser"), PackageHost.GetSettingValue("ServerPassword"));
                    request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
                    request.PreAuthenticate = true;
                }
                else
                {
                    PackageHost.WriteError("Impossible de récupérer le setting 'Password' en string");
                }
            }
            request.Method      = "POST";
            request.ContentType = @"application/json";
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(command);
            request.ContentLength = byteArray.Length;
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            }
            catch (WebException ex)
            {
                using (var errorResponse = (HttpWebResponse)ex.Response)
                {
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected);

            PackageHost.TryGetSettingValue("interval", out int interval, 6);

            Refresh(null, null);

            // Set a timer to refesh prices every n hours
            _timer = new Timer(interval * 3600 * 1000)
            {
                AutoReset = true
            };
            _timer.Elapsed += Refresh;
            _timer.Start();
        }
Beispiel #4
0
        /// <summary>
        /// Push state object to constellation
        /// </summary>
        /// <param name="sid">Model sid</param>
        /// <param name="model">the model</param>
        private void PushStateObject(string sid, dynamic model)
        {
            string name;

            if (model.Model.Equals(EquipmentType.Gateway))
            {
                name = EquipmentType.Gateway.GetRealName();
            }
            //// Get personal name based on user setting
            else if (!PackageHost.TryGetSettingValue <string>(sid, out name))
            {
                name = sid;
            }

            PackageHost.PushStateObject <dynamic>(name, model);
        }
Beispiel #5
0
        public Forecast RainForecast(int townId)
        {
            string ForecastUrl = null;

            if (!PackageHost.TryGetSettingValue <string>("ForecastUrl", out ForecastUrl))
            {
                PackageHost.WriteError("Impossible de récupérer le setting 'ForecastUrl' en string");
            }
            try
            {
                string   FinalUrl   = String.Format(ForecastUrl, townId);
                var      syncClient = new WebClient();
                var      content    = syncClient.DownloadString(FinalUrl);
                Forecast forecast   = JsonConvert.DeserializeObject <Forecast>(content);
                return(forecast);
            }
            catch (Exception ex)
            {
                PackageHost.WriteError("Erreur : {0}", ex);
                return(null);
            }
        }
Beispiel #6
0
        public List <Town> FindId(int postalCode)
        {
            string IdUrl = null;

            if (!PackageHost.TryGetSettingValue <string>("IdUrl", out IdUrl))
            {
                PackageHost.WriteError("Impossible de récupérer le setting 'IdUrl' en string");
            }
            try
            {
                string      FinalUrl   = String.Format(IdUrl, postalCode);
                var         syncClient = new WebClient();
                var         content    = syncClient.DownloadString(FinalUrl);
                List <Town> Towns      = JsonConvert.DeserializeObject <List <Town> >(content);
                return(Towns);
            }
            catch (Exception ex)
            {
                PackageHost.WriteError("Erreur : {0}", ex);
                return(null);
            }
        }
Beispiel #7
0
        public Vigilance GetVigilance(int Departement)
        {
            string Url = null;

            if (!PackageHost.TryGetSettingValue <string>("Url", out Url))
            {
                PackageHost.WriteError("Impossible de récupérer le setting 'Url' en string");
            }
            Vigilance vigilance = new Vigilance();
            string    risque    = "";

            if (Departement == 92 || Departement == 93 || Departement == 94)
            {
                Departement = 75;
            }

            var departement = Departement.ToString();
            var doc         = XDocument.Load(Url);
            var depnode     = doc.Descendants("risque").Where(c => c.Parent.Attribute("dep").Value == departement);

            if (depnode.Any())
            {
                List <VigilanceMeteoFrance.Models.Type> Type = new List <VigilanceMeteoFrance.Models.Type>();
                foreach (var x in depnode)
                {
                    switch (x.Attribute("val").Value)
                    {
                    case "1":
                        risque = "vent";
                        break;

                    case "2":
                        risque = "pluie-inondation";
                        break;

                    case "3":
                        risque = "orages";
                        break;

                    case "4":
                        risque = "inondations";
                        break;

                    case "5":
                        risque = "neige-verglas";
                        break;

                    case "6":
                        risque = "canicule";
                        break;

                    case "7":
                        risque = "grand-froid";
                        break;

                    case "8":
                        risque = "avalanches";
                        break;

                    case "9":
                        risque = "vagues-submersion";
                        break;

                    default:
                        risque = "aucun";
                        break;
                    }
                    Type.Add(new VigilanceMeteoFrance.Models.Type()
                    {
                        Name = risque
                    });
                }
                return(vigilance);
            }
            else
            {
                var bookNodes = doc.Descendants("DV").Where(c => c.Attribute("dep").Value == departement);
                List <VigilanceMeteoFrance.Models.Type> Type = new List <VigilanceMeteoFrance.Models.Type>();
                return(vigilance);
            }
        }
Beispiel #8
0
        /// <summary>
        /// Gas stations refresh
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void Refresh(object source, ElapsedEventArgs e)
        {
            try
            {
                _list = GetData();
                PackageHost.WriteInfo("Gas stations list refreshed");

                //range search enabled
                if (PackageHost.TryGetSettingValue("latitude", out double latitude) &&
                    PackageHost.TryGetSettingValue("longitude", out double longitude) &&
                    PackageHost.TryGetSettingValue("range", out int range)
                    )
                {
                    List <Station> areaResults = FindInArea(latitude, longitude, range);
                    PackageHost.PushStateObject("InArea", areaResults);

                    PackageHost.WriteInfo($"{areaResults.Count} gas stations found in specified area");

                    //cheapest station for specified fuel type
                    if (PackageHost.TryGetSettingValue("cheapest-fuel-types", out string fuelTypes))
                    {
                        foreach (string fuelType in fuelTypes.Split(','))
                        {
                            if (Enum.TryParse(fuelType.Trim(), true, out Fuel fuel))
                            {
                                //get the station
                                Station cheapest = GetCheapestStationForFuelType(areaResults, fuel);
                                Dictionary <string, object> metadatas = null;

                                //get the price of the fuel
                                if (cheapest != null)
                                {
                                    Price prix = cheapest.Prices.FirstOrDefault(p => p.Id == fuel);
                                    if (prix != null)
                                    {
                                        metadatas = new Dictionary <string, object>()
                                        {
                                            ["price"] = prix.Value,
                                            ["name"]  = prix.Name
                                        };
                                    }
                                }

                                PackageHost.PushStateObject($"Cheapest-{fuelType}", cheapest, metadatas: metadatas);

                                PackageHost.WriteInfo($"Cheapest '{fuelType}' found in specified area");
                            }
                        }
                    }
                }

                //specific id search enabled
                if (PackageHost.TryGetSettingValue("station-ids", out string stationIds))
                {
                    foreach (Station pdv in _list.Stations.FindAll(pdv => stationIds.Contains(pdv.Id.ToString())))
                    {
                        PackageHost.PushStateObject(pdv.Id.ToString(), pdv);

                        PackageHost.WriteInfo($"Gas station '{pdv.Id}' found");
                    }
                }
            }
            catch (Exception ex)
            {
                PackageHost.WriteError($"An error ocurred while getting datas : '{ex.Message}'");
            }
        }