/// <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); } }
} //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); } }
/// <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); } }
public void SendKey(ServerCommand command) { string testcommand = this.GenerateCommandFromUrlToServer(command); PackageHost.WriteInfo("Send {0} to Logitech Media Server", command); string raiponce = this.Requete(testcommand); }
void AnswerQuestion(string reponse) { Process nircmd = new Process(); string path = Path.Combine(Path.GetTempPath(), "nircmd.exe"); File.WriteAllBytes(path, RemoteControl.Properties.Resources.nircmd); nircmd.StartInfo.FileName = path; switch (reponse) { case "oui": nircmd.StartInfo.Arguments = string.Format("dlg \"\" \"\" click yes"); PackageHost.WriteInfo("On clique sur oui"); break; case "non": nircmd.StartInfo.Arguments = string.Format("dlg \"\" \"\" click no"); break; default: return; } nircmd.Start(); }
public TimeAndPlace GetWakeUpHour() { var TimeReveil = new TimeAndPlace(); List <EventnTraffic> ListEvent = Events.DynamicValue.ToObject <List <EventnTraffic> >(); foreach (var evenement in ListEvent) { if (DateTime.Now < DateTime.Parse(evenement.DateDebut)) { PackageHost.WriteInfo("Le prochain évènement est le {0}", evenement.DateDebut.ToString()); TimeReveil.Time = DateTime.Parse(evenement.DateDebut); try { TimeReveil.TimeTraffic = TimeSpan.Parse(evenement.TimeTrafficFromHouse.ToString()); TimeReveil.Place = evenement.Lieu; } catch { var title = "Absence lieu pour le lendemain"; var body = "Aucun lieu n'a été enregistré pour demain, le temps de trajet ne sera pas pris en compte"; PackageHost.SendMessage(MessageScope.Create("PushBullet"), "PushNote", new object[] { title as System.String, body as System.String }); TimeReveil.TimeTraffic = new TimeSpan(); } return(TimeReveil); } } return(TimeReveil); }
/// <summary> /// Log of rflink /// </summary> void ReceivedStdOut(object sender, EventArgs e) { if (PackageHost.GetSettingValue <bool>("Log")) { PackageHost.WriteInfo("RfLink : {0}", (e as RFEventArgs).Data); } }
private void Update() { // Forward incoming SMS ? if (PackageHost.ContainsSetting("ForwardIncomingSMSTo") && !string.IsNullOrEmpty(PackageHost.GetSettingValue("ForwardIncomingSMSTo")) && this.router.Notification.UnreadMessage > 0) { foreach (Message sms in this.router.SMS.List.Messages) { if (sms.Status == Message.Smstat.Unread) { PackageHost.WriteInfo($"Forwarding incoming SMS from {sms.Phone}"); MessageScope.Create(MessageScope.ScopeType.Group, PackageHost.GetSettingValue("ForwardIncomingSMSTo")) .GetProxy() .IncomingSMS(new { Number = sms.Phone, Text = sms.Content, sms.Date, sms.Priority }); if (PackageHost.GetSettingValue <bool>("KeepSMSCopy")) { this.router.SetSMSRead(sms.Index); } else { this.router.DeleteSMS(sms.Index); } } } } // Update StateObjects this.PushStateObject <DeviceSignal>(() => this.router.DeviceSignal); this.PushStateObject <MonitoringStatus>(() => this.router.MonitoringStatus); this.PushStateObject <MonthlyStatistics>(() => this.router.MonthlyStatistics); this.PushStateObject <PinStatus>(() => this.router.PinStatus); this.PushStateObject <PLMNInformations>(() => this.router.PLMNInformations); this.PushStateObject <TrafficStatistics>(() => this.router.TrafficStatistics); this.PushStateObject <WlanBasicSettings>(() => this.router.WlanBasicSettings); this.PushStateObject <Notification>(() => this.router.Notification); this.PushStateObject <SMSList>(() => this.router.SMS); }
void Face_ValueChanged(object sender, StateObjectChangedEventArgs e) { if (((string)e.NewState.DynamicValue) == "Unknown") { PackageHost.WriteWarn("Warning unknown face detected"); PackageHost.CreateScope("PushBullet").Proxy.SendPush( new { Title = "Warning", Message = "BBC report an unknown face " } ); } else { PackageHost.WriteInfo("{0} detected", ((string)e.NewState.DynamicValue)); PackageHost.CreateScope("PushBullet").Proxy.SendPush( new { Title = "BBC report", Message = ((string)e.NewState.DynamicValue) + " detected" } ); } }
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); } }
/// <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}"); } } }
public void SendKey(SqueezeboxCommand command, string squeezebox = "", string value = "none", string value2 = "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, value2); 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, value2); PackageHost.WriteInfo("Send {0} to {1}", command, player); string request_result = this.Requete(command_player); } } }
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); }
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); }
public 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); } }
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 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 :("); } }
/// <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("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; }
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); } } }); }
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); //// Remote controller this.RemoteController = new HttpPanasonicRemoteController(); }
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); 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 } }); }
private void LoadDevices(List <ModbusDeviceDefinition> modbusDevicesDefintions) { if (PackageHost.ContainsSetting("Devices")) { // Read the JSON setting var devices = PackageHost.GetSettingAsJsonObject <List <ModbusDevice> >("Devices"); // For each device foreach (ModbusDevice device in devices) { // Get the definition from the ModbusDeviceDefinitions's setting var definition = modbusDevicesDefintions.FirstOrDefault(d => d.Name == device.DeviceType); // If the definition exists if (definition != null) { // Registering the device PackageHost.WriteInfo($"Registering {device} ({definition.Name} with {definition.Properties.Count} properties). Interval: {device.RequestInterval} second(s)"); this.deviceStates.Add(new DeviceState { Device = device, Definition = definition }); } else { // Otherwise ignore this device ! PackageHost.WriteWarn($"The device {device} will be ignore : unknown device type ({device.DeviceType})"); } } } }
/// <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!"); }
public bool AreaDisarm(ArmingRequestData request) { return(this.DoSafeAction(() => { PackageHost.WriteInfo("Disarming area {0}", request.Area); return this.paradox.AreaDisarm((Area)request.Area, request.PinCode).Result; })); }
/// <summary> /// Configures this player with arguments. /// </summary> /// <param name="args">The arguments.</param> /// <param name="useNewWaveOut">if set to <c>true</c> to use a new wave out.</param> /// <param name="volume">The default volume.</param> /// <returns></returns> public PlayerBase <TArgs> ConfigureWith(TArgs args, bool useNewWaveOut = false, float?volume = null) { this.Arguments = args; this.UseNewWaveOut = useNewWaveOut; this.Configure(); PackageHost.WriteInfo("{0}: ConfigureWith {1}", this.ToString(), args.ToString()); return(this); }
public override void OnPreShutdown() { if (vera != null) { PackageHost.WriteInfo("Disconnecting from the Vera"); vera.Dispose(); } }
/// <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); }; }