コード例 #1
0
        public override void AfterRegister(Lwm2mClient Client)
        {
            base.AfterRegister(Client);

            this.TriggerAll(new TimeSpan(0, 1, 0));
            this.state.TriggerAll(new TimeSpan(0, 1, 0));
        }
コード例 #2
0
        public override void AfterRegister(Lwm2mClient Client)
        {
            base.AfterRegister(Client);

            this.TriggerAll(new TimeSpan(0, 1, 0));
            this.current.TriggerAll(new TimeSpan(0, 1, 0));
            this.min.TriggerAll(new TimeSpan(0, 1, 0));
            this.max.TriggerAll(new TimeSpan(0, 1, 0));
        }
コード例 #3
0
        public async Task TestInitialize()
        {
            this.coapClient = new CoapEndpoint(new int[] { 5783 }, new int[] { 5784 }, null, null,
                                               false, false, new TextWriterSniffer(Console.Out, BinaryPresentationMethod.Hexadecimal));

            this.lwm2mClient = new Lwm2mClient("Lwm2mTestClient", this.coapClient,
                                               new Lwm2mSecurityObject(),
                                               new Lwm2mServerObject(),
                                               new Lwm2mAccessControlObject(),
                                               new Lwm2mDeviceObject("Waher Data AB", "Unit Test", Environment.MachineName,
                                                                     Environment.OSVersion.VersionString, "PC", Environment.OSVersion.Platform.ToString(),
                                                                     Environment.Version.ToString()));

            await this.lwm2mClient.LoadBootstrapInfo();
        }
コード例 #4
0
        public void TestCleanup()
        {
            if (this.lwm2mClient != null)
            {
                this.lwm2mClient.Dispose();
                this.lwm2mClient = null;
            }

            if (this.coapClient != null)
            {
                CoapResource[] Resources = this.coapClient.GetRegisteredResources();

                this.coapClient.Dispose();
                this.coapClient = null;

                Assert.AreEqual(1, Resources.Length, "There are resources still registered on the CoAP client.");
            }
        }
