public override void OnStart()
        {
            PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected);

            while (PackageHost.IsRunning)
            {
                int Heure  = DateTime.Now.Hour;
                int Minute = DateTime.Now.Minute;

                if (DateTime.Now.Date != dateProcessedFeeding.Date && Heure == 13 && Minute == 30)
                {
                    dateProcessedFeeding = DateTime.Now;
                    PackageHost.SendMessage(MessageScope.Create("FishtNess"), "Feeding", null);
                }

                if (DateTime.Now.Date != dateProcessedSwitchON.Date && Heure == 11 && Minute == 30)
                {
                    dateProcessedSwitchON = DateTime.Now;
                    PackageHost.SendMessage(MessageScope.Create("FishtNess"), "SwitchState", true);
                }

                if (DateTime.Now.Date != dateProcessedSwitchOFF.Date && Heure == 21 && Minute == 30)
                {
                    dateProcessedSwitchOFF = DateTime.Now;
                    PackageHost.SendMessage(MessageScope.Create("FishtNess"), "SwitchState", false);
                }


                if (DateTime.Now.Date != dateProcessedPushBullet1.Date && Heure == 8)
                {
                    dateProcessedPushBullet1 = DateTime.Now;
                    PackageHost.CreateMessageProxy("PushBullet").PushNote("ATTENTION", "La température de l'aquarium est : {0}°C.", this.Temperature.DynamicValue);
                }

                else if (DateTime.Now.Date != dateProcessedPushBullet2.Date && Heure == 15)
                {
                    dateProcessedPushBullet2 = DateTime.Now;
                    PackageHost.CreateMessageProxy("PushBullet").PushNote("ATTENTION", "La température de l'aquarium est : {0}°C.", this.Temperature.DynamicValue);
                }

                else if (DateTime.Now.Date != dateProcessedPushBullet3.Date && Heure == 8)
                {
                    dateProcessedPushBullet3 = DateTime.Now;
                    PackageHost.CreateMessageProxy("PushBullet").PushNote("ATTENTION", "L'acidite (pH) de l'aquarium est : {0}.", this.Acidity.DynamicValue);
                }

                else if (DateTime.Now.Date != dateProcessedPushBullet4.Date && Heure == 15)
                {
                    dateProcessedPushBullet4 = DateTime.Now;
                    PackageHost.CreateMessageProxy("PushBullet").PushNote("ATTENTION", "L'acidite (pH) de l'aquarium est : {0}.", this.Acidity.DynamicValue);
                }



                Thread.Sleep(PackageHost.GetSettingValue <int>("Interval"));
            }
        }
Пример #2
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            if (string.IsNullOrEmpty(PackageHost.GetSettingValue("token")))
            {
                throw new Exception("Access Token not defined!");
            }

            // Init the Realtime Event Stream
            this._webSocket = new WebSocket(WS_ROOT_URI + PackageHost.GetSettingValue("token"));
            this._webSocket.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
            this._webSocket.OnOpen    += (s, e) => PackageHost.WriteInfo("Connected to the realtime event stream");
            this._webSocket.OnClose   += (s, e) => PackageHost.WriteWarn("Disconnected to the realtime event stream");
            this._webSocket.OnError   += (s, e) => PackageHost.WriteWarn("Error on the realtime event stream : " + e.Message);
            this._webSocket.OnMessage += (s, e) =>
            {
                dynamic message = JsonConvert.DeserializeObject(e.Data);
                switch (((string)message.type))
                {
                case "nop":     //Sent every 30 seconds confirming the connection is active.
                    break;

                case "tickle":
                    switch ((string)message.subtype)
                    {
                    case "push":
                        string pushesGroup = PackageHost.GetSettingValue("SendPushesReceivedToGroup");
                        if (!string.IsNullOrEmpty(pushesGroup))
                        {
                            Push lastPush = this.GetPushes(DateTime.UtcNow.AddMinutes(-1))?.Pushes?.FirstOrDefault();
                            PackageHost.CreateMessageProxy(MessageScope.ScopeType.Group, pushesGroup).ReceivePush(lastPush);
                        }
                        break;

                    case "device":
                        this.GetDevices();
                        break;
                    }
                    break;

                case "push":
                    dynamic data            = message.push;
                    string  ephemeralsGroup = PackageHost.GetSettingValue("SendEphemeralsReceivedToGroup");
                    if (!string.IsNullOrEmpty(ephemeralsGroup))
                    {
                        PackageHost.CreateMessageProxy(MessageScope.ScopeType.Group, ephemeralsGroup).ReceiveEphemeral(data);
                    }
                    break;
                }
            };
            this._webSocket.ConnectAsync();
            this.GetCurrentUser();
            this.GetDevices();
            this.GetChats();
        }
