public void Init()
        {
            if (controllerFlag)
            {
                if (gpioController.TryOpenPin(TRIGGER, GpioSharingMode.Exclusive, out gpioTrigger, out gpioOpenStatus[0]))
                {
                    gpioTrigger.SetDriveMode(GpioPinDriveMode.Output);
                    gpioTrigger.Write(GpioPinValue.Low);
                }

                for (int i = 0; i < 3; i++)
                {
                    if (gpioController.TryOpenPin(LevelPins[i], GpioSharingMode.Exclusive, out gpioLevels[i], out gpioOpenStatus[i + 1]))
                    {
                        gpioLevels[i].SetDriveMode(GpioPinDriveMode.Input);
                        gpioLevels[i].ValueChanged += LevelValueChanged;
                    }
                }
            }
            else
            {
                Debug.WriteLine("ERROR, No Controller");
            }

            EventLevels(this, new LevelsEventArgs(0));
        }
示例#2
0
        private void InitializeDevice()
        {
            GpioPin dataPin;
            GpioPin clockPin;

            if (device == null)
            {
                GpioController controller = GpioController.GetDefault();
                GpioOpenStatus status;
                if (controller != null &&
                    controller.TryOpenPin(AppSettings.ClockPinNumber, GpioSharingMode.Exclusive, out clockPin, out status) &&
                    controller.TryOpenPin(AppSettings.DataPinNumber, GpioSharingMode.Exclusive, out dataPin, out status))
                {
                    device = new HX711(clockPin, dataPin);
                }
                else
                {
                    device = null;
                }
            }
            if (device != null)
            {
                device.PowerOn();
            }
        }
示例#3
0
        public async Task <bool> TryInitGPIO()
        {
            GpioController gpioController = GpioController.GetDefault();

            if (gpioController == null)
            {
                await WriteMessage("This Device is not IoT friendly!  (No GPIO Controller found)", true);

                return(false);
            }
            if (gpioController.TryOpenPin(LEDPinNumber, GpioSharingMode.Exclusive, out LEDPin, out GpioOpenStatus openStatus))
            {
                await WriteMessage($"Output Pin ({LEDPinNumber}) Opened Successfully!!");
            }
            else
            {
                await WriteMessage($"Output Pin ({LEDPinNumber}) Failed to Open", true);

                return(false);
            }

            LEDPin.SetDriveMode(GpioPinDriveMode.Output);
            LEDPin.Write(GpioPinValue.High);
            LEDPinState = true;
            await UpdateLight();
            await WriteMessage("Output Pin initialized and on");

            return(true);
        }
示例#4
0
        private void InitializeGpio()
        {
            _gpioController = GpioController.GetDefault();
            List <int> keysToRemove = new List <int>();

            foreach (int key in GpioPinDictionary.Keys)
            {
                GpioPin        gpioPin;
                GpioOpenStatus status;
                _gpioController.TryOpenPin(key, GpioSharingMode.SharedReadOnly, out gpioPin, out status);

                if (status == GpioOpenStatus.PinOpened)
                {
                    Pin pin = GpioPinDictionary[key];
                    pin.GpioPin           = gpioPin;
                    pin.IsActive          = gpioPin.Read() == GpioPinValue.High;
                    gpioPin.ValueChanged += GpioPinOnValueChanged;
                }
                else if (status == GpioOpenStatus.PinUnavailable)
                {
                    keysToRemove.Add(key);
                }
            }

            foreach (int i in keysToRemove)
            {
                GpioPinDictionary[i].IsUnavailable = true;
                GpioPinDictionary.Remove(i);
            }
        }
示例#5
0
        public HX711()
        {
            GpioController controller = GpioController.GetDefault();
            GpioPin        clockPin;
            GpioPin        dataPin;
            GpioOpenStatus status;

            if (controller != null &&
                controller.TryOpenPin(6, GpioSharingMode.Exclusive, out clockPin, out status) &&
                controller.TryOpenPin(5, GpioSharingMode.Exclusive, out dataPin, out status))
            {
                PowerDownAndSerialClockInput = clockPin;
                PowerDownAndSerialClockInput.SetDriveMode(GpioPinDriveMode.Output);

                SerialDataOutput = dataPin;
                SerialDataOutput.SetDriveMode(GpioPinDriveMode.Input);
            }
        }
        async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            //Get a deferral so we can use an awaitable API to respond to the message
            var messageDeferral = args.GetDeferral();

            try
            {
                var    input      = args.Request.Message;
                string appName    = input["AppName"].ToString();
                string actionName = input["ActionName"].ToString();

                //Create the response
                var result = new ValueSet();

                if (gpioController != null)
                {
                    if (ledPin == null)
                    {
                        gpioController.TryOpenPin(LED_PIN, GpioSharingMode.Exclusive, out ledPin, out pinStatus);
                        if (ledPin != null)
                        {
                            ledPin.SetDriveMode(GpioPinDriveMode.Output);
                        }
                    }
                }

                if (actionName == "error")
                {
                    //Open LED
                    ledPin.Write(GpioPinValue.High);
                    result.Add("led-status", "ON");
                }

                if (actionName == "clear")
                {
                    //Close LED
                    ledPin.Write(GpioPinValue.Low);
                    result.Add("led-status", "OFF");
                }

                //Send the response
                await args.Request.SendResponseAsync(result);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                //Complete the message deferral so the platform knows we're done responding
                messageDeferral.Complete();
            }
        }
