/// <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); } }
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); } }
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); } }
protected AgentSessionBase(MessageTransceiver transceiver, string serverSessionId, string sessionClientId) { this.Transceiver = transceiver; this.ServerSessionId = serverSessionId; this.SessionClientId = sessionClientId; SessionId = Guid.NewGuid().ToString("N"); TimeCreated = DateTime.UtcNow; CacheSpan = TimeSpan.FromHours(1); LifeSpan = TimeSpan.FromHours(8); TokenSource = new CancellationTokenSource(); taskList = new ConcurrentDictionary <string, Task>(StringComparer.Ordinal); _log = new Lazy <ILog>(() => LogManager.GetLogger(GetType())); Output = new SessionOutput(transceiver, ServerSessionId, SessionClientId); WorkDirectory = Path.Combine(Configuration.WorkDirectory, SessionId); ContentDirectory = Path.Combine(WorkDirectory, "content"); BinDirectory = Path.Combine(WorkDirectory, "bin"); Packages = new PackageHost { ServerSessionId = serverSessionId, Transceiver = transceiver, }; Applications = new ApplicationHost(); }
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 } }); } }
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()); } }
/// <summary> /// Récupère le faceID d'une photo /// </summary> /// <param name="imageFilePath"></param> /// <returns>faceID</returns> static async Task <string> FaceIDAsync(string imageFilePath) { PackageHost.WriteInfo("\n\n\nPath of the image : " + imageFilePath); Console.Write("\n\n\nPath of the image : " + imageFilePath); string faceId; string faceId_String = ""; // Si le fichier existe, on récupère le faceID if (File.Exists(imageFilePath)) { // Execute the REST API call. try { faceId = await MakeFaceAnalysisRequest(imageFilePath); faceId_String = Convert.ToString(faceId); } catch (Exception e) { Console.WriteLine("\n" + Convert.ToString(e.Message) + "\nPress Enter to exit...\n"); } } // Sinon, affichage d'un message d'erreur else { Console.WriteLine("\nInvalid file path.\nPress Enter to exit...\n"); } return(faceId_String); }
/// <summary> /// Ajout du state object /// </summary> /// <param name="nom">Nom du SO</param> /// <param name="val">Valeur du SO</param> private static void PushStateObject(string nom, string val) { if (!val.ToString().Contains(nug)) { PackageHost.PushStateObject(nom, Newtonsoft.Json.JsonConvert.DeserializeObject(val), lifetime: Refresh * 2); } }
/// <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"); } }
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")); } }); }
public override void OnStart() { PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected); string Maison; try { Maison = PackageHost.GetSettingValue <string>("Adresse de la maison"); } catch { Maison = "1 Vieux chemin des loups bailleul"; } Task.Factory.StartNew(() => { while (PackageHost.IsRunning) { GetAgendaNTraffic(Maison); try { Thread.Sleep(PackageHost.GetSettingValue <int>("Interval de rafraichissement")); } catch { Thread.Sleep(300000); } } }); }
public override void OnStart() { PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected); //// Remote controller this.RemoteController = new HttpPanasonicRemoteController(); }
public override void OnStart() { PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected); PackageHost.WriteInfo("Je suis le package nommé {0} version {1}", PackageHost.PackageName, PackageHost.PackageVersion); Task.Factory.StartNew(() => { while (PackageHost.IsRunning) { //Mettre les valeurs des capteurs dans la classe Rcapteur.Humidité.Value = this.hum.DynamicValue; Rcapteur.Luminosité.Value = this.lum.DynamicValue; Rcapteur.Niveau_eau.Value = rdn.Next(10, 30); Rcapteur.Température.Value = this.temp.DynamicValue; //STATE OBJECT CAPTEURS PackageHost.PushStateObject("Résultats Capteurs", Rcapteur, lifetime: PackageHost.GetSettingValue <int>("Interval") + 4000); //STATE OBJECT //Un state object expire si après 4 seconde de son intervale il n'est pas mis à jour. C'est un choix arbitraire Thread.Sleep(PackageHost.GetSettingValue <int>("Interval")); //Ajouter du code qui surveille temperature/Humidite des plantes dans la serre et envoyer un push si c'est le cas } }); }
/// <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}"); } } }
private void computer_HardwareAdded(IHardware hardware) { PackageHost.WriteInfo("Adding " + hardware.Name); if (hardware.HardwareType == HardwareType.HDD) { var hddName = "PHYSICALDRIVE" + hardware.Identifier.ToString().Replace("/hdd/", ""); var searcher = new ManagementObjectSearcher($"SELECT * FROM Win32_DiskDrive WHERE Name LIKE \"%{ hddName }\""); ManagementObject mo = searcher.Get().OfType <ManagementObject>().FirstOrDefault(); if (mo != null) { PackageHost.PushStateObject(hardware.Identifier.ToString(), new DiskDrive() { Name = this.GetWmiValue(mo, "Name"), Hardware = hardware.ToString(), SerialNumber = this.GetWmiValue(mo, "SerialNumber"), Model = this.GetWmiValue(mo, "Model"), Status = this.GetWmiValue(mo, "Status"), MediaType = this.GetWmiValue(mo, "MediaType"), Manufacturer = this.GetWmiValue(mo, "Manufacturer"), Caption = this.GetWmiValue(mo, "Caption") }); } } this.PushHardwaresList(); }
public override void OnStart() { PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected); Task.Factory.StartNew(async() => { while (PackageHost.IsRunning) { //réinitialise les valeurs des données toutes les minutes var myData = new Values(); myData.Pass = ""; myData.Login = ""; myData.Latitude = 0; myData.Longitude = 0; PackageHost.PushStateObject("Values", myData, lifetime: 50); PackageHost.WriteInfo("Initializing default settings, reset in" + delay + "seconds"); await Task.Delay(60000 * delay); //en minutes } } ); PackageHost.WriteInfo("values are : {0}", this.PushValues.DynamicValue); //initialisation des valeurs des stateObjects au démarrage latitude = this.PushValues.DynamicValue.Latitude; longitude = this.PushValues.DynamicValue.Longitude; login = this.PushValues.DynamicValue.Login; pass = this.PushValues.DynamicValue.Pass; //notification des changements de valeurs*/ this.PushValues.ValueChanged += OnValueChanged; }
/// <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); }
private void OnValueChanged(object sender, StateObjectChangedEventArgs e) { //récupération des nouvelles valeurs PackageHost.WriteInfo("values are : {0}", this.PushValues.DynamicValue); latitude = e.NewState.DynamicValue.Latitude; longitude = e.NewState.DynamicValue.Longitude; login = e.NewState.DynamicValue.Login; pass = e.NewState.DynamicValue.Pass; myGuid = Auth(pass, login, latitude, longitude); String myGuidString = myGuid.ToString(); PackageHost.WriteInfo("generated token : {0}", myGuid); PackageHost.WriteInfo("Sending generated token"); if (myGuid != Guid.Empty) //si token valide généré par Auth, envoi à la Raspberry { //communication avec la Raspberry MessageScope.Create("ConstellationPackagePython2").OnSagaResponse((response) => { //premier envoi du token, récupération de ce même token PackageHost.WriteInfo("Sending generated token"); PackageHost.WriteInfo("Raspberry response : {0}", response); String responseC = myGuidString + "fr42kilj8"; //deuxième envoi du token + clé de sécurite PackageHost.WriteInfo(" Sending token + key "); PackageHost.SendMessage(MessageScope.Create("ConstellationPackagePython2"), "reponse", responseC); }).GetProxy().question <String>(myGuidString); } }
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()); } }
private void ParametresServeur_ValueChanged(object sender, StateObjectChangedEventArgs e) { HaveToWait = false; StopWait.Cancel(); PackageHost.WriteInfo("Changement de param"); if (bool.Parse(e.NewState.DynamicValue.IsActive.ToString())) { PackageHost.WriteInfo("Le réveil est maintenant actif"); if (bool.Parse(e.NewState.DynamicValue.ManualMode.ToString()))//Si en mode manuel { PackageHost.WriteInfo("Configuration changée : Réveil en mode manuel "); ModeManuel(); } else //Si en mode automatique calendar { PackageHost.WriteInfo("Configuration changée : Réveil en mode auto "); ModeAuto(); } } else { PackageHost.WriteInfo("Le réveil n'est plus actif :("); } }
public MainWindow() { PackageHost.RegisterStateObjectLinks(this); PackageHost.RegisterMessageCallbacks(this); PackageHost.DeclarePackageDescriptor(); InitializeComponent(); }
private static void SetPollen() { if (Log) { PackageHost.WriteInfo("Mise à jours des données sur les risques du pollen"); } // Récupération contenu page WebRequest request = WebRequest.Create("https://pollens.fr/load_vigilance_map"); request.Method = "GET"; WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string content = reader.ReadToEnd(); reader.Close(); response.Close(); // Extraction data var data = JObject.Parse(JObject.Parse(content).SelectToken("vigilanceMapCounties").ToString()).SelectToken(DepNum.ToString()); // Récup risque global int.TryParse(((JValue)data.SelectToken("riskLevel")).Value.ToString(), out int riskLevel); // Detail List <Vegetal> vegetaux = new List <Vegetal>(); foreach (var item in (JArray)data.SelectToken("risks")) { vegetaux.Add(new Vegetal(item["pollenName"].ToString(), Risques.Single(r => r.id.Equals((int)item["level"])).couleur, (int)item["level"])); } //// Traitement HTML //HtmlDocument document = new HtmlDocument(); //document.LoadHtml(data.SelectToken("riskSummary").ToString()); //// Récup couleurs //HtmlNodeCollection couleurCollec = document.DocumentNode.SelectNodes("//g[rect]/rect"); //// Récup nom //HtmlNodeCollection nomCollec = document.DocumentNode.SelectNodes("//tspan[@text-anchor='end']/text()"); //// Construction données //string couleur; //List<Vegetal> vegetaux = new List<Vegetal>(couleurCollec.Count); //for (int i = 0; i < couleurCollec.Count; i++) //{ // // TODO : gerer la correspondance, via Y ? (couleurCollec[i].Attributes) // couleur = GetColor(couleurCollec[i].Attributes["style"].Value); // vegetaux.Add(new Vegetal(((HtmlTextNode)nomCollec[i]).Text.Trim(), couleur, Risques.Single(r => r.couleur.Equals(couleur)).id)); //} PackageHost.PushStateObject("Pollens", vegetaux, metadatas: new Dictionary <string, object> { ["Departement"] = DepNum }, lifetime: RefreshInterval * 2); PackageHost.PushStateObject("Risque", Risques.Single(r => r.id.Equals(riskLevel)), metadatas: new Dictionary <string, object> { ["Departement"] = DepNum }, lifetime: RefreshInterval * 2); }
/// <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 !"); }
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()); } }
/// <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); }
List <Trajets> GetTraffic(double start_longitude, double start_latitude, double finish_longitude, double finish_latitude) { string AddressURL = "https://www.waze.com/row-RoutingManager/routingRequest?from=x%3A" + start_longitude.ToString("0.0000000", System.Globalization.CultureInfo.InvariantCulture) + "+y%3A" + start_latitude.ToString("0.0000000", System.Globalization.CultureInfo.InvariantCulture) + "&to=x%3A" + finish_longitude.ToString("0.0000000", System.Globalization.CultureInfo.InvariantCulture) + "+y%3A" + finish_latitude.ToString("0.0000000", System.Globalization.CultureInfo.InvariantCulture) + "&at=0&returnJSON=true&timeout=60000&nPaths=3&options=AVOID_TRAILS%3At"; WebClient webClient = new WebClient(); webClient.Headers.Add("user-agent", "Only a test!"); var result = webClient.DownloadString(AddressURL); var root = JsonConvert.DeserializeObject <RootObject>(result); List <Trajets> trajet = new List <Trajets>(); foreach (var pair in root.alternatives) { int sumTime = 0; int sumRealTime = 0; foreach (var test in pair.response.results) { sumTime += test.crossTimeWithoutRealTime; sumRealTime += test.crossTime; } int totalTime = sumTime / 60; int totalRealTime = sumRealTime / 60; trajet.Add(new Trajets() { Path = pair.response.routeName, Time = totalTime, RealTime = totalRealTime, RouteType = pair.response.routeType[0] }); PackageHost.WriteInfo("{0} : {1}", pair.response.routeName, totalRealTime); } return(trajet); }
public void SendKey(SqueezeboxCommand command, string squeezebox = "", string value = "none") { if (string.IsNullOrEmpty(squeezebox)) { string players = "{\"id\":1,\"method\":\"slim.request\",\"params\":[\"\",[\"players\",\"0\",\"100\"]]}"; var players_result = this.Requete(players); JavaScriptSerializer js = new JavaScriptSerializer(); RootObject root = (RootObject)js.Deserialize(players_result, typeof(RootObject)); foreach (var player in root.result.players_loop) { string command_player = this.GenerateCommandFromUrlToSqueezebox(command, player.playerid, value); PackageHost.WriteInfo("Send {0} to {1}", command, player.name); string request_result = this.Requete(command_player); } } else { var players = squeezebox.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries); foreach (string player in players) { string command_player = this.GenerateCommandFromUrlToSqueezebox(command, player, value); PackageHost.WriteInfo("Send {0} to {1}", command, player); string request_result = this.Requete(command_player); } } }
private void PushHardware(IHardware hardware, int level = 0) { if (hardware.SubHardware.Length > 0) { foreach (var shw in hardware.SubHardware) { this.PushHardware(shw, level + 1); } } foreach (var sensorType in hardware.Sensors.Select(g => g.SensorType).Distinct()) { foreach (var item in hardware.Sensors) { if (item.SensorType == sensorType) { PackageHost.PushStateObject(item.Identifier.ToString(), new SensorValue() { Name = item.Name, Value = item.Value, Type = item.SensorType }, lifetime: DEFAULT_LIFETIME, metadatas: new System.Collections.Generic.Dictionary <string, object>() { ["Hardware"] = item.Hardware.Name }); } } } }
private void UpdateStateObjects(Relay relay, bool state) { if (relay == Relay.All) { int i = 0; foreach (var item in Enum.GetValues(typeof(Relay))) { if (++i > PackageHost.GetSettingValue <int>("RelayCount") || item == (object)Relay.All) { break; } else { var relayAttribute = typeof(Relay).GetMember(item.ToString())[0].GetCustomAttribute <RelayAttribute>(); PackageHost.PushStateObject(item.ToString(), state, metadatas: new System.Collections.Generic.Dictionary <string, object>() { ["Id"] = relayAttribute.Number, ["Flag"] = relayAttribute.Code.ToString() }); } } } else { var relayAttribute = typeof(Relay).GetMember(relay.ToString())[0].GetCustomAttribute <RelayAttribute>(); PackageHost.PushStateObject(relay.ToString(), state, metadatas: new System.Collections.Generic.Dictionary <string, object>() { ["Id"] = relayAttribute.Number, ["Flag"] = relayAttribute.Code.ToString() }); } }
/// <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); } }