Пример #3
0
 /// <summary>
 /// Handles the ValueChanged event of the OutdoorSensor control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="StateObjectChangedEventArgs"/> instance containing the event data.</param>
 /// <exception cref="NotImplementedException"></exception>
 private void OutdoorSensor_ValueChanged(object sender, StateObjectChangedEventArgs e)
 {
     //If the outdoor sensor detect the necklace and the pet was inside
     if ((bool)e.NewState.DynamicValue.Etat && (bool)this.AnimalPresence.DynamicValue.Etat)
     {
         //If the flap is closed
         if (!(bool)this.Flap.DynamicValue.Etat)
         {
             //Nothing to do
         }
         else
         {
             //Close the flap
             PackageHost.CreateMessageProxy("Chatiere").CloseFlap();
             PackageHost.CreateMessageProxy("Chatiere").StateObjectAnimalPresence_ChangeValue(this.AnimalPresence.Value.Name, false);
         }
     }
     //If the outdoor sensor detect the necklace and the pet was outside
     else if ((bool)e.NewState.DynamicValue.Etat && !(bool)this.AnimalPresence.DynamicValue.Etat)
     {
         if (!(bool)this.Flap.DynamicValue.Etat)
         {
             if ((bool)this.LockFlap.DynamicValue.Etat)
             {
                 //Do not open the flap
             }
             else
             {
                 if (!(bool)this.Flap.DynamicValue.Etat)
                 {
                     PackageHost.CreateMessageProxy("Chatiere").OpenFlap();
                     if (DayPeriod())
                     {
                         PackageHost.CreateMessageProxy("Chatiere").SwitchOnLed();
                     }
                     else
                     {
                         //Nothing to do
                     }
                 }
                 else
                 {
                     //Nothing to do
                 }
             }
         }
         else
         {
             //Nothing to do
         }
     }
 }
Пример #4
0
        /// <summary>
        /// Handles the ValueChanged event of the Flap control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="StateObjectChangedEventArgs"/> instance containing the event data.</param>
        /// <exception cref="NotImplementedException"></exception>
        private async void Flap_ValueChanged(object sender, StateObjectChangedEventArgs e)
        {
            //If the flap is opened
            if ((bool)e.NewState.DynamicValue.Etat)
            {
                await Task.Delay(10000);

                if ((bool)this.Flap.DynamicValue.Etat)
                {
                    PackageHost.CreateMessageProxy("Chatiere").CloseFlap();
                }
            }
            //Else, nothing to do
        }