示例#7
0
 private static bool InitializeRight(GpioController controller)
 {
     if (!controller.TryOpenPin(3, GpioSharingMode.Exclusive, out _rightDoor, out GpioOpenStatus rightStatus))
     {
         return(false);
     }
     if (rightStatus != GpioOpenStatus.PinOpened)
     {
         return(false);
     }
     _rightDoor.SetDriveMode(GpioPinDriveMode.Output);
     _rightDoor.Write(GpioPinValue.High);
     return(true);
 }
示例#8
0
        public void Initialize()
        {
            if (device == null)
            {
                GpioController controller = GpioController.GetDefault();
                GpioOpenStatus status;

                if (controller != null &&
                    controller.TryOpenPin(Int32.Parse(CalibrationSettings[WeightClockGpioPinNumberSetting].ToString()), GpioSharingMode.Exclusive, out clockPin, out status) &&
                    controller.TryOpenPin(Int32.Parse(CalibrationSettings[WeightDataGpioPinNumberSetting].ToString()), GpioSharingMode.Exclusive, out dataPin, out status))
                {
                    device = new HX711(clockPin, dataPin);
                }
                else
                {
                    device = null;
                }
            }
            if (device != null)
            {
                device.PowerOn();
            }
        }
 public StatusLED(byte clock_pin, byte data_pin, byte num_leds)
 {
     this.gpio = GpioController.GetDefault();
     if (gpio == null)
     {
         Debug.WriteLine("There is no GPIO controller on this device.");
         return;
     }
     else
     {
         this.clockPin         = clock_pin;
         this.dataPin          = data_pin;
         this.numLeds          = num_leds;
         this.ledVals          = new Dictionary <byte, RGBVal>();
         this.generatedLedVals = new Dictionary <byte, RGBVal>();
         this.timer            = new DispatcherTimer();
         bool clockOpen = gpio.TryOpenPin(this.clockPin, GpioSharingMode.Exclusive, out gpClockPin, out gpClockStatus);
         bool dataOpen  = gpio.TryOpenPin(this.dataPin, GpioSharingMode.Exclusive, out gpDataPin, out gpDataStatus);
         gpClockPin.SetDriveMode(GpioPinDriveMode.Output);
         gpDataPin.SetDriveMode(GpioPinDriveMode.Output);
         if (!dataOpen || !clockOpen)
         {
             throw new Exception("Failed to open required pins.");
         }
         for (byte i = 0; i < this.numLeds; i++)
         {
             this.ledVals[i]          = new RGBVal(0, 0, 0);
             this.generatedLedVals[i] = new RGBVal(0, 0, 0);
         }
         hasUpdate           = true;
         manualMode          = true;
         this.timer.Interval = TimeSpan.FromMilliseconds(100);
         this.timer.Tick    += Timer_Tick;
         this.timer.Start();
         Debug.WriteLine("Started status led thing.");
     }
 }
        public GpioPin OpenPin(int pinNumber, GpioSharingMode sharingMode = GpioSharingMode.Exclusive)
        {
            GpioPin        pin = null;
            GpioOpenStatus status;

            if (m_controller.TryOpenPin(pinNumber, sharingMode, out pin, out status))
            {
                if (Pins == null)
                {
                    Pins = new List <Pin>();
                }

                Pins.Add(new Pin(pinNumber, pin, status));
            }

            return(pin);
        }
