示例#1
0
        public static async Task <SensorData> PollDevice(string deviceId, int retries = 3)
        {
            BluetoothLEDevice device = null;
            var sensorData           = new SensorData {
                DeviceId = deviceId
            };

            try
            {
                device = await BluetoothLEDevice.FromIdAsync(deviceId);

                if (device == null)
                {
                    sensorData.Error = SensorData.ErrorType.CannotConnect;
                }
            }
            catch (Exception ex) when(ex.HResult == E_DEVICE_NOT_AVAILABLE)
            {
                sensorData.Error = SensorData.ErrorType.BluetoothOff;
            }

            if (device != null)
            {
                sensorData.Error = SensorData.ErrorType.CommError;
                var data = await device.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                if (data.Status == GattCommunicationStatus.Success)
                {
                    var query   = new QueryParams(data.Services, DataService, sensorData);
                    var success =
                        await Read(new QueryParams(data.Services, GenericAccess, sensorData).Read(DeviceName)) &&
                        await Read(query.Read(Firmware)) &&
                        await Write(query.Write(ModeSet, SerialNumberMode)) &&
                        await Read(query.Read(SerialNumber)) &&
                        await Write(query.Write(ModeSet, RealtimeModeOn)) &&
                        await Read(query.Read(Sensors)) &&
                        await Write(query.Write(ModeSet, RealtimeModeOff));

                    sensorData.Error = SensorData.ErrorType.None;
                }
            }
            device?.Dispose();

            if ((sensorData.Error == SensorData.ErrorType.CommError || sensorData.IsBad) && retries-- > 0)
            {
                await Task.Delay(500);

                sensorData = await PollDevice(sensorData.DeviceId, retries);
            }

            return(sensorData);
        }