コード例 #5
0
ファイル: App.xaml.cs プロジェクト: markchipman/MIoT
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ICoapContentFormat).GetTypeInfo().Assembly,
                    typeof(IDtlsCredentials).GetTypeInfo().Assembly,
                    typeof(Lwm2mClient).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low);

                            this.digitalOutput0?.Set(this.output.Value);
                            this.actuation0?.Set(this.output.Value);
                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                foreach (DeviceInformation DeviceInfo in Devices)
                {
                    if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith("Arduino"))
                    {
                        Log.Informational("Connecting to " + DeviceInfo.Name);

                        this.arduinoUsb = new UsbSerial(DeviceInfo);
                        this.arduinoUsb.ConnectionEstablished += () =>
                                                                 Log.Informational("USB connection established.");

                        this.arduino              = new RemoteDevice(this.arduinoUsb);
                        this.arduino.DeviceReady += async() =>
                        {
                            try
                            {
                                Log.Informational("Device ready.");

                                this.arduino.pinMode(13, PinMode.OUTPUT);                                    // Onboard LED.
                                this.arduino.digitalWrite(13, PinState.HIGH);

                                this.arduino.pinMode(8, PinMode.INPUT);                                      // PIR sensor (motion detection).

                                this.arduino.pinMode(9, PinMode.OUTPUT);                                     // Relay.

                                this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                                this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                                this.digitalOutput0?.Set(this.output.Value);
                                this.actuation0?.Set(this.output.Value);
                                await MainPage.Instance.OutputSet(this.output.Value);

                                Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                                  new KeyValuePair <string, object>("Output", this.output.Value));

                                this.arduino.pinMode("A0", PinMode.ANALOG);                                 // Light sensor.
                            }
                            catch (Exception ex)
                            {
                                Log.Critical(ex);
                            }
                        };

                        this.arduinoUsb.ConnectionFailed += message =>
                        {
                            Log.Error("USB connection failed: " + message);
                        };

                        this.arduinoUsb.ConnectionLost += message =>
                        {
                            Log.Error("USB connection lost: " + message);
                        };

                        this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                        break;
                    }
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                /************************************************************************************
                * To create an unencrypted CoAP Endpoint on the default CoAP port:
                *
                *    this.coapEndpoint = new CoapEndpoint();
                *
                * To create an unencrypted CoAP Endpoint on the default CoAP port,
                * with a sniffer that outputs communication to the window:
                *
                *    this.coapEndpoint = new CoapEndpoint(new LogSniffer());
                *
                * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using
                * the users defined in the IUserSource users:
                *
                *    this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users);
                *
                * To create a CoAP endpoint, that listens to both the default CoAP port, for
                * unencrypted communication, and the default CoAPS port, for encrypted,
                * authenticated and authorized communication, using
                * the users defined in the IUserSource users. Only users having the given
                * privilege (if not empty) will be authorized to access resources on the endpoint:
                *
                *    this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                *       new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false);
                *
                ************************************************************************************/

                this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                                                     new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false);

                this.outputResource = this.coapEndpoint.Register("/Output", (req, resp) =>
                {
                    string s;

                    if (this.output.HasValue)
                    {
                        s = this.output.Value ? "true" : "false";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, async(req, resp) =>
                {
                    try
                    {
                        string s = req.Decode() as string;
                        if (s == null && req.Payload != null)
                        {
                            s = Encoding.UTF8.GetString(req.Payload);
                        }

                        if (s == null || !CommonTypes.TryParse(s, out bool Output))
                        {
                            resp.RST(CoapCode.BadRequest);
                        }
                        else
                        {
                            resp.Respond(CoapCode.Changed);
                            await this.SetOutput(Output, req.From.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                }, Notifications.Acknowledged, "Digital Output.", null, null,
                                                                 new int[] { PlainText.ContentFormatCode });

                this.outputResource?.TriggerAll(new TimeSpan(0, 1, 0));

                this.lwm2mClient = new Lwm2mClient("MIoT:Actuator:" + this.deviceId, this.coapEndpoint,
                                                   new Lwm2mSecurityObject(),
                                                   new Lwm2mServerObject(),
                                                   new Lwm2mAccessControlObject(),
                                                   new Lwm2mDeviceObject("Waher Data AB", "ActuatorLwm2m", this.deviceId, "1.0", "Actuator", "1.0", "1.0"),
                                                   new DigitalOutput(this.digitalOutput0 = new DigitalOutputInstance(0, this.output.HasValue && this.output.Value, "Relay")),
                                                   new Actuation(this.actuation0         = new ActuationInstance(0, this.output.HasValue && this.output.Value, "Relay")));

                this.digitalOutput0.OnRemoteUpdate += async(Sender, e) =>
                {
                    try
                    {
                        await this.SetOutput(((DigitalOutputInstance)Sender).Value, e.Request.From.ToString());
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                this.actuation0.OnRemoteUpdate += async(Sender, e) =>
                {
                    try
                    {
                        await this.SetOutput(((ActuationInstance)Sender).Value, e.Request.From.ToString());
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                await this.lwm2mClient.LoadBootstrapInfo();

                this.lwm2mClient.OnStateChanged += (sender, e) =>
                {
                    Log.Informational("LWM2M state changed to " + this.lwm2mClient.State.ToString() + ".");
                };

                this.lwm2mClient.OnBootstrapCompleted += (sender, e) =>
                {
                    Log.Informational("Bootstrap procedure completed.");
                };

                this.lwm2mClient.OnBootstrapFailed += (sender, e) =>
                {
                    Log.Error("Bootstrap procedure failed.");

                    this.coapEndpoint.ScheduleEvent(async(P) =>
                    {
                        try
                        {
                            await this.RequestBootstrap();
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    }, DateTime.Now.AddMinutes(15), null);
                };

                this.lwm2mClient.OnRegistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server registration completed.");
                };

                this.lwm2mClient.OnRegistrationFailed += (sender, e) =>
                {
                    Log.Error("Server registration failed.");
                };

                this.lwm2mClient.OnDeregistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server deregistration completed.");
                };

                this.lwm2mClient.OnDeregistrationFailed += (sender, e) =>
                {
                    Log.Error("Server deregistration failed.");
                };

                this.lwm2mClient.OnRebootRequest += async(sender, e) =>
                {
                    Log.Warning("Reboot is requested.");

                    try
                    {
                        await this.RequestBootstrap();
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                await this.RequestBootstrap();
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
コード例 #6
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ICoapContentFormat).GetTypeInfo().Assembly,
                    typeof(IDtlsCredentials).GetTypeInfo().Assembly,
                    typeof(Lwm2mClient).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += () =>
                    {
                        Log.Informational("Device ready.");

                        this.arduino.pinMode(13, PinMode.OUTPUT);                            // Onboard LED.
                        this.arduino.digitalWrite(13, PinState.HIGH);

                        this.arduino.pinMode(8, PinMode.INPUT);                              // PIR sensor (motion detection).
                        PinState Pin8 = this.arduino.digitalRead(8);
                        this.lastMotion = Pin8 == PinState.HIGH;
                        MainPage.Instance.DigitalPinUpdated(8, Pin8);

                        this.arduino.pinMode(9, PinMode.OUTPUT);                             // Relay.
                        this.arduino.digitalWrite(9, 0);                                     // Relay set to 0

                        this.arduino.pinMode("A0", PinMode.ANALOG);                          // Light sensor.
                        MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0"));

                        this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000);
                    };

                    this.arduino.AnalogPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.AnalogPinUpdated(pin, value);
                    };

                    this.arduino.DigitalPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.DigitalPinUpdated(pin, value);

                        if (pin == 8)
                        {
                            bool Input = (value == PinState.HIGH);
                            this.lastMotion = Input;
                            this.digitalInput0?.Set(Input);
                            this.presenceSensor0?.Set(Input);
                            this.genericSensor0?.Set(Input ? 1.0 : 0.0);
                            this.motionResource?.TriggerAll();
                            this.momentaryResource?.TriggerAll();
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }

                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                /************************************************************************************
                * To create an unencrypted CoAP Endpoint on the default CoAP port:
                *
                *    this.coapEndpoint = new CoapEndpoint();
                *
                * To create an unencrypted CoAP Endpoint on the default CoAP port,
                * with a sniffer that outputs communication to the window:
                *
                *    this.coapEndpoint = new CoapEndpoint(new LogSniffer());
                *
                * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using
                * the users defined in the IUserSource users:
                *
                *    this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users);
                *
                * To create a CoAP endpoint, that listens to both the default CoAP port, for
                * unencrypted communication, and the default CoAPS port, for encrypted,
                * authenticated and authorized communication, using
                * the users defined in the IUserSource users. Only users having the given
                * privilege (if not empty) will be authorized to access resources on the endpoint:
                *
                *    this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                *       new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false);
                *
                ************************************************************************************/

                //this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                //	new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false);

                this.coapEndpoint = new CoapEndpoint(new int[] { 5783 }, new int[] { 5784 }, null, null,
                                                     false, false);

                this.lightResource = this.coapEndpoint.Register("/Light", (req, resp) =>
                {
                    string s;

                    if (this.lastLight.HasValue)
                    {
                        s = ToString(this.lastLight.Value, 2) + " %";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, Notifications.Unacknowledged, "Light, in %.", null, null,
                                                                new int[] { PlainText.ContentFormatCode });

                this.lightResource?.TriggerAll(new TimeSpan(0, 0, 5));

                this.motionResource = this.coapEndpoint.Register("/Motion", (req, resp) =>
                {
                    string s;

                    if (this.lastMotion.HasValue)
                    {
                        s = this.lastMotion.Value ? "true" : "false";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, Notifications.Acknowledged, "Motion detector.", null, null,
                                                                 new int[] { PlainText.ContentFormatCode });

                this.motionResource?.TriggerAll(new TimeSpan(0, 1, 0));

                this.momentaryResource = this.coapEndpoint.Register("/Momentary", (req, resp) =>
                {
                    if (req.IsAcceptable(Xml.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsXml(req, resp);
                    }
                    else if (req.IsAcceptable(Json.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsJson(req, resp);
                    }
                    else if (req.IsAcceptable(PlainText.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsPlainText(req, resp);
                    }
                    else if (req.Accept.HasValue)
                    {
                        throw new CoapException(CoapCode.NotAcceptable);
                    }
                    else
                    {
                        this.ReturnMomentaryAsPlainText(req, resp);
                    }
                }, Notifications.Acknowledged, "Momentary values.", null, null,
                                                                    new int[] { Xml.ContentFormatCode, Json.ContentFormatCode, PlainText.ContentFormatCode });

                this.momentaryResource?.TriggerAll(new TimeSpan(0, 0, 5));

                this.lwm2mClient = new Lwm2mClient("MIoT:Sensor:" + this.deviceId, this.coapEndpoint,
                                                   new Lwm2mSecurityObject(),
                                                   new Lwm2mServerObject(),
                                                   new Lwm2mAccessControlObject(),
                                                   new Lwm2mDeviceObject("Waher Data AB", "SensorLwm2m", this.deviceId, "1.0", "Sensor", "1.0", "1.0"),
                                                   new DigitalInput(this.digitalInput0           = new DigitalInputInstance(0, this.lastMotion, "Motion Detector", "PIR")),
                                                   new AnalogInput(this.analogInput0             = new AnalogInputInstance(0, this.lastLight, 0, 100, "Ambient Light Sensor", "%")),
                                                   new GenericSensor(this.genericSensor0         = new GenericSensorInstance(0, null, string.Empty, 0, 1, "Motion Detector", "PIR"),
                                                                     this.genericSensor1         = new GenericSensorInstance(1, this.lastLight, "%", 0, 100, "Ambient Light Sensor", "%")),
                                                   new IlluminanceSensor(this.illuminanceSensor0 = new IlluminanceSensorInstance(0, this.lastLight, "%", 0, 100)),
                                                   new PresenceSensor(this.presenceSensor0       = new PresenceSensorInstance(0, this.lastMotion, "PIR")),
                                                   new PercentageSensor(this.percentageSensor0   = new PercentageSensorInstance(0, this.lastLight, 0, 100, "Ambient Light Sensor")));

                await this.lwm2mClient.LoadBootstrapInfo();

                this.lwm2mClient.OnStateChanged += (sender, e) =>
                {
                    Log.Informational("LWM2M state changed to " + this.lwm2mClient.State.ToString() + ".");
                };

                this.lwm2mClient.OnBootstrapCompleted += (sender, e) =>
                {
                    Log.Informational("Bootstrap procedure completed.");
                };

                this.lwm2mClient.OnBootstrapFailed += (sender, e) =>
                {
                    Log.Error("Bootstrap procedure failed.");

                    this.coapEndpoint.ScheduleEvent(async(P) =>
                    {
                        try
                        {
                            await this.RequestBootstrap();
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    }, DateTime.Now.AddMinutes(15), null);
                };

                this.lwm2mClient.OnRegistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server registration completed.");
                };

                this.lwm2mClient.OnRegistrationFailed += (sender, e) =>
                {
                    Log.Error("Server registration failed.");
                };

                this.lwm2mClient.OnDeregistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server deregistration completed.");
                };

                this.lwm2mClient.OnDeregistrationFailed += (sender, e) =>
                {
                    Log.Error("Server deregistration failed.");
                };

                this.lwm2mClient.OnRebootRequest += async(sender, e) =>
                {
                    Log.Warning("Reboot is requested.");

                    try
                    {
                        await this.RequestBootstrap();
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                await this.RequestBootstrap();
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }