我正在使用运行最新稳定Windows IoT核心版(v.10.0.17763.737)的RaspberryPis(v3)来检索数据并控制我的蓝牙恒温器。我在蓝牙连接的稳定性上苦苦挣扎了很长时间。几个月前,我将所有节点切换到外部加密狗(来自Microsoft兼容性列表的一个加密狗:ORICO BTA-403),这可以改善这种情况,但距离稳定还很遥远。
一段时间(从几分钟到几天不等)后,蓝牙连接将停止工作。我已经实现了一个powershell脚本来检查这种情况并触发“ devcon restart USB ”命令。这有帮助,但仅占所有故障的50%。如果不能解决问题,则必须重新启动节点。但是,这并不令人满意,因为引导时会不时冻结节点,而我的经验是过多的重新引导会缩短micro sd卡的寿命。
经过几个小时的分析,我发现蓝牙支持服务可能是问题所在。在连接崩溃之前,我可以使用powershell轻松重启蓝牙支持服务。发生问题后,这将不再可能。服务重新启动挂起,并且服务的状态表明它正在等待重新启动或类似的操作。
你们也有同样的经历吗?还是我的蓝牙连接实现太差了?我附上了该功能供您查看:
private async Task Connect()
{
try
{
int count = 0;
do
{
count++;
if (count > 10)
{
m_IsInitialized = false;
//throw new Exception("More than 10 tries have not been successfull for connecting with thermostat module. Stopping.");
}
m_IsInitialized = false;
m_Device = await BluetoothLEDevice.FromIdAsync(m_DeviceID);
if (m_Device == null)
{
throw new Exception("Device was not found.");
}
m_Characteristics = new Dictionary<ushort, GattCharacteristic>();
GattDeviceServicesResult gattServices = await m_Device.GetGattServicesAsync();
foreach (GattDeviceService service in gattServices.Services)
{
try
{
GattCharacteristicsResult characteristicsResult = await service.GetCharacteristicsAsync();
IReadOnlyList<GattCharacteristic> characteristics = characteristicsResult.Characteristics;
foreach (GattCharacteristic characteristic in characteristics)
{
try
{
m_Characteristics.Add(characteristic.AttributeHandle, characteristic);
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
if (properties.HasFlag(GattCharacteristicProperties.Notify))
{
try
{
GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Success)
{
characteristic.ValueChanged += Characteristic_ValueChanged;
m_IsInitialized = true;
//Logger.ServiceLog(string.Format("Thermostat has been initialized successfully ({0} tries).", count));
return;
}
}
catch (Exception ex4)
{
throw new Exception("4: GattCommunicationStatus: " + ex4.Message + "\nStackTrace: " + ex4.StackTrace);
}
}
}
catch (Exception ex3)
{
throw new Exception("3: GattCharacteristic: " + ex3.Message + "\nStackTrace: " + ex3.StackTrace);
}
}
}
catch (Exception ex2)
{
throw new Exception("2: GattDeviceService: " + ex2.Message + "\nStackTrace: " + ex2.StackTrace);
}
}
//Logger.ServiceLog(string.Format("Thermostat:Connect: Unsuccessful try: {0}", count));
await Task.Delay(1 * 60 * 1000);
}
while (!m_IsInitialized);
}
catch (Exception ex)
{
Logger.ServiceLog("1: Thermostat.cs Connect", ex);
}
}
如您所见,该代码充满了调试帮助,但是当连接崩溃时根本没有引发异常。我真的很期待任何帮助,因为经过数月的奋斗,我真的希望获得一个稳定的解决方案,而没有任何黑客或变通办法。
感谢您的帮助:-)