private void TryNotifyDeviceConnected(DeviceData dev) { if (dev.State != DeviceState.Online) { return; } Task <int> task = new Task <int>(() => { var ret = ExcuteAdbShellCmd("dumpsys window displays |head -n 3", dev.Serial); log_.Debug($"OnDeviceChanged {ret}"); Regex regex = new Regex(@"init=(\d+)x(\d+)"); var m = regex.Match(ret); if (m.Success) { Size sz = new Size(); sz.Width = Convert.ToInt32(m.Groups[1].Value); sz.Height = Convert.ToInt32(m.Groups[2].Value); double rate = sz.Height * 1.0 / Display_height; var e2 = new UsbDeviceEventArgs(dev); e2.screen_size = sz; e2.display_zoom_rate = rate; OnDeviceConnected?.Invoke(this, e2); } return(1); }); task.Start(); }
public async Task UpdatePairedBluetoothDevicesAsync(CancellationToken cancellationToken = default) { await setDotNetRefAsync(cancellationToken); var module = await _moduleTask.Value; var jsDevices = await module.InvokeAsync <Device[]>("WebBluetoothFunctions.GetPairedBluetoothDevices", cancellationToken); // Remove disconnected devices for (int i = connectedDevices.Count - 1; i >= 0; i--) { if (!jsDevices.Select(d => d.Id).Contains(connectedDevices[i].Id)) { OnDeviceDisconnected?.Invoke(connectedDevices[i]); connectedDevices.RemoveAt(i); } } // Add connected Devices foreach (var newDevice in jsDevices) { if (!connectedDevices.Select(d => d.Id).Contains(newDevice.Id)) { connectedDevices.Add(newDevice); OnDeviceConnected?.Invoke(newDevice); } } }
protected void NotifyDeviceConnected() { Task.Run(() => { try { OnDeviceConnected?.Invoke(); } catch (Exception e) { Logger.GetInstance(typeof(UsbWatcher)).Error(e.ToString()); } }); }
/// <summary> /// This method opens the device (using the abstract method GetDeviceAsync). /// </summary> /// <param name="deviceInfo">Device information of the device to be opened</param> /// <returns>True if the device was successfully opened, false if the device could not be opened for well known reasons. /// An exception may be thrown if the device could not be opened for extraordinary reasons.</returns> /// <remarks>This method should be called from UI thread. (may show authorization popup)</remarks> public async Task OpenDeviceAsync(DeviceInformation deviceInfo) { _device = await GetDeviceAsync(deviceInfo); // Device could have been blocked by user or the device has already been opened by another app. if (IsDeviceConnected) { DeviceInformation = deviceInfo; if (_appSuspendEventHandler == null || _appResumeEventHandler == null) { RegisterForAppEvents(); } // User can block the device after it has been opened in the Settings charm. We can detect this by registering for the DeviceAccessInformation.AccessChanged event if (_deviceAccessEventHandler == null) { RegisterForDeviceAccessStatusChange(); } // Create and register device watcher events for the device to be opened unless we're reopening the device if (_deviceWatcher == null) { try { _deviceWatcher = DeviceInformation.CreateWatcher(DeviceSelector); } catch (UnauthorizedAccessException) { // TODO: show error message / throw error event return; } RegisterForDeviceWatcherEvents(); } if (!_watcherStarted) { // Start the device watcher after we made sure that the device is opened. StartDeviceWatcher(); } // Notify registered callback handle that the device has been opened OnDeviceConnected?.Invoke(this, DeviceInformation); } }
public async Task <Device> RequestDeviceAsync(RequestDeviceQuery query, CancellationToken cancellationToken = default) { await setDotNetRefAsync(cancellationToken); var jsonQuery = JsonConvert.SerializeObject(query, Formatting.None, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); var module = await _moduleTask.Value; var newDevice = await module.InvokeAsync <Device>("WebBluetoothFunctions.RequestDevice", cancellationToken, jsonQuery); if (newDevice != null) { connectedDevices.Add(newDevice); OnDeviceConnected?.Invoke(newDevice); } return(newDevice); }
private void OnDeviceChange(InputDevice device, InputDeviceChange inputDeviceChange) { deviceEventArgs.device = device; switch (inputDeviceChange) { case InputDeviceChange.Added: Debug.Log($"{device} was added."); OnDeviceConnected?.Invoke(this, deviceEventArgs); break; case InputDeviceChange.Removed: Debug.Log($"{device} was removed."); OnDeviceDisconnected?.Invoke(this, deviceEventArgs); break; default: break; } }
public async void Connect(string deviceId, OnDeviceConnected callback = null) { connectedDevice = await BluetoothLEDevice.FromIdAsync(deviceId); callback.Invoke(this); }
/// <summary> /// This method opens the device using the WinRT Serial API. After the device is opened, save the device /// so that it can be used across scenarios. /// /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed /// on the UI thread. /// /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes. /// </summary> /// <returns> /// True if the device was successfully opened, false if the device could not be opened for well known reasons. /// An exception may be thrown if the device could not be opened for extraordinary reasons. /// </returns> public async Task <Boolean> OpenDeviceAsync(DeviceInformation deviceInfo, string deviceSelector) { Boolean successfullyOpenedDevice = false; NotifyType notificationStatus; string notificationMessage = null; Device = await SerialDevice.FromIdAsync(deviceInfo.Id); // Device could have been blocked by user or the device has already been opened by another app. if (Device != null) { successfullyOpenedDevice = true; DeviceInformation = deviceInfo; DeviceSelector = deviceSelector; notificationStatus = NotifyType.StatusMessage; notificationMessage = "Device " + DeviceInformation.Id + " opened"; // Notify registered callback handle that the device has been opened OnDeviceConnected?.Invoke(this, DeviceInformation); if (appSuspendEventHandler == null || appResumeEventHandler == null) { RegisterForAppEvents(); } // Register for DeviceAccessInformation.AccessChanged event and react to any changes to the // user access after the device handle was opened. if (deviceAccessEventHandler == null) { RegisterForDeviceAccessStatusChange(); } // Create and register device watcher events for the device to be opened unless we're reopening the device if (deviceWatcher == null) { deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector); RegisterForDeviceWatcherEvents(); } if (!watcherStarted) { // Start the device watcher after we made sure that the device is opened. StartDeviceWatcher(); } } else { successfullyOpenedDevice = false; notificationStatus = NotifyType.ErrorMessage; var deviceAccessStatus = DeviceAccessInformation.CreateFromId(deviceInfo.Id).CurrentStatus; if (deviceAccessStatus == DeviceAccessStatus.DeniedByUser) { notificationMessage = "Access to the device was blocked by the user : "******"Access to the device was blocked by the system : " + deviceInfo.Id; } else { // Most likely the device is opened by another app, but cannot be sure notificationMessage = "Unknown error, possibly opened by another app : " + deviceInfo.Id; } } MainPage.Current.NotifyUser(notificationMessage, notificationStatus); return(successfullyOpenedDevice); }
private void _devManager_DeviceDisconnected(IDevice device) { OnDeviceConnected?.Invoke(device, false); }
private void _devManager_DeviceConnected(IDevice device) { OnDeviceConnected?.Invoke(device, true); }
private void ReceiveEnd(IAsyncResult ar) { // Retrieve state var state = (ConnectionState)ar.AsyncState; // Complete read Int32 chunkLength; try { chunkLength = state.Connection.EndReceive(ar); } catch (ObjectDisposedException) // Occurs during in-flight disposal - we need to catch it for a graceful shutdown { return; // Abort read } catch (SocketException ex) // Occurs when there is a connection error { // Report error RaiseDeviceError(state, ex.Message, false); return; // Abort receive } // If the expected number of bytes hasn't arrived yet, wait for more bytes if (state.ReceiveBufferExpected != state.ReceiveBufferUsed) { // Receive more bytes ReceiveStart(state); return; } // If header hasn't been processed yet, process it if (null == state.ReceiveReceiveMessageType) { // Yes, this could have been in the switch below, but it made for some funky reading // Check sync bytes if (state.ReceiveBuffer[0] != 0x02 || state.ReceiveBuffer[1] != 0x55) { RaiseDeviceError(state, $"Incorrect sync bytes encountered ({state.ReceiveBuffer[0]},{state.ReceiveBuffer[1]}).", true); return; } // Decode message type state.ReceiveReceiveMessageType = (ReceiveMessageTypes)state.ReceiveBuffer[2]; // Decode message length and increase the number of bytes expected var messageLength = BitConverter.ToUInt16(state.ReceiveBuffer, 3); state.ReceiveBufferExpected += messageLength; // Receive more bytes ReceiveStart(state); return; } switch (state.ReceiveReceiveMessageType.Value) { case ReceiveMessageTypes.Hello: // Device is providing basic information about it state.Device = Device.Parse(state.ReceiveBuffer, 5); state.Connection.Send(new Byte[] { 0x02, 0x55 }); // Sync bytes state.Connection.Send((Byte)TransmitMessageTypes.HelloResponse); // Message type state.Connection.Send((UInt16)8); // Message length state.Connection.Send(TelematicsTime.Encode(DateTime.UtcNow)); // Time state.Connection.Send((UInt32)0); // Flags TODO: how to tell device to redirect to OEM? OnDeviceConnected?.Invoke(this, new OnDeviceConnectedArgs() { RemoteAddressString = state.RemoteAddressString, Device = state.Device }); break; case ReceiveMessageTypes.Records: // Device is providing records // It seems that MESSAGE contains multiple RECORDS // which contain multiple FIELDS // which contains multiple things which I'm going to call ATTRIBUTES // Attributes are the actual data. // // In summary: MESSAGE => RECORDS => FIELDS => ATTRIBUTES var position = 5; var records = new List <Record>(); while (position < state.ReceiveBufferExpected) { records.Add(Record.Parse(state.ReceiveBuffer, ref position)); } OnRecordsReceived?.Invoke(this, new OnRecordsReceivedArgs() { RemoteAddressString = state.RemoteAddressString, Device = state.Device, Records = records }); break; case ReceiveMessageTypes.CommitRequest: // Device asking us to confirm that we've successfully received and stored records // Send confirmation // TODO: When would we not confirm a commit? state.Connection.Send(new Byte[] { 0x02, 0x55 }); // Sync bytes state.Connection.Send((Byte)TransmitMessageTypes.CommitResponse); // Message type state.Connection.Send((UInt16)1); // Message length state.Connection.Send((Byte)1); // Success break; case ReceiveMessageTypes.VersionData: // Device providing version information (no idea what this is for!!) RaiseDeviceError(state, $"Version information received and discarded.", false); // TODO: do something with the information break; case ReceiveMessageTypes.TimeRequest: // Device asking for the current time state.Connection.Send(new Byte[] { 0x02, 0x55 }); // Sync bytes state.Connection.Send((Byte)TransmitMessageTypes.TimeResponse); // Message type state.Connection.Send((UInt16)4); // Message length state.Connection.Send(TelematicsTime.Encode(DateTime.UtcNow)); // Current time break; case ReceiveMessageTypes.AsyncMessageResponse: // Device is giving responses to async messages, which is not currently implemented, so should not be recieved RaiseDeviceError(state, $"Message async responses received and discarded.", false); // TODO: do something with the information break; default: RaiseDeviceError(state, $"Unsupported message type received ({state.ReceiveReceiveMessageType.Value}). Message discarded.", false); break; } // Receive more ResetState(state); ReceiveStart(state); }
/// <summary> /// This method opens the device using the WinRT Serial API. After the device is opened, save the device /// so that it can be used across scenarios. /// /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed /// on the UI thread. /// /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes. /// </summary> /// <returns> /// True if the device was successfully opened, false if the device could not be opened for well known reasons. /// An exception may be thrown if the device could not be opened for extraordinary reasons. /// </returns> public async Task <bool> OpenDeviceAsync(DeviceInformation deviceInfo, string deviceSelector) { bool successfullyOpenedDevice = false; NotifyType notificationStatus; string notificationMessage = null; Device = await SerialDevice.FromIdAsync(deviceInfo.Id); // Device could have been blocked by user or the device has already been opened by another app. if (Device != null) { successfullyOpenedDevice = true; DeviceInformation = deviceInfo; DeviceSelector = deviceSelector; // necessary for the MALT read/write to work try { Device.BaudRate = 9600; Device.DataBits = 8; Device.Handshake = SerialHandshake.None; } catch { } // should be set by default try { Device.StopBits = SerialStopBitCount.One; Device.Parity = SerialParity.None; } catch { } notificationStatus = NotifyType.StatusMessage; notificationMessage = "Device " + DeviceInformation.Id + " opened"; // Notify registered callback handle that the device has been opened OnDeviceConnected?.Invoke(this, DeviceInformation); if (appSuspendEventHandler == null || appResumeEventHandler == null) { RegisterForAppEvents(); } // Create and register device watcher events for the device to be opened unless we're reopening the device if (deviceWatcher == null) { deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector); RegisterForDeviceWatcherEvents(); } if (!watcherStarted) { // Start the device watcher after we made sure that the device is opened. StartDeviceWatcher(); } } else { successfullyOpenedDevice = false; notificationStatus = NotifyType.ErrorMessage; var deviceAccessStatus = DeviceAccessInformation.CreateFromId(deviceInfo.Id).CurrentStatus; if (deviceAccessStatus == DeviceAccessStatus.DeniedByUser) { notificationMessage = "Access to the device was blocked by the user : "******"Access to the device was blocked by the system : " + deviceInfo.Id; } else { // Most likely the device is opened by another app, but cannot be sure notificationMessage = "Unknown error, possibly opened by another app : " + deviceInfo.Id; } } rootPage.NotifyUser(notificationMessage, notificationStatus); return(successfullyOpenedDevice); }
/// <summary> /// Starts this instance. /// </summary> /// <param name="scanMode">The scan mode.</param> /// <returns><c>true</c> if successfully, <c>false</c> otherwise.</returns> public bool LidarStart(EScanMode scanMode = EScanMode.Boost) { try { if (IsRunning || IsDisposed) { return(false); } _ScanNumber = 0; // Load driver if (!NativeModuleManager.InitializeNativeModule(NativeModuleNames.NativeRpLidar)) { Console.WriteLine("Can not load lidar native driver library."); return(false); } // Initialize driver if (RpLidarInterface.LidarInitializeDriver() != 0) { Console.WriteLine("Can not initialize lidar driver."); } // Connect device if (RpLidarInterface.LidarConnect(_SerialPort, _SerialPortSpeed) != 0) { Console.WriteLine($"Can not connect to serial port \"{_SerialPort}:{_SerialPortSpeed}\"."); } // Get device info _DeviceInfo = new rplidar_response_device_info_t { serialNum = new byte[16] }; if (RpLidarInterface.LidarGetDeviceInfo(ref _DeviceInfo) != 0) { Console.WriteLine("Can not get device info from device."); } // Get device health info _DeviceHealthInfo = new rplidar_response_device_health_t(); if (RpLidarInterface.LidarGetHealth(ref _DeviceHealthInfo) != 0) { Console.WriteLine($"Can not get device health info from device."); } // Reset device on error state if (_DeviceHealthInfo.Status == (byte)EDeviceStatus.RPLIDAR_STATUS_ERROR) { Console.WriteLine($@"Reset device due to error device health status: {_DeviceHealthInfo.Status}"); RpLidarInterface.LidarReset(); } // Start spinning motor if (RpLidarInterface.LidarStartMotor() != 0) { Console.WriteLine($"Can not start device motor."); } // Start scanning _RpLidarScanMode = new RplidarScanMode { scan_mode = new char[64] }; if (RpLidarInterface.LidarStartScan(false, (ushort)scanMode, ref _RpLidarScanMode) != 0) { Console.WriteLine($"Can not start scan mode."); } // Initialize task _TokenSource = new CancellationTokenSource(); _Token = _TokenSource.Token; _Task = Task.Factory.StartNew(() => LidarTaskDoWork(_Token), _Token); if (RpLidarInterface.LidarIsConnected() == 1) { return(true); } else { return(false); } } finally { if (RpLidarInterface.LidarIsConnected() == 1) { OnDeviceConnected?.Invoke(this, EventArgs.Empty); } } }