private void InitFirmata() { //USB\VID_2A03&PID_0043&REV_0001 //create a serial connection //var devices = await UsbSerial.listAvailableDevicesAsync(); //var devList = devices.ToList(); serial = new UsbSerial("VID_2A03", "PID_0043"); //construct the firmata client firmata = new UwpFirmata(); firmata.FirmataConnectionReady += Firmata_FirmataConnectionReady; firmata.StringMessageReceived += Firmata_StringMessageReceived; //last, construct the RemoteWiring layer by passing in our Firmata layer. arduino = new RemoteDevice(firmata); arduino.DeviceReady += Arduino_DeviceReady; //if you create the firmata client yourself, don't forget to begin it! firmata.begin(serial); //you must always call 'begin' on your IStream object to connect. //these parameters do not matter for bluetooth, as they depend on the device. However, these are the best params to use for USB, so they are illustrated here serial.begin(57600, SerialConfig.SERIAL_8N1); }
public ControlPage() { this.InitializeComponent(); turn = Turn.none; direction = Direction.none; accelerometer = App.accelerometer; bluetooth = App.bluetooth; arduino = App.arduino; if (accelerometer == null || bluetooth == null || arduino == null) { Frame.Navigate(typeof(MainPage)); return; } startButton.IsEnabled = true; stopButton.IsEnabled = true; disconnectButton.IsEnabled = true; keepScreenOnRequest = new DisplayRequest(); keepScreenOnRequest.RequestActive(); App.arduino.pinMode(enableA, PinMode.OUTPUT); App.arduino.pinMode(MotorA1, PinMode.OUTPUT); App.arduino.pinMode(MotorA2, PinMode.OUTPUT); App.arduino.pinMode(enableB, PinMode.OUTPUT); App.arduino.pinMode(MotorB1, PinMode.OUTPUT); App.arduino.pinMode(MotorB2, PinMode.OUTPUT); arduino.digitalWrite(enableA, PinState.HIGH); arduino.digitalWrite(enableB, PinState.HIGH); }
public ControlPage() { this.InitializeComponent(); turn = Turn.none; direction = Direction.none; accelerometer = App.accelerometer; bluetooth = App.bluetooth; arduino = App.arduino; if( accelerometer == null || bluetooth == null || arduino == null ) { Frame.Navigate( typeof( MainPage ) ); return; } startButton.IsEnabled = true; stopButton.IsEnabled = true; disconnectButton.IsEnabled = true; bluetooth.ConnectionLost += Bluetooth_ConnectionLost; keepScreenOnRequest = new DisplayRequest(); keepScreenOnRequest.RequestActive(); App.arduino.pinMode( LR_DIRECTION_CONTROL_PIN, PinMode.OUTPUT ); App.arduino.pinMode( FB_DIRECTION_CONTROL_PIN, PinMode.OUTPUT ); App.arduino.pinMode( LR_MOTOR_CONTROL_PIN, PinMode.PWM ); App.arduino.pinMode( FB_MOTOR_CONTROL_PIN, PinMode.PWM ); App.arduino.pinMode(HEARTBEAT_LED_PIN, PinMode.OUTPUT); }
private void btnConnect_Click(object sender, RoutedEventArgs e) { Helpers.OutputTextBox = txtMessages; Helpers.ShowMessage("About to Connect"); // *** IMPORTANT *** // You need to add the VID and PID for your device. // I'll post screen shots of finding it on my blog // at http://MosesSoftware.com // // NOTE: The line below is, obviously, for a USB cnnected // device. You can also use a BlueTooth. connection = new UsbSerial("VID_2341", "PID_0042"); arduino = new RemoteDevice(connection); arduino.DeviceReady += OnDeviceReady; arduino.AnalogPinUpdated += OnAnalogPinUpdated; arduino.DeviceConnectionFailed += OnDeviceConnectionFailed; arduino.DeviceConnectionLost += OnDeviceConnectionLost; arduino.DigitalPinUpdated += OnDigitialPinUpdated; arduino.StringMessageReceived += OnStringMessageReceived; arduino.SysexMessageReceived += OnSysexMessageReceived; arduino.I2c.I2cReplyEvent += OnI2CReplyEvent; // *** IMPORTANT *** // Make sure the baud rate is the same as the one specified // in the Firmata program uploaded to the arduino. connection.begin(57600, SerialConfig.SERIAL_8N1); }
public RemoteDevice CreateDeviceUnderTestAndConnect(MockBoard board) { // setup and start connection events RemoteDevice device = null; mockFirmataStream = new MockStream(board); device = new RemoteDevice(mockFirmataStream); device.DeviceReady += OnDeviceReady; device.DeviceConnectionFailed += OnConnectionFailed; mockFirmataStream.begin(0, SerialConfig.SERIAL_8N1); // Wait for connection DateTime timeout = DateTime.UtcNow.AddMilliseconds(10000); System.Threading.SpinWait.SpinUntil(() => ( timeout <= DateTime.UtcNow || mockFirmataStream.connectionReady() || this.DeviceState == DeviceState.Ready )); foreach(var pin in board.Pins) { pin.CurrentValueChanged += Pin_CurrentValueChanged; } return device; }
public ControlPageMaisto() { this.InitializeComponent(); turn = Turn.none; direction = Direction.none; accelerometer = App.accelerometer; bluetooth = App.bluetooth; arduino = App.arduino; if( accelerometer == null || bluetooth == null || arduino == null ) { Frame.Navigate( typeof( MainPage ) ); return; } startButton.IsEnabled = true; stopButton.IsEnabled = true; disconnectButton.IsEnabled = true; bluetooth.ConnectionLost += Bluetooth_ConnectionLost; keepScreenOnRequest = new DisplayRequest(); keepScreenOnRequest.RequestActive(); App.arduino.pinMode( FORWARD_CONTROL_PIN, PinMode.OUTPUT ); App.arduino.pinMode( REVERSE_CONTROL_PIN, PinMode.OUTPUT ); App.arduino.pinMode( LEFT_CONTROL_PIN, PinMode.OUTPUT ); App.arduino.pinMode( RIGHT_CONTROL_PIN, PinMode.OUTPUT ); }
public MainPage() { this.InitializeComponent(); if( useBluetooth ) { /* * I've written my bluetooth device name as a parameter to the BluetoothSerial constructor. You should change this to your previously-paired * device name if using Bluetooth. You can also use the BluetoothSerial.listAvailableDevicesAsync() function to list * available devices, but that is not covered in this sample. */ bluetooth = new BluetoothSerial( "RNBT-E072" ); arduino = new RemoteDevice( bluetooth ); bluetooth.ConnectionEstablished += OnConnectionEstablished; //these parameters don't matter for bluetooth bluetooth.begin( 0, 0 ); } else { /* * I've written my Arduino device VID and PID as a parameter to the BluetoothSerial constructor. You should change this to your * device VID and PID if using USB. You can also use the UsbSerial.listAvailableDevicesAsync() function to list * available devices, but that is not covered in this sample. */ usb = new UsbSerial( "VID_2341", "PID_0043" ); //I've written in my device D directly arduino = new RemoteDevice( usb ); usb.ConnectionEstablished += OnConnectionEstablished; //SerialConfig.8N1 is the default config for Arduino devices over USB usb.begin( 115200, SerialConfig.SERIAL_8N1 ); } }
public BlinkyExample(RemoteDevice arduino, int millisecodInterval) { Arduino = arduino; Interval = millisecodInterval; timer = ThreadPoolTimer.CreatePeriodicTimer(OnTimerElapsed, TimeSpan.FromMilliseconds(millisecodInterval)); }
private void MainPage_Loaded(object sender, RoutedEventArgs e) { var connection = new BluetoothSerial("RNBT-A297"); _arduino = new RemoteDevice(connection); connection.ConnectionEstablished += Connection_ConnectionEstablished; connection.begin(0, 0); }
private void Arduino_Disconnect() { arduinoConnected = false; arduinoConnection.end(); arduinoConnection = null; arduino = null; }
public VirtualLDR(RemoteDevice arduino, UnoAnalogPins pin, int SampleRateMilliseconds, string name) : base("light", "p", SensorMakerDen.ValuesPerSample.One, SampleRateMilliseconds, name) { this.arduino = arduino; this.pin = pin; StartMeasuring(); }
public OutputPin(RemoteDevice arduino, byte pin, string name) : base(name, "output", IotType.Actuator) { this.arduino = arduino; this.pin = pin; arduino.pinMode(pin, PinMode.OUTPUT); }
public ServoController(RemoteDevice device, byte pin, bool inverse = false, int delay = 10) { _inverse = inverse; Device = device; Pin = pin; _delay = delay; Deattach(); }
public MainPage() { this.InitializeComponent(); UsbSerial connection =new UsbSerial("VID_2341", "PID_0043"); arduino = new RemoteDevice(connection); //just start typing this and you can autocomplete using tab connection.ConnectionEstablished += Connection_ConnectionEstablished; arduino.DeviceReady += TurnOnLight; connection.begin(57600, SerialConfig.SERIAL_8N1); }
public BandController( RemoteDevice device ) : base( device ) { connected = false; turn = Turn.none; direction = Direction.none; Device.pinMode( LR_DIRECTION_CONTROL_PIN, PinMode.OUTPUT ); Device.pinMode( FB_DIRECTION_CONTROL_PIN, PinMode.OUTPUT ); device.pinMode( LR_MOTOR_CONTROL_PIN, PinMode.PWM ); device.pinMode( FB_MOTOR_CONTROL_PIN, PinMode.PWM ); }
private async void Arduino_Connect() { arduinoConnected = false; ArduinoConnectionStatusText.Text = "Connecting..."; arduinoConnection = new BluetoothSerial( "RNBT-773E" ); arduino = new RemoteDevice( arduinoConnection ); arduino.DeviceReady += Arduino_DeviceReady; arduino.DeviceConnectionFailed += Arduino_DeviceConnectionFailed; arduino.DeviceConnectionLost += Arduino_DeviceConnectionLost; arduinoConnection.begin( 115200, SerialConfig.SERIAL_8N1 ); }
public static void Usb_Reconnect() { #if HARDWARE App.usb = new UsbSerial("2341", "8036"); App.arduino = new RemoteDevice(App.usb); App.usb.begin(115200, SerialConfig.SERIAL_8N1); App.usb.ConnectionEstablished += Usb_ConnectionEstablished; ; App.usb.ConnectionLost += Usb_ConnectionLost; App.usb.ConnectionFailed += Usb_ConnectionFailed; #endif }
public MainPage() { this.InitializeComponent(); usb = new UsbSerial("VID_2341", "PID_003D"); //I've written in my device D directly arduino = new RemoteDevice(usb); usb.ConnectionEstablished += OnConnectionEstablished; //SerialConfig.8N1 is the default config for Arduino devices over USB usb.begin(57600, SerialConfig.SERIAL_8N1); }
public MainPage() { this.InitializeComponent(); if (USE_VBB_CONNECTION) { /* * VirtualBreadboard Virtual Firmata device (www.virtualbreadboard.com) * - is the server, so you must run VBB first * - connection port 5000 as set in the VBB firmata port property * - connects using the local IP address, 127.0.0.1 * - You must enable Private Networks ( Cient & Server ) in thePackage : Capabilities manifest */ LocalSerialSocket localSocket = new LocalSerialSocket(5000); if (USE_CUSTOM_PROTOCOL) { myRemoteProtocol = new CustomRemoteProtocol(localSocket); } else { arduino = new RemoteDevice(localSocket); } arduino.DeviceReady += OnConnectionEstablished; connection = localSocket; } else { /* * I've written my bluetooth device name as a parameter to the BluetoothSerial constructor. You should change this to your previously-paired * device name if using Bluetooth. You can also use the BluetoothSerial.listAvailableDevicesAsync() function to list * available devices, but that is not covered in this sample. */ BluetoothSerial bluetooth = new BluetoothSerial("RNBT-E072"); if (USE_CUSTOM_PROTOCOL) { myRemoteProtocol = new CustomRemoteProtocol(bluetooth); } else { arduino = new RemoteDevice(bluetooth); } bluetooth.ConnectionEstablished += OnConnectionEstablished; connection = bluetooth; } //these parameters don't matter for localSocket/bluetooth connection.begin(115200, SerialConfig.SERIAL_8N1); }
public async Task CaptureReadings() { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.bluetooth = new BluetoothSerial("RNBT-9E86"); this.firmata = new UwpFirmata(); this.firmata.FirmataConnectionReady += Firmata_FirmataConnectionReady; this.firmata.StringMessageReceived += Firmata_StringMessageReceived; this.device = new RemoteDevice(firmata); this.firmata.begin(bluetooth); bluetooth.begin(9600, SerialConfig.SERIAL_8N1); }); }
public SerialOutController(RemoteDevice device, byte dataPin, byte clockPin, byte latchPin, byte numOuputs = 8) { _device = device; _dataPin = dataPin; _clockPin = clockPin; _latchPin = latchPin; _numOuputs = numOuputs; _data = new List<bool>(numOuputs); for (int i = 0; i < numOuputs; i++) _data.Add(false); device.pinMode(dataPin, PinMode.OUTPUT); }
public MainPage() { this.InitializeComponent(); usb = new UsbSerial("VID_2341", "PID_8036"); List<ConnectTheDotsSensor> sensors_one = new List<ConnectTheDotsSensor> { new ConnectTheDotsSensor("2198a348-e2f9-4438-ab23-82a3930662ac", "Temperature", "F"), }; List<ConnectTheDotsSensor> sensors_two = new List<ConnectTheDotsSensor> { new ConnectTheDotsSensor("2298a348-e2f9-4438-ab23-82a3930662ac", "light", "C"), }; List<ConnectTheDotsSensor> sensors_three = new List<ConnectTheDotsSensor> { new ConnectTheDotsSensor("2398a348-e2f9-4438-ab23-82a3930662ac", "humidity", "Lux"), }; arduino = new RemoteDevice(usb); arduino.DeviceReady += onDeviceReady; usb.begin(57600, SerialConfig.SERIAL_8N1); ctdHelper1 = new ConnectTheDotsHelper(serviceBusNamespace: "*********",//choice the serviceBusNamespace at here like "exampleIoT-ns" eventHubName: "ehdevices", keyName: "D1", key: "**********************",//copy the key which come from D1 connection of "ehdevices" displayName: "Temperature", organization: "DFRobot", location: "Shanghai", sensorList: sensors_one); ctdHelper2 = new ConnectTheDotsHelper(serviceBusNamespace: "*********",//choice the serviceBusNamespace at here like "exampleIoT-ns" eventHubName: "ehdevices", keyName: "D2", key: "**********************",//copy the key which come from D2 connection of "ehdevices" displayName: "light", organization: "DFRobot", location: "Shanghai", sensorList: sensors_two); ctdHelper3 = new ConnectTheDotsHelper(serviceBusNamespace: "*********",//choice the serviceBusNamespace at here like "exampleIoT-ns" eventHubName: "ehdevices", keyName: "D3", key: "**********************",//copy the key which come from D3 connection of "ehdevices" displayName: "humidity", organization: "DFRobot", location: "Shanghai", sensorList: sensors_three); Button_Click(null, null); }
public MainPage() { this.InitializeComponent(); arduino = App.Arduino; App.Telemetry.TrackEvent( "RemoteBlinky_Windows10_SuccessfullyConnected" ); App.Arduino.DeviceConnectionLost += Arduino_OnDeviceConnectionLost; currentState = PinState.LOW; OnButton.IsEnabled = true; OffButton.IsEnabled = true; BlinkButton.IsEnabled = true; }
private async void connect() { dt = new DispatcherTimer() { Interval = new TimeSpan(500) }; var dev = await BluetoothSerial.listAvailableDevicesAsync(); foreach (var x in dev) { System.Diagnostics.Debug.WriteLine("Found " + x.Name); } bluetoothcomm = new BluetoothSerial(dev[0]); arduino = new RemoteDevice(bluetoothcomm); bluetoothcomm.ConnectionEstablished+= Comm_ConnectionEstablished; bluetoothcomm.begin(57600, SerialConfig.SERIAL_8N1); }
UsbSerial usb; //Handle the USB connction #endregion Fields #region Constructors public MainPage() { this.InitializeComponent(); //USB VID and PID of the "Arduino Expansion Shield for Raspberry Pi B+" usb = new UsbSerial("VID_2341", "PID_8036"); //Arduino RemoteDevice Constractor via USB. arduino = new RemoteDevice(usb); //Add DeviceReady callback when connecting successfully arduino.DeviceReady += onDeviceReady; //Baudrate on 57600 and SerialConfig.8N1 is the default config for Arduino devices over USB usb.begin(57600, SerialConfig.SERIAL_8N1); }
public MainPage() { this.InitializeComponent(); /* * I've written my bluetooth device name as a parameter to the BluetoothSerial constructor. You should change this to your previously-paired * device name if using Bluetooth. You can also use the BluetoothSerial.listAvailableDevicesAsync() function to list * available devices, but that is not covered in this sample. */ bluetooth = new BluetoothSerial( "RNBT-E072" ); arduino = new RemoteDevice( bluetooth ); bluetooth.ConnectionEstablished += OnConnectionEstablished; //these parameters don't matter for bluetooth bluetooth.begin( 115200, SerialConfig.SERIAL_8N1 ); }
public MainPage() { this.InitializeComponent(); //아두이노와 연결하기 위한 준비. 하드웨어 ID를 이용한다. connection = new UsbSerial("VID_2A03", "PID_0043"); //아두이노 연결하기 arduino = new RemoteDevice(connection); //디바이스 장치 준비. 아두이노의 setup과 같은 역할을 한다. arduino.DeviceReady += Arduino_DeviceReady; //아날로그 핀 업데이트 동작이 생길 시에 진행되는 함수 설정한다. arduino.AnalogPinUpdated += Arduino_AnalogPinUpdated; //아두이노 연결 작업이 성립되었을 때의 동작을 설정한다. connection.ConnectionEstablished += Connection_ConnectionEstablished; //커넥션을 연결한다. connection.begin(57600, SerialConfig.SERIAL_8N1); }
private async void Page_Loaded(object sender, RoutedEventArgs e) { var devices = await UsbSerial.listAvailableDevicesAsync(); if (!devices.Any()) { var dialog = new MessageDialog("There is no device connected"); await dialog.ShowAsync(); return; } connection = new UsbSerial(devices.First()); arduino = new RemoteDevice(connection); arduino.DeviceReady += Setup; connection.begin(57600, SerialConfig.SERIAL_8N1); }
// Configure and open Arduino connection private void openArduinoConnection() { Debug.WriteLine("IOConnector.openArduinoConnection"); // Configure USB connection usb = new UsbSerial("VID_" + Storage.GetSetting<string>("VID"), "PID_" + Storage.GetSetting<string>("PID")); arduino = new RemoteDevice(usb); // Setup callback functions usb.ConnectionEstablished += Usb_ConnectionEstablished; usb.ConnectionFailed += Usb_ConnectionFailed; usb.ConnectionLost += Usb_ConnectionLost; arduino.DeviceReady += Arduino_DeviceReady; arduino.DeviceConnectionFailed += Arduino_DeviceConnectionFailed; arduino.DeviceConnectionLost += Arduino_DeviceConnectionLost; // Begin arduino connection usb.begin(57600, SerialConfig.SERIAL_8N1); arduinoSignalTimer.Change(10*ARDUINO_ALIVE_TIMER_PERIOD, ARDUINO_ALIVE_TIMER_PERIOD); }
private void button_Click(object sender, RoutedEventArgs e) { // Create Firmata this.mkr1000_firmata = new UwpFirmata(); //Create MKR1000 Device mkr1000 = new Microsoft.Maker.RemoteWiring.RemoteDevice(mkr1000_firmata); //Establish a network serial connection. change it to the right IP address and port wificonnection = new Microsoft.Maker.Serial.NetworkSerial(new Windows.Networking.HostName("192.168.1.42"), 3030); //Attach event handlers wificonnection.ConnectionEstablished += NetWorkSerial_ConnectionEstablished; wificonnection.ConnectionFailed += NetWorkSerial_ConnectionFailed; //Begin Firmata mkr1000_firmata.begin(wificonnection); //Begin connection wificonnection.begin(115200, Microsoft.Maker.Serial.SerialConfig.SERIAL_8N1); }
private async void Init() { try { Log.Informational("Starting application."); Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, 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); 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); 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 == 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.GetBestContentType("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); } }, 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.GetBestContentType("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); } resp.SendResponse(); } catch (Exception ex) { resp.SendResponse(ex); } }, false, this.tokenAuthentication); this.httpServer.Register("/Login", null, (req, resp) => { if (!req.HasData || req.Session == 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) => { IUser User; if (!req.Session.TryGetVariable("User", out Variable v) || (User = v.ValueObject as IUser) == null) { throw new ForbiddenException(); } string Token = this.tokenFactory.Create(new KeyValuePair <string, object>("sub", User.UserName)); resp.ContentType = JwtCodec.ContentType; resp.Write(Token); }, true, false, true); }
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(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); 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 == 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); /************************************************************************************ * 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)); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await Dialog.ShowAsync()); } }
/// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); if (instance == this) { instance = null; } if (this.chatServer != null) { this.chatServer.Dispose(); this.chatServer = null; } if (this.bobClient != null) { this.bobClient.Dispose(); this.bobClient = null; } if (this.sensorServer != null) { this.sensorServer.Dispose(); this.sensorServer = null; } if (this.xmppClient != null) { this.xmppClient.Dispose(); this.xmppClient = null; } if (this.minuteTimer != null) { this.minuteTimer.Dispose(); this.minuteTimer = null; } #if GPIO if (this.gpioPin != null) { this.gpioPin.Dispose(); this.gpioPin = null; } #else if (this.arduino != null) { this.arduino.digitalWrite(13, PinState.LOW); this.arduino.pinMode(13, PinMode.INPUT); // Onboard LED. this.arduino.pinMode(9, PinMode.INPUT); // Relay. this.arduino.Dispose(); this.arduino = null; } if (this.arduinoUsb != null) { this.arduinoUsb.end(); this.arduinoUsb.Dispose(); this.arduinoUsb = null; } #endif Log.Terminate(); deferral.Complete(); }
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(); 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); 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); 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); 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()); } }
public VirtualRelay(RemoteDevice arduino, byte pin, string name) : base(arduino, pin, name) { }
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(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(); 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). MainPage.Instance.DigitalPinUpdated(8, this.arduino.digitalRead(8)); 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); }; 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); } } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await Dialog.ShowAsync()); } }
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 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()); } }
protected override void OnAppearing() { RemoteDevice.PauseCollector(); }
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(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(); 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()); } }