示例#11
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            await load();

            try
            {
                var id = int.Parse(gpio.Text);
                switch (pwmselect.SelectedIndex)
                {
                case 1:
                case 0:
                {
                    gpioPin?.Dispose();
                    gpioPin = null;
                    pwmPin?.Dispose();
                    pwmPin = null;
                    try
                    {
                        pwmPin = pwmController.OpenPin(id);
                    }
                    catch (Exception err)
                    {
                        _ = new MessageDialog("打开指定硬件PWM GPIO接口失败" + err.ToString()).ShowAsync();
                    }
                }
                break;

                default:
                {
                    if (gpioController.TryOpenPin(id, GpioSharingMode.Exclusive, out var pin, out var gpioOpenStatus))
                    {
                        pwmPin?.Dispose();
                        pwmPin = null;
                        gpioPin?.Dispose();
                        gpioPin = null;
                        gpioPin = pin;
                    }
                    else
                    {
                        _ = new MessageDialog("打开指定GPIO接口失败").ShowAsync();
                    }
                }
示例#12
0
        private void InitDHT22()
        {
            GpioController gpc      = GpioController.GetDefault();
            GpioPin        dht22Pin = null;

            if (gpc == null)
            {
                App.log.LogEvent("Contrôleur GPIO absent !", null, LoggingLevel.Warning);
            }
            else
            {
                GpioOpenStatus status;
                if (!gpc.TryOpenPin(17, GpioSharingMode.Exclusive, out dht22Pin, out status))
                {
                    App.log.LogEvent("L'accès à la broche GPIO 17 est impossible : " + status.ToString(), null, LoggingLevel.Warning);
                }
            }
            _dht22 = new DHT22(dht22Pin);
            DHT22SPL.DataContext = new DHT22VM(_dht22);
        }
示例#13
0
        public static GpioPin InitGpioPin(this GpioController controller,
                                          int pinNumber,
                                          GpioPinDriveMode driverMode = GpioPinDriveMode.Input,
                                          GpioSharingMode sharingMode = GpioSharingMode.Exclusive)
        {
            GpioPin        pin;
            GpioOpenStatus openStatus;

            if (!controller.TryOpenPin(pinNumber, sharingMode, out pin, out openStatus))
            {
                throw new IOException($"Unable to open Pin Number {pinNumber}!");
            }
            pin.Write(GpioPinValue.Low);
            pin.SetDriveMode(driverMode);
            if (openStatus != GpioOpenStatus.PinOpened)
            {
                throw new IOException($"Pin Number {pinNumber} was opened but has an open status of [{openStatus}]!");
            }
            return(pin);
        }
示例#14
0
        void InitialiseGpioPin()
        {
            GpioController gpioController = null;

            try { gpioController = GpioController.GetDefault(); }
            catch (FileNotFoundException) { };

            if (gpioController != null)
            {
                GpioPin        localPin   = null;
                GpioOpenStatus openStatus = GpioOpenStatus.PinUnavailable;

                if (gpioController.TryOpenPin(
                        this.GpioPinNumber, GpioSharingMode.Exclusive, out localPin, out openStatus))
                {
                    this.gpioPin = localPin;
                    this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);
                }
            }
        }
示例#15
0
        private GpioPin OpenPin(int pin)
        {
            if (gpio == null)
            {
                gpio = GpioController.GetDefault();
            }

            GpioPin gpioPin = null;

            if (!gpioPins.ContainsKey(pin))
            {
                // Try at least 3 times before failing completely
                for (int i = 0; i < 3; i++)
                {
                    GpioOpenStatus status;
                    if (gpio.TryOpenPin(pin, GpioSharingMode.Exclusive, out gpioPin, out status))
                    {
                        if (status == GpioOpenStatus.PinOpened)
                        {
                            gpioPin.SetDriveMode(GpioPinDriveMode.Output);
                            gpioPins.Add(pin, gpioPin);
                            break;
                        }
                        else
                        {
                            System.Threading.Tasks.Task.Delay(250);
                        }
                    }
                }
            }
            else
            {
                gpioPin = gpioPins[pin];
            }

            return(gpioPin);
        }
        private bool OpenGpioPin(int pinNumber, out GpioPin pin)
        {
            GpioOpenStatus openStat = GpioOpenStatus.PinUnavailable;

            if (_controller.TryOpenPin(pinNumber, GpioSharingMode.Exclusive, out pin, out openStat))
            {
                switch (openStat)
                {
                case GpioOpenStatus.PinOpened:
                    Debug.WriteLine("Pin Successfully opened - Pin Number - {0}!!", pinNumber);
                    break;

                case GpioOpenStatus.PinUnavailable:
                    Debug.WriteLine("Pin Unavailable. Pin Number - {0}", pinNumber);
                    break;

                case GpioOpenStatus.SharingViolation:
                    Debug.WriteLine("Sharing violation to open pin on pin number - {0}", pinNumber);
                    break;
                }
            }

            return(openStat == GpioOpenStatus.PinOpened);
        }
示例#17
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);

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

                await db.Start();

#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();

                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 += 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);
                }
#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 is null && req.Payload != null)
                        {
                            s = Encoding.UTF8.GetString(req.Payload);
                        }

                        if (s is 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,
示例#18
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(XmppClient).GetTypeInfo().Assembly,
                    typeof(Waher.Content.Markdown.MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(XML).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Expression).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Graphs.Graph).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 ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(this.output);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output));
                        }
                        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();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo == 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 += 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);

                            await MainPage.Instance.OutputSet(this.output.Value);

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

                            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);
                }
#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);

                string Host = await RuntimeSettings.GetAsync("XmppHost", "waher.se");

                int Port = (int)await RuntimeSettings.GetAsync("XmppPort", 5222);

                string UserName = await RuntimeSettings.GetAsync("XmppUserName", string.Empty);

                string PasswordHash = await RuntimeSettings.GetAsync("XmppPasswordHash", string.Empty);

                string PasswordHashMethod = await RuntimeSettings.GetAsync("XmppPasswordHashMethod", string.Empty);

                if (string.IsNullOrEmpty(Host) ||
                    Port <= 0 || Port > ushort.MaxValue ||
                    string.IsNullOrEmpty(UserName) ||
                    string.IsNullOrEmpty(PasswordHash) ||
                    string.IsNullOrEmpty(PasswordHashMethod))
                {
                    await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                async() => await this.ShowConnectionDialog(Host, Port, UserName));
                }
                else
                {
                    this.xmppClient = new XmppClient(Host, Port, UserName, PasswordHash, PasswordHashMethod, "en",
                                                     typeof(App).GetTypeInfo().Assembly) // Add "new LogSniffer()" to the end, to output communication to the log.
                    {
                        AllowCramMD5   = false,
                        AllowDigestMD5 = false,
                        AllowPlain     = false,
                        AllowScramSHA1 = true
                    };
                    this.xmppClient.OnStateChanged    += this.StateChanged;
                    this.xmppClient.OnConnectionError += this.ConnectionError;
                    this.AttachFeatures();

                    Log.Informational("Connecting to " + this.xmppClient.Host + ":" + this.xmppClient.Port.ToString());
                    this.xmppClient.Connect();
                }

                this.minuteTimer = new Timer((State) =>
                {
                    if (this.xmppClient != null &&
                        (this.xmppClient.State == XmppState.Error || this.xmppClient.State == XmppState.Offline))
                    {
                        this.xmppClient.Reconnect();
                    }
                }, null, 60000, 60000);
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

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

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ImageCodec).GetTypeInfo().Assembly,
                    typeof(MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(MarkdownToHtmlConverter).GetTypeInfo().Assembly,
                    typeof(IJwsAlgorithm).GetTypeInfo().Assembly,
                    typeof(Expression).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

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

                await db.Start();

#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);

                            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();

                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 += 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);

                            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);
                }
#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);

                this.tokenAuthentication = new JwtAuthentication(this.deviceId, this.users, this.tokenFactory);

                this.httpServer = new HttpServer();
                //this.httpServer = new HttpServer(new LogSniffer());

                StorageFile File = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Root/favicon.ico"));

                string Root = File.Path;
                Root = Root.Substring(0, Root.Length - 11);
                this.httpServer.Register(new HttpFolderResource(string.Empty, Root, false, false, true, true));

                this.httpServer.Register("/", (req, resp) =>
                {
                    throw new TemporaryRedirectException("/Index.md");
                });

                this.httpServer.Register("/Momentary", (req, resp) =>
                {
                    resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");

                    if (req.Header.Accept != null)
                    {
                        switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json"))
                        {
                        case "text/xml":
                        case "application/xml":
                            this.ReturnMomentaryAsXml(req, resp);
                            break;

                        case "application/json":
                            this.ReturnMomentaryAsJson(req, resp);
                            break;

                        default:
                            throw new NotAcceptableException();
                        }
                    }
                    else
                    {
                        this.ReturnMomentaryAsXml(req, resp);
                    }

                    return(Task.CompletedTask);
                }, this.tokenAuthentication);

                this.httpServer.Register("/Set", null, async(req, resp) =>
                {
                    try
                    {
                        if (!req.HasData)
                        {
                            throw new BadRequestException();
                        }

                        if (!(req.DecodeData() is string s) || !CommonTypes.TryParse(s, out bool OutputValue))
                        {
                            throw new BadRequestException();
                        }

                        if (req.Header.Accept != null)
                        {
                            switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json"))
                            {
                            case "text/xml":
                            case "application/xml":
                                await this.SetOutput(OutputValue, req.RemoteEndPoint);
                                this.ReturnMomentaryAsXml(req, resp);
                                break;

                            case "application/json":
                                await this.SetOutput(OutputValue, req.RemoteEndPoint);
                                this.ReturnMomentaryAsJson(req, resp);
                                break;

                            default:
                                throw new NotAcceptableException();
                            }
                        }
                        else
                        {
                            await this.SetOutput(OutputValue, req.RemoteEndPoint);
                            this.ReturnMomentaryAsXml(req, resp);
                        }

                        await resp.SendResponse();
                    }
                    catch (Exception ex)
                    {
                        await resp.SendResponse(ex);
                    }
                }, false, this.tokenAuthentication);

                this.httpServer.Register("/Login", null, (req, resp) =>
                {
                    if (!req.HasData || req.Session is null)
                    {
                        throw new BadRequestException();
                    }

                    object Obj = req.DecodeData();

                    if (!(Obj is Dictionary <string, string> Form) ||
                        !Form.TryGetValue("UserName", out string UserName) ||
                        !Form.TryGetValue("Password", out string Password))
                    {
                        throw new BadRequestException();
                    }

                    string From = null;

                    if (req.Session.TryGetVariable("from", out Variable v))
                    {
                        From = v.ValueObject as string;
                    }

                    if (string.IsNullOrEmpty(From))
                    {
                        From = "/Index.md";
                    }

                    IUser User = this.Login(UserName, Password);
                    if (User != null)
                    {
                        Log.Informational("User logged in.", UserName, req.RemoteEndPoint, "LoginSuccessful", EventLevel.Minor);

                        req.Session["User"] = User;
                        req.Session.Remove("LoginError");

                        throw new SeeOtherException(From);
                    }
                    else
                    {
                        Log.Warning("Invalid login attempt.", UserName, req.RemoteEndPoint, "LoginFailure", EventLevel.Minor);
                        req.Session["LoginError"] = "Invalid login credentials provided.";
                    }

                    throw new SeeOtherException(req.Header.Referer.Value);
                }, true, false, true);

                this.httpServer.Register("/GetSessionToken", null, (req, resp) =>
                {
                    if (!req.Session.TryGetVariable("User", out Variable v) ||
                        !(v.ValueObject is IUser User))
                    {
                        throw new ForbiddenException();
                    }

                    string Token = this.tokenFactory.Create(new KeyValuePair <string, object>("sub", User.UserName));

                    resp.ContentType = JwtCodec.ContentType;
                    resp.Write(Token);

                    return(Task.CompletedTask);
                }, true, false, true);
            }