Пример #5
0
        public async Task Maj_SerreAsync()
        {
            int i, a;

            String[][] response = await PackageHost.CreateMessageProxy("MySQL").Select_DB <System.String[][]>("plante,serre WHERE plante.Id = serre.Id" as System.String,
                                                                                                              "nom,url,seuil_lum,temp,besoin_eau,humidite,maturation,position_x,position_y,effectif" as System.String);

            a = await PackageHost.CreateMessageProxy("MySQL").Count_DB <System.Int32>("plante" as System.String);

            Serre so = new Serre(response[0].Length, a);

            init_tab(so.tab_url, PackageHost.GetSettingValue <String>("default_picture"));
            for (i = 0; i < response[0].Length; i++) //Contient les infos sur toutes les plantes planté dans la serre
            {
                so.Plante[i]            = new Plante();
                so.Plante[i].nom        = response[0][i];
                so.Plante[i].url        = response[1][i];
                so.Plante[i].seuil_lum  = response[2][i];
                so.Plante[i].temp       = response[3][i];
                so.Plante[i].besoin_eau = response[4][i];
                so.Plante[i].humidite   = response[5][i];
                so.Plante[i].maturation = response[6][i];
                so.Plante[i].position_x = response[7][i];
                so.Plante[i].position_y = response[8][i];
                so.Plante[i].effectif   = response[9][i];

                so.tab_url[(int.Parse(so.Plante[i].position_x) - 1) + (int.Parse(so.Plante[i].position_y) - 1) * PackageHost.GetSettingValue <Int32>("max_y")] = so.Plante[i].url;
            }
            so.LastId = a + 1; //Nouvel Id utilisable pendantl'ajout d'une plante

            response = await PackageHost.CreateMessageProxy("MySQL").Select_DB <System.String[][]>("plante" as System.String,
                                                                                                   "Id,nom,url,seuil_lum,temp,besoin_eau,humidite,maturation" as System.String);

            for (i = 0; i < response[0].Length; i++) //Contient toute les infos de la table plante
            {
                so.data[i]            = new Database();
                so.data[i].Id         = response[0][i];
                so.data[i].nom        = response[1][i];
                so.data[i].url        = response[2][i];
                so.data[i].seuil_lum  = response[3][i];
                so.data[i].temp       = response[4][i];
                so.data[i].besoin_eau = response[5][i];
                so.data[i].humidite   = response[6][i];
                so.data[i].maturation = response[7][i];
            }

            PackageHost.PushStateObject("Serre", so);
        }
Пример #6
0
 private void ZoneMinder_OnEventChanged(object sender, ZoneMinderBase.ZoneMinderEvent e)
 {
     if (!e.Event.Terminated)
     {
         PackageHost.WriteWarn($"New event #{e.Event.EventId} ({e.Event.Cause}) on monitor #{e.Event.MonitorId} detected ({e.Event.Notes})");
     }
     else
     {
         PackageHost.WriteInfo($"Event #{e.Event.EventId} ({e.Event.Cause}) on monitor #{e.Event.MonitorId} is terminated (Lenght:{e.Event.Length}sec - {e.Event.Notes})");
     }
     // Forward ZM event to Constellation group
     if (PackageHost.GetSettingValue <bool>("ForwardEvents"))
     {
         PackageHost.CreateMessageProxy(Constellation.MessageScope.ScopeType.Group, PackageHost.GetSettingValue("EventsGroupName")).OnZoneMinderEvent(e.Event);
     }
 }