示例#20
0
文件: App.xaml.cs 项目: VRDate/MIoT
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

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

                await db.Start();

#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);

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

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

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));
                        }
                        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();

                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 += 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.

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

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

                            await MainPage.Instance.OutputSet(LastOn);

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

                            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);
                }
#endif
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
示例#21
0
        /// <summary>
        ///     Open a connection with the Servo Pi
        /// </summary>
        /// <returns></returns>
        /// <example>servopi.Connect();</example>
        public async Task Connect()
        {
            if (IsConnected)
            {
                return; // Already connected
            }

            if (!ApiInformation.IsTypePresent("Windows.Devices.I2c.I2cDevice"))
            {
                return; // This system does not support this feature: can't connect
            }

            /* Initialize the I2C bus */
            try
            {
                var aqs = I2cDevice.GetDeviceSelector(ABE_Helpers.I2C_CONTROLLER_NAME); // Find the selector string for the I2C bus controller
                var dis = await DeviceInformation.FindAllAsync(aqs);                    // Find the I2C bus controller device with our selector string

                if (dis.Count == 0)
                {
                    return; // Controller not found
                }

                var settings = new I2cConnectionSettings(Address)
                {
                    BusSpeed = I2cBusSpeed.FastMode
                };

                i2cbus = await I2cDevice.FromIdAsync(dis[0].Id, settings);

                /* Create an I2cDevice with our selected bus controller and I2C settings */
                if (i2cbus != null)
                {
                    // Connection is established so set IsConnected to true

                    IsConnected = true;

                    helper.WriteI2CByte(i2cbus, MODE1, 0x00);

                    // Check to see if the output pin has been set and if so try to connect to the GPIO pin on the Raspberry Pi
                    if (OutputEnablePin != 0)
                    {
                        gpio = GpioController.GetDefault();

                        if (gpio != null)
                        {
                            GpioOpenStatus status;

                            gpio.TryOpenPin(OutputEnablePin, GpioSharingMode.Exclusive, out pin, out status);
                            if (status == GpioOpenStatus.PinOpened)
                            {
                                // Latch HIGH value first. This ensures a default value when the pin is set as output
                                pin.Write(GpioPinValue.High);
                                // Set the IO direction as output
                                pin.SetDriveMode(GpioPinDriveMode.Output);
                            }
                        }
                    }

                    // Fire the Connected event handler
                    Connected?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    IsConnected = false;
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                throw new Exception("I2C Initialization Failed", ex);
            }
        }
示例#22
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));

#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());
            }
        }
示例#23
0
文件: App.xaml.cs 项目: lulzzz/MIoT
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).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);

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

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

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));
                        }
                        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();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo == 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 += 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.

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

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

                            await MainPage.Instance.OutputSet(LastOn);

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

                            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);
                }