Пример #7
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            //events:
            this.IndoorSensor.ValueChanged  += IndoorSensor_ValueChanged;
            this.OutdoorSensor.ValueChanged += OutdoorSensor_ValueChanged;
            this.Flap.ValueChanged          += Flap_ValueChanged;

            //Push state object with an interval (default value : 1 seconde)
            Task.Run(async() =>
            {
                while (PackageHost.IsRunning)
                {
                    PackageHost.CreateMessageProxy("Chatiere").StateObjectState_ChangeValue(this.IndoorSensor.Value.Name, this.IndoorSensor.DynamicValue.Etat);
                    PackageHost.CreateMessageProxy("Chatiere").StateObjectState_ChangeValue(this.OutdoorSensor.Value.Name, this.OutdoorSensor.DynamicValue.Etat);
                    PackageHost.CreateMessageProxy("Chatiere").StateObjectState_ChangeValue(this.Flap.Value.Name, this.Flap.DynamicValue.Etat);
                    PackageHost.CreateMessageProxy("Chatiere").StateObjectState_ChangeValue(this.Light.Value.Name, this.Light.DynamicValue.Etat);
                    PackageHost.CreateMessageProxy("Chatiere").StateObjectState_ChangeValue(this.LockFlap.Value.Name, this.LockFlap.DynamicValue.Etat);
                    PackageHost.CreateMessageProxy("Chatiere").StateObjectAnimalPresence_ChangeValue(this.AnimalPresence.Value.Name, this.AnimalPresence.DynamicValue.Etat);
                    await Task.Delay(PackageHost.GetSettingValue <int>("interval"));
                }
            });

            Task.Run(async() =>
            {
                while (PackageHost.IsRunning)
                {
                    while (true)
                    {
                        if (DateTime.Now.Hour >= PackageHost.GetSettingValue <int>("LockIntervalHigh"))
                        {
                            //change the state object to on
                            PackageHost.CreateMessageProxy("Chatiere").StateObjectState_ChangeValue(this.LockFlap.Value.Name, true);
                            break;
                        }
                        await Task.Delay(15000);
                    }
                    while (DateTime.Now.Hour < PackageHost.GetSettingValue <int>("LockIntervalLow") ||
                           DateTime.Now.Hour >= PackageHost.GetSettingValue <int>("LockIntervalHigh"))
                    {
                        await Task.Delay(15000);
                    }
                    //change the state object to off
                    PackageHost.CreateMessageProxy("Chatiere").StateObjectState_ChangeValue(this.LockFlap.Value.Name, false);
                }
            });
        }
Пример #8
0
        public override void OnStart()
        {
            PackageHost.WriteInfo("Package starting - IsRunning: {0} - IsConnected: {1}", PackageHost.IsRunning, PackageHost.IsConnected);
            PackageHost.WriteInfo("je demarre le brain");

            // A chaque MàJ du S.O. etatSonnette on regarde sa valeur
            PackageHost.StateObjectUpdated += (s, e) =>
            {
                if (e.StateObject.Name == "etatSonnette")
                {
                    if (e.StateObject.DynamicValue["etat"] == 1)
                    {
                        PackageHost.WriteInfo("Screenshot !!!");
                        PackageHost.WriteInfo("Name : " + e.StateObject.Name);
                        PackageHost.CreateMessageProxy("Constellation_Screenshot").Screenshot();
                        AnalysePhotosAsync();
                    }
                }
            };
        }
Пример #9
0
        /// <summary>
        /// Gère le processus de la reconnaissance d'image
        /// </summary>
        static async void AnalysePhotosAsync()
        {
            bool keep_going = false;

            PackageHost.WriteInfo("--------------------- Face - Detect ---------------------\n");
            Console.WriteLine("--------------------- Face - Detect ---------------------\n");

            // Obtention des faceID des photos "témoins"
            string[] fichiersTemoins    = Directory.GetFiles(@"D:\images\Photos_Temoins");
            string[] listeFaceIDTemoins = await FaceIDPhotosTemoins(fichiersTemoins);

            // Obtention du faceID de la photo qui vient d'être prise
            string imageFilePath = @"D:\images\image.jpg";
            string faceId2       = await FaceIDAsync(imageFilePath);

            // Si y'a un bien un faceID on peut continuer l'analyse
            if (faceId2 != "")
            {
                Console.WriteLine("\nfaceId2 : " + faceId2 + "\n");
                keep_going = true;
            }
            // Sinon on affiche un message
            else
            {
                Console.WriteLine("\nfaceId2 invalide\n");
            }

            if (keep_going)
            {
                bool samePerson = false;
                PackageHost.WriteInfo("--------------------- Face - Verify ---------------------\n");
                Console.WriteLine("--------------------- Face - Verify ---------------------\n");
                int i = 0;
                // Envoi à Cognitives Services des faceID de chaque photo témoin avec le faceID de la photo prise
                while (i < listeFaceIDTemoins.Length && !samePerson)
                {
                    Result_face_verify verif = await MakeRequestFaceVerify(listeFaceIDTemoins[i], faceId2);

                    PackageHost.WriteInfo("\nVerification :\nisIdentical : " + verif.IsIdentical + ", condifence : " + Convert.ToString(verif.Confidence) + "\n\n\n");
                    Console.Write("\nVerification :\nisIdentical : " + verif.IsIdentical + ", condifence : " + Convert.ToString(verif.Confidence) + "\n\n\n");

                    // Si la personne qui a été prise en photo est dans les photos témoins, on ouvre la porte
                    if (verif.IsIdentical == true)
                    {
                        samePerson = true;
                        PackageHost.CreateMessageProxy("SerrurePackage").OpenDoor();
                    }
                    i++;
                }
                // S'il n'y a pas eu de correspondance, envoi de la photo avec PushBullet
                if (!samePerson)
                {
                    Console.Write("\nPersonne autorisee non reconnue\n");
                    PackageHost.CreateMessageProxy("PushBullet").PushFile(@"D:\Images\image.jpg", "Ca sonne !", "Device");
                }
            }
            else
            {
                Console.Write("\nFace - Verify impossible, faceId non valide\n");
                PackageHost.WriteInfo("\nMessage envoyé sur PushBullet");
                PackageHost.CreateMessageProxy("PushBullet").PushFile(@"D:\Images\image.jpg", "Ca sonne !", "Device");
            }
        }
Пример #10
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            // Check PortName settings
            if (!PackageHost.ContainsSetting("PortName"))
            {
                PackageHost.WriteError("The setting 'PortName' is requiered to start the package !");
                return;
            }

            // Get the custom names
            this.stateObjectCustomNames  = PackageHost.GetSettingAsJsonObject <Dictionary <string, string> >("StateObjectCustomNames");
            PackageHost.SettingsUpdated += (s, e) =>
            {
                // Refresh the dictionary on settings's update!
                this.stateObjectCustomNames = PackageHost.GetSettingAsJsonObject <Dictionary <string, string> >("StateObjectCustomNames");
            };

            // Init the RFX manager
            this.rfx = new RfxManager(PackageHost.GetSettingValue("PortName"));

            // Message handler for verbose mode
            this.rfx.OnMessage += (s, e) =>
            {
                if (PackageHost.GetSettingValue <bool>("Verbose"))
                {
                    PackageHost.WriteInfo(e.Message);
                }
            };

            // Forward message to group ?
            this.rfx.OnPacketReceived += (s, e) =>
            {
                if (PackageHost.ContainsSetting("ForwardRawMessageToGroup") && !string.IsNullOrEmpty(PackageHost.GetSettingValue("ForwardRawMessageToGroup")))
                {
                    PackageHost.CreateMessageProxy(MessageScope.ScopeType.Group, PackageHost.GetSettingValue("ForwardRawMessageToGroup")).MessageReceived(e.Packet);
                }
            };

            // Attach handler on receive packet
            this.rfx.Subscribe <InterfaceMessage>(p =>
            {
                PackageHost.WriteInfo($"RFXCOM device ({p.TransceiverName}) connected on port '{this.rfx.RfxInterface.SerialPort.PortName}' with {p.Protocols.Count(i => i.Enabled)} protocol(s) enabled ({string.Join(", ", p.Protocols.Where(i => i.Enabled).Select(i => i.Name))})");
                PackageHost.PushStateObject("RFXCOM", new { p.TransceiverName, p.TypeName, p.Protocols, p.FirmwareVersion }, "RfxCom.Device");
            });
            this.rfx.Subscribe <TemperatureSensor>(p =>
            {
                // Push StateObject
                PackageHost.PushStateObject(this.GetStateObjectName("TemperatureSensor_" + p.SensorID), new
                {
                    p.SensorID,
                    p.Channel,
                    p.SequenceNumber,
                    p.BatteryLevel,
                    p.SignalLevel,
                    p.Temperature,
                    p.SubTypeName
                }, "RfxCom.TemperatureSensor", new Dictionary <string, object>()
                {
                    ["Type"] = p.TypeName, ["RawData"] = BitConverter.ToString(p.RawData)
                }, PackageHost.GetSettingValue <int>("SensorStateObjectLifetime"));
            });
            this.rfx.Subscribe <TemperatureHumiditySensor>(p =>
            {
                // Push StateObject
                PackageHost.PushStateObject(this.GetStateObjectName("TemperatureHumiditySensor_" + p.SensorID), new
                {
                    p.SensorID,
                    p.Channel,
                    p.SequenceNumber,
                    p.BatteryLevel,
                    p.SignalLevel,
                    p.Temperature,
                    p.Humidity,
                    p.Status,
                    p.SubTypeName,
                }, "RfxCom.TemperatureHumiditySensor", new Dictionary <string, object>()
                {
                    ["Type"] = p.TypeName, ["RawData"] = BitConverter.ToString(p.RawData)
                }, PackageHost.GetSettingValue <int>("SensorStateObjectLifetime"));
            });

            // Starting !
            var protocolsEnabled = PackageHost.ContainsSetting("ProtocolsEnabled") ? PackageHost.GetSettingValue("ProtocolsEnabled").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToArray() : null;

            this.rfx.Connect(protocolsEnabled);
            PackageHost.WriteInfo("The RFXcom package is started!");
        }
Пример #11
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            var config = PackageHost.GetSettingAsConfigurationSection <SnmpConfiguration>("snmpConfiguration");

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

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

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

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

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

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

            using (
                var stream =
                    new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine("calendar-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin      = DateTime.Now;
            request.ShowDeleted  = false;
            request.SingleEvents = true;
            try
            {
                request.MaxResults = int.Parse(PackageHost.GetSettingValue("Nombre d'evenements"));
            }
            catch
            {
                request.MaxResults = 5;
            }
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
            Events events = request.Execute();

            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    string when = eventItem.Start.DateTime.ToString();
                    if (String.IsNullOrEmpty(when))
                    {
                        when = eventItem.Start.Date;
                    }
                    EventnTraffic a = new EventnTraffic();
                    a.DateDebut = eventItem.Start.DateTime.ToString();
                    a.DateFin   = eventItem.End.DateTime.ToString();
                    a.Nom       = eventItem.Summary;
                    a.Lieu      = eventItem.Location;
                    //PackageHost.WriteInfo("{0} à {1}, {2}", a.Nom, a.DateDebut, a.Lieu);
                    if (!string.IsNullOrEmpty(a.Lieu))
                    {
                        TimeSpan       duree_trajet = new TimeSpan();
                        Task <dynamic> reponse      = PackageHost.CreateMessageProxy("GoogleTraffic").GetRoutes <dynamic>(Maison, a.Lieu);
                        if (reponse.Wait(30000) && reponse.IsCompleted)
                        {
                            try
                            {
                                duree_trajet = TimeSpan.Parse(reponse.Result[0].TimeWithTraffic.ToString());
                                //PackageHost.WriteInfo("Durée de trajet : {0}", duree_trajet.ToString());
                                a.TimeTrafficFromHouse = duree_trajet.ToString();
                            }

                            catch
                            {
                                PackageHost.WriteError("Impossible de trouver de temps de trajet pour {0}", a.Lieu);
                                a.TimeTrafficFromHouse = new TimeSpan().ToString();
                            }
                        }
                        else
                        {
                            PackageHost.WriteError("Aucune réponse !");
                        }
                    }
                    DonnesAgenda.Add(a);
                    //Console.WriteLine("{0} à {1}", a.Nom, a.DateDebut);
                }
            }
            else
            {
                Console.WriteLine("No upcoming events found.");
                PackageHost.WriteWarn("Aucun Evenement Trouvé !");
            }
            PackageHost.PushStateObject("EventWithTraffic", DonnesAgenda);

            return(DonnesAgenda);
        }