#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);

                this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty);
                //this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty, new LogSniffer());
                this.mqttClient.OnStateChanged += (sender, state) =>
                {
                    Log.Informational("MQTT client state changed: " + state.ToString());

                    if (state == MqttState.Connected)
                    {
                        this.mqttClient.SUBSCRIBE("Waher/MIOT/" + this.deviceId + "/Set/+", MqttQualityOfService.AtLeastOnce);
                    }
                };

                this.mqttClient.OnContentReceived += async(sender, e) =>
                {
                    try
                    {
                        if (e.Topic.EndsWith("/On"))
                        {
                            string s = Encoding.UTF8.GetString(e.Data);
                            s = s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower();

                            if (bool.TryParse(s, out bool On))
                            {
                                await this.SetOutput(On, "MQTT");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                DateTime Now = DateTime.Now;
                this.reconnectionTimer = new Timer(this.CheckConnection, null, 120000 - Now.Millisecond - Now.Second * 1000, 60000);
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

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

				SimpleXmppConfiguration xmppConfiguration = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config",
					Guid.NewGuid().ToString().Replace("-", string.Empty),   // Default user name.
					Guid.NewGuid().ToString().Replace("-", string.Empty),   // Default password.
					FormSignatureKey, FormSignatureSecret, typeof(App).GetTypeInfo().Assembly);

				Log.Informational("Connecting to XMPP server.");

				xmppClient = xmppConfiguration.GetClient("en", typeof(App).GetTypeInfo().Assembly, false);
				xmppClient.AllowRegistration(FormSignatureKey, FormSignatureSecret);

				if (xmppConfiguration.Sniffer && MainPage.Sniffer != null)
					xmppClient.Add(MainPage.Sniffer);

				if (!string.IsNullOrEmpty(xmppConfiguration.Events))
					Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, xmppConfiguration.Events, false));

				if (!string.IsNullOrEmpty(xmppConfiguration.ThingRegistry))
				{
					thingRegistryClient = new ThingRegistryClient(xmppClient, xmppConfiguration.ThingRegistry);

					thingRegistryClient.Claimed += (sender, e) =>
					{
						ownerJid = e.JID;
						Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair<string, object>("Public", e.IsPublic));
						this.RaiseOwnershipChanged();
					};

					thingRegistryClient.Disowned += (sender, e) =>
					{
						Log.Informational("Thing has been disowned.", ownerJid);
						ownerJid = string.Empty;
						this.Register();    // Will call this.OwnershipChanged() after successful registration.
					};

					thingRegistryClient.Removed += (sender, e) =>
					{
						Log.Informational("Thing has been removed from the public registry.", ownerJid);
					};
				}

				if (!string.IsNullOrEmpty(xmppConfiguration.Provisioning))
					provisioningClient = new ProvisioningClient(xmppClient, xmppConfiguration.Provisioning);

				Timer ConnectionTimer = new Timer((P) =>
				{
					if (xmppClient.State == XmppState.Offline || xmppClient.State == XmppState.Error || xmppClient.State == XmppState.Authenticating)
					{
						try
						{
							Log.Informational("Reconnecting.");
							xmppClient.Reconnect();
						}
						catch (Exception ex)
						{
							Log.Critical(ex);
						}
					}
				}, null, 60000, 60000);

				xmppClient.OnStateChanged += (sender, NewState) =>
				{
					Log.Informational(NewState.ToString());

					switch (NewState)
					{
						case XmppState.Connected:
							connected = true;

							if (!registered && this.thingRegistryClient != null)
								this.Register();

							break;

						case XmppState.Offline:
							immediateReconnect = connected;
							connected = false;

							if (immediateReconnect)
								xmppClient.Reconnect();
							break;
					}
				};

				xmppClient.OnPresenceSubscribe += (sender, e) =>
				{
					Log.Informational("Subscription request received from " + e.From + ".");

					e.Accept();     // TODO: Provisioning

					RosterItem Item = xmppClient.GetRosterItem(e.FromBareJID);
					if (Item == null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From)
						xmppClient.RequestPresenceSubscription(e.FromBareJID);

					xmppClient.SetPresence(Availability.Chat);
				};

				xmppClient.OnPresenceUnsubscribe += (sender, e) =>
				{
					Log.Informational("Unsubscription request received from " + e.From + ".");
					e.Accept();
				};

				xmppClient.OnRosterItemUpdated += (sender, e) =>
				{
					if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe)
						xmppClient.RemoveRosterItem(e.BareJid);
				};

				gpio = GpioController.GetDefault();
				if (gpio != null)
				{
					int c = gpio.PinCount;
					int i;

					for (i = 0; i < c; i++)
					{
						if (gpio.TryOpenPin(i, GpioSharingMode.Exclusive, out GpioPin Pin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened)
						{
							gpioPins[i] = new KeyValuePair<GpioPin, KeyValuePair<TextBlock, TextBlock>>(Pin,
								MainPage.Instance.AddPin("GPIO" + i.ToString(), Pin.GetDriveMode(), Pin.Read().ToString()));

							Pin.ValueChanged += async (sender, e) =>
							{
								if (!this.gpioPins.TryGetValue(sender.PinNumber, out KeyValuePair<GpioPin, KeyValuePair<TextBlock, TextBlock>> P))
									return;

								PinState Value = e.Edge == GpioPinEdge.FallingEdge ? PinState.LOW : PinState.HIGH;

								if (this.sensorServer.HasSubscriptions(ThingReference.Empty))
								{
									DateTime TP = DateTime.Now;
									string s = "GPIO" + sender.PinNumber.ToString();

									this.sensorServer.NewMomentaryValues(
										new EnumField(ThingReference.Empty, TP, s, Value, FieldType.Momentary, FieldQoS.AutomaticReadout));
								}

								await P.Value.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Value.Text = Value.ToString());
							};
						}
					}
				}

				DeviceInformationCollection Devices = await Microsoft.Maker.Serial.UsbSerial.listAvailableDevicesAsync();
				foreach (DeviceInformation DeviceInfo in Devices)
				{
					if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith("Arduino"))
					{
						Log.Informational("Connecting to " + DeviceInfo.Name);
						arduinoUsb = new UsbSerial(DeviceInfo);
						arduinoUsb.ConnectionEstablished += () =>
						{
							Log.Informational("USB connection established.");
						};

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

							Dictionary<int, bool> DisabledPins = new Dictionary<int, bool>();
							Dictionary<string, KeyValuePair<Enum, string>> Values = new Dictionary<string, KeyValuePair<Enum, string>>();
							PinMode Mode;
							PinState State;
							string s;
							ushort Value;

							foreach (byte PinNr in arduino.DeviceHardwareProfile.DisabledPins)
								DisabledPins[PinNr] = true;

							foreach (byte PinNr in arduino.DeviceHardwareProfile.AnalogPins)
							{
								if (DisabledPins.ContainsKey(PinNr))
									continue;

								s = "A" + (PinNr - arduino.DeviceHardwareProfile.AnalogOffset).ToString();
								if (arduino.DeviceHardwareProfile.isAnalogSupported(PinNr))
									arduino.pinMode(s, PinMode.ANALOG);

								Mode = arduino.getPinMode(s);
								Value = arduino.analogRead(s);

								Values[s] = new KeyValuePair<Enum, string>(Mode, Value.ToString());
							}

							foreach (byte PinNr in arduino.DeviceHardwareProfile.DigitalPins)
							{
								if (DisabledPins.ContainsKey(PinNr) || (PinNr > 6 && PinNr != 13))	// Not sure why this limitation is necessary. Without it, my Arduino board (or the Microsoft Firmata library) stops providing me with pin update events.
									continue;

								if (PinNr == 13)
								{
									arduino.pinMode(13, PinMode.OUTPUT);    // Onboard LED.
									arduino.digitalWrite(13, PinState.HIGH);
								}
								else
								{
									if (arduino.DeviceHardwareProfile.isDigitalInputSupported(PinNr))
										arduino.pinMode(PinNr, PinMode.INPUT);
								}

								s = "D" + PinNr.ToString();
								Mode = arduino.getPinMode(PinNr);
								State = arduino.digitalRead(PinNr);

								Values[s] = new KeyValuePair<Enum, string>(Mode, State.ToString());
							}

							await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
							{
								lock (arduinoPins)
								{
									foreach (KeyValuePair<string, KeyValuePair<Enum, string>> P in Values)
										arduinoPins[P.Key] = MainPage.Instance.AddPin(P.Key, P.Value.Key, P.Value.Value);
								}
							});

							this.SetupControlServer();
						};

						arduino.AnalogPinUpdated += async (pin, value) =>
						{
							KeyValuePair<TextBlock, TextBlock> P;
							DateTime TP = DateTime.Now;

							lock (this.arduinoPins)
							{
								if (!this.arduinoPins.TryGetValue(pin, out P))
									return;
							}

							if (this.sensorServer.HasSubscriptions(ThingReference.Empty))
							{
								this.sensorServer.NewMomentaryValues(
									new Int32Field(ThingReference.Empty, TP, pin + ", Raw",
										value, FieldType.Momentary, FieldQoS.AutomaticReadout),
									new QuantityField(ThingReference.Empty, TP, pin,
										value / 10.24, 2, "%", FieldType.Momentary, FieldQoS.AutomaticReadout));
							}

							await P.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Text = value.ToString());
						};

						arduino.DigitalPinUpdated += async (pin, value) =>
						{
							KeyValuePair<TextBlock, TextBlock> P;
							DateTime TP = DateTime.Now;
							string s = "D" + pin.ToString();

							lock (this.arduinoPins)
							{
								if (!this.arduinoPins.TryGetValue("D" + pin.ToString(), out P))
									return;
							}

							if (this.sensorServer.HasSubscriptions(ThingReference.Empty))
							{
								this.sensorServer.NewMomentaryValues(
									new EnumField(ThingReference.Empty, TP, s, value, FieldType.Momentary, FieldQoS.AutomaticReadout));
							}

							await P.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Text = value.ToString());
						};

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

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

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

				sensorServer = new SensorServer(xmppClient, provisioningClient, true);
				sensorServer.OnExecuteReadoutRequest += (Sender, Request) =>
				{
					DateTime Now = DateTime.Now;
					LinkedList<Field> Fields = new LinkedList<Field>();
					DateTime TP = DateTime.Now;
					string s;
					bool ReadMomentary = Request.IsIncluded(FieldType.Momentary);
					bool ReadStatus = Request.IsIncluded(FieldType.Status);

					Log.Informational("Readout requested", string.Empty, Request.Actor);

					foreach (KeyValuePair<GpioPin, KeyValuePair<TextBlock, TextBlock>> Pin in gpioPins.Values)
					{
						if (ReadMomentary && Request.IsIncluded(s = "GPIO" + Pin.Key.PinNumber.ToString()))
						{
							Fields.AddLast(new EnumField(ThingReference.Empty, TP, s,
								Pin.Key.Read(), FieldType.Momentary, FieldQoS.AutomaticReadout));
						}

						if (ReadStatus && Request.IsIncluded(s = "GPIO" + Pin.Key.PinNumber.ToString() + ", Mode"))
						{
							Fields.AddLast(new EnumField(ThingReference.Empty, TP, s,
								Pin.Key.GetDriveMode(), FieldType.Status, FieldQoS.AutomaticReadout));
						}
					}

					if (arduinoPins != null)
					{
						foreach (KeyValuePair<string, KeyValuePair<TextBlock, TextBlock>> Pin in arduinoPins)
						{
							byte i;

							if (ReadMomentary && Request.IsIncluded(s = Pin.Key))
							{
								if (s.StartsWith("D") && byte.TryParse(s.Substring(1), out i))
								{
									Fields.AddLast(new EnumField(ThingReference.Empty, TP, s,
										arduino.digitalRead(i), FieldType.Momentary, FieldQoS.AutomaticReadout));
								}
								else
								{
									ushort Raw = arduino.analogRead(s);
									double Percent = Raw / 10.24;

									Fields.AddLast(new Int32Field(ThingReference.Empty, TP, s + ", Raw",
										Raw, FieldType.Momentary, FieldQoS.AutomaticReadout));

									Fields.AddLast(new QuantityField(ThingReference.Empty, TP, s,
										Percent, 2, "%", FieldType.Momentary, FieldQoS.AutomaticReadout));
								}
							}

							if (ReadStatus && Request.IsIncluded(s = Pin.Key + ", Mode"))
							{
								if (s.StartsWith("D") && byte.TryParse(s.Substring(1), out i))
								{
									Fields.AddLast(new EnumField(ThingReference.Empty, TP, s,
										arduino.getPinMode(i), FieldType.Status, FieldQoS.AutomaticReadout));
								}
								else
								{
									Fields.AddLast(new EnumField(ThingReference.Empty, TP, s,
										arduino.getPinMode(s), FieldType.Status, FieldQoS.AutomaticReadout));
								}
							}
						}
					}

					Request.ReportFields(true, Fields);
				};

				if (arduino == null)
					this.SetupControlServer();

                xmppClient.Connect();
			}
			catch (Exception ex)
			{
				Log.Emergency(ex);

				MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
				await Dialog.ShowAsync();
			}
		}
示例#25
0
        /// <summary>
        /// Open a connection with the Servo Pi
        /// </summary>
        /// <returns></returns>
        /// <example>servopi.Connect();</example>
        public async Task Connect()
        {
            /* Initialize the I2C bus */
            try
            {
                string aqs = I2cDevice.GetDeviceSelector(helper.I2C_CONTROLLER_NAME); /* Find the selector string for the I2C bus controller                   */
                var    dis = await DeviceInformation.FindAllAsync(aqs);               /* Find the I2C bus controller device with our selector string           */

                var settings = new I2cConnectionSettings(Address);
                settings.BusSpeed = I2cBusSpeed.FastMode;

                i2cbus = await I2cDevice.FromIdAsync(dis[0].Id, settings);    /* Create an I2cDevice with our selected bus controller and I2C settings */

                if (i2cbus != null)
                {
                    // Connection is established so set IsConnected to true

                    IsConnected = true;

                    helper.WriteI2CByte(i2cbus, MODE1, 0x00);

                    // Check to see if the output pin has been set and if so try to connect to the GPIO pin on the Raspberry Pi
                    if (OutputEnablePin != 0)
                    {
                        gpio = GpioController.GetDefault();

                        if (gpio != null)
                        {
                            GpioOpenStatus status;

                            gpio.TryOpenPin(OutputEnablePin, GpioSharingMode.Exclusive, out pin, out status);
                            if (status == GpioOpenStatus.PinOpened)
                            {
                                // Latch HIGH value first. This ensures a default value when the pin is set as output
                                pin.Write(GpioPinValue.High);
                                // Set the IO direction as output
                                pin.SetDriveMode(GpioPinDriveMode.Output);
                            }
                        }
                    }

                    // Fire the Connected event handler

                    EventHandler handler = Connected;
                    if (handler != null)
                    {
                        handler(this, EventArgs.Empty);
                    }
                }
                else
                {
                    IsConnected = false;
                }
                return;
            }
            /* If initialization fails, display the exception and stop running */
            catch (Exception e)
            {
                IsConnected = false;
                throw e;
            }
        }