I have a BLE sensor that sends data at a frequency of 100Hz and I've developed an UWP application to receive this data. I'm having a weird issue where after a couple of seconds of everything working fine, I stop receiving notifications for new data.
Now, I say it's weird because this happens when I'm using the laptop's internal Bluetooth but not when using a Bluetooth dongle. When using the dongle it works fine and never stops. Both internal Bluetooth and dongle drivers are updated to the latest version Windows can find.
As soon as the notification stops the sensor disconnects.
The sensor is based on the Nordic nRF52832 SoC.
Now a bit of information about my code:
I have a Sensor.cs class in which I handle the connection and the streaming of the data.
I'm using BluetoothLEAdvertisementWatcher in order to find the sensor.
The GattCharacteristic's are private members of the Sensor class.
I subscribe to notifications by calling:
await _gattDataSensorsCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
The application doesn't do anything fancy. Just connects to the sensor, starts the streaming and prints the data.
I've done quite a research and couldn't find anything similar. I've found posts about notifications stopping because the object was taken away by the GC, the characteristics were local variables instead of class members or calls weren't awaited.
Why does this happen?
1st edit
#Emil I'm sorry, my fault for not mentioning that as soon as the notifications stop, the sensor disconnects. I'm editing the question to mention that as well as it's something relevant. Anyway I'm trying what you mention asap.
#GrooverFromHolland That option was checked. I've tried unchecking that option on a couple of computers but sadly, unchecking it only makes the code last a few seconds longer.
#Nico Zhu - MSFT I've followed the link you posted and read the doc also went to my sensor's manual to double check if the characteristic allows Notify and it does, it does allow Read and Notify. I also do the same thing characteristic.ValueChanged += Characteristic_ValueChanged; as it's mentioned in the doc.
About the sensor disconnecting when the notifications stop/the valuechanged stops firing. I have to add that on my MainWindow, the sensor object is a member class and it isn't disposed at any moment. So it doesn't make sense that the GC takes the object away, right?
2nd edit
I've tried the code I'm using with both the laptop plugged and unplugged to a power source and it's always set to max performance. The code I'm using can be found here: link
3rd edit
Following #Emil 's recommendations I was finally able to scan the traffic. Tried to understand what the pcap file generated by USBPcap, but I simply don't understand. I've tried the issue with 2 sensors and the disconnect/notification stop pattern looks different for each sensor.
I've made a Dropbox folder containing the two pcap files: link
From what I understood, in the file "ble-FE592382586F.pcap" the interesting line No are: 12647 and 12681. It says the source is the controller and the destination is host. Is the controller the laptop's bluetooth driver?
Controller means the bluetooth chip (inside or outside the computer) and host is the main cpu. They talk with each other over usb. At packet 12681 in the first file, the disconnect reason is Connection Timeout (0x08). This means the connection was dropped unexpectedly (radio interference/bad signal?). At packet 613 in the other file, we have the same situation. A difference is that in only in the second file, there was a new attempt to reconnect the device.
Since you do not use bonding, you must make sure to re-write the client characteristic configuration descriptor upon every new connection. It doesn't seem like you do this.
I ran into similar - what I discovered was that the GattCharacteristic (the object you call WriteClientCharacteristicConfigurationDescriptorAsync on) was getting GCed - as soon as I added that to a class-wide variable (I made a Dictionary of all the characteristics I was tracking), my notifications kept coming
Related
I considered cross posting to the Super User site or similar but don't know how. As you will see this is not just a programming question.
I developed some C# code to communicate with an Onset InTemp thermometer via Bluetooth Low Energy (BLE). It works fine for a long time. I'm able to get beacons (which have the thermometer data) and also connect, get services and characteristics in case I need to get missed data or set parameters on the thermometer. However, after about 8 hours (can be as much as 24 hours) of continuously receiving beacons and connecting, getting historical data, etc., my app hangs on this line:
var gatt = await device.GetGattServicesAsync();
I put lines before and after this line and verified it's clearly hanging on this line. Again, it can be after 8 hours or 24 hours of use. It certainly chugs along just fine for quite a time. Killing and restarting the program is of no help. It hangs on the first call to:
device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
Only rebooting the PC fixes the problem. This is not surprising given the messages in the Windows Event Logs before it hangs:
The Bluetooth driver expected an HCI event with a certain size but did not receive it.
It's for this reason that I stated that this might be a SuperUser board question. No matter how badly I programmed my code :), killing the program should get BLE working again. FWIW, I did try disabling/re-enabling BLE through settings before rebooting.
I have found some links to this problem, but nothing very definitive.
I'm also working on writing a smaller, complete program to show the problem. So far, I can't get example program to fail from which I conclude that either (1) I haven't let it run long enough, or (2) I'm not fully duplicating what is going on with my full program. Perhaps I'm not putting as much pressure on the BLE drivers or I'm not listening for beacons and attempting to connect in the same ratios or with the same timing.
I should say that I see a lot of gripes about Windows implementation of the BLE Host layer and BLE drivers. Unfortunately, I'm stuck with Windows. Nordic also suggested that everything I'm reporting is a "known problem" and using their Nordic dongle will solve the problem. See for example: https://devzone.nordicsemi.com/f/nordic-q-a/65516/using-nrf52840-dongle-as-receiver-client-for-onset-thermometer.
That may well be true, but it would be a lot of work as they have libraries in C++ and Node.JS but not C#.
Any help is greatly appreciated.
Thank you!
I need to write an application that can seat in the middle of a serial port communication between an application (3rd party, no source) running on my pc and a serial device connected to it (say on COM1).
The application normally communicates with the device as soon as you plug the cable. What I need to do is break this communication by "installing" my app in the middle so I can control what data goes through.
The only way I can think of solving this is creating a a pair of virtual serial ports (COM5<->COM6) using com0com. Then I would redirect the app to use COM5 instead of COM1 (I can set this in the app options) and then write a program that will copy every byte received in COM6 (sent by the application) into COM1 (sent to the device) and viceversa.
The problem is that I need to do this without introducing any delays into the communication, otherwise the application and the device will go out of sync.
I tried creating a C# console app to do this, but it seems to wait for a pause in the stream before raising the datareceived event, effectively introducing several ms of delay (speed is 9600).
What I would like to try now is to rewrite the program (maybe using the win32 api?) in such a way that it relays each rx byte as soon as it arrives, so the device would not notice any delay.
Can I do this using win32? Is there a simpler solution you can recommend?
Thanks
Maybe not much of a complete answer for your question but I think this might be worth a try.
Depending on your needs (you did not explain them) you can try to use Termite together with com0com. You can see a quick example here.
There is also an open source clone but I think the very feature you need (forwarding) was never implemented.
In any case, Termite allows scripting, so it is quite likely to be able to meet your needs.
I am working on a C# development project which aims at controlling a flying robot thanks to a set of Optitrack cameras (infrared Motion capture system). The concept works really well, you get a position from the camera system, our application can access to these data and we can control the robot.
The problem comes, I believe, from the communication chain. We have a USB cable linking our PC to an STM32F4 based board, which acts as a bridge and simply sends everything received on USB to radio thanks to an embedded NRF module (nRF24L01+ chip). This mechanic goes both way (NRF -> USB -> PC). The board is running under C using FreeRTOS. The PC runs Windows 10.
On the PC side we use the official STM32 VCP driver 1.4 from ST. On the board firmware, we have this user-made library for VCP on STM32F4: https://stm32f4-discovery.net/2014/08/library-24-virtual-com-port-vcp-stm32f4xx/
There are no queues on the bridge board except the ones from the radio module itself and potentially the STM32 VCP driver itself. I checked, there is a circular buffer in this driver used for in and out messages. Using JSCOPE I can visualize in real time how this circular buffer behaves and I've never seen an overflow happening.
My problem comes from the fact that a delay suddenly appears.
The system works perfectly for tens of minutes (between 10 to 20 minutes) and then a delay is clearly perceptible, which makes the controller oscillate. This happens when I do a second flight.
The following have been tried:
- Restart the C# application
- Run the C# application in debug mode and stand alone mode
- Change USB cable (shorter)
- Change USB port
- Change of computer
- Reinstall the ST VCP drivers
- Lower drastically the communication frequency (the control loop)
When the problem appears, the above solutions didn't work, the delay remains completely and none of the above proved to make it more reliable.
On the C# application, I reset all communication Lists before each flight. The SerialPort port object (from System.IO) has its buffers reset as well (DiscardOutBuffer, DiscardInBuffer, BaseStream.Flush methods)
I found a "hack" to make it work, but it is not what we want as a final solution. The "hack" is to simply physically disconnect / reconnect the USB connecting the board acting as a bridge. After this manipulation, the delay disappears.
So my questions are:
What could possibly bring this delay, knowing it doesn't look to be application dependant, nor frequency related (bandwidth).
What could explain why this disappear when unplugging/plugging the bridge board ?
I know this question is about a big project and could be hard to understand from outside. Feel free to ask me for more details if needed.
Cheers,
Marc
I've spent almost 4 hours trying to figure out a solution for this issue. Basically, I am writing an application in C# using DirectShowNet that shows video from a webcam, allows you to take snapshots, and change resolution of the webcam. I have a device manager that detects when a webcam is unplugged, then replugged back in. However, I'm having difficultly recreating the graph after the device has been plugged back in.
The first thing I do is create the FilterGraph object and cast it to a IFilterGraph3. Then, I make this call:
graphBuilder.AddSourceFilterForMoniker(deviceMoniker, null, deviceName, out sourceFilter)
This call works when you initially launch the application, and even if you Dispose of the graph and create a new one. However, the only time is doesn't work is when trying to create the graph after the device is plugged back in.
On one machine (Win8 x64), I am receiving this error:
REGDB_E_CLASSNOTREG - 0x80040154 - Class not registered
On another machine (Win7 x64), I am receiving this error:
REGDB_E_IIDNOTREG - 0x80040155 - Interface not registered
I have tested both building this code as Any CPU and x86. Also, I have tested it on other machines, but independent of the OS, I still get the Interface not registered error. I have tried using both a Logitech C920 and a Microsoft LifeCam Studio. Both result in the same error. I have also tried the alternative, using the IMoniker method:
deviceMoniker.BindToObject(null, null, ref baseFilterId, out source);
Same error occurs. I feel like there may be something that is lingering after the device is disconnected that I am not cleaning up to allow the graph to grab the source (webcam filter) properly. Any ideas would be appreciated.
General HRESULT error codes can be found here: COM Error Codes (Generic)
So, basically, I just woke up one morning, got to work, and stared at the code and went, "Wait, I know why this isn't working...". It is a threading issue. The initial graphs I was creating were on a different thread than the graphs I was trying to create later. That's why it only happens when I recreate the graphs.
I was also having a problem with IVideoWindow's put_Owner method when the device is plugged in after the application has already started. In this case, the device wasn't unplugged while executing, and put_Owner would freeze/deadlock trying to that method.
Overall, I have a thread that is detecting when a device is unplugged/plugged in using DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice). So, when I go to create these graphs, they are not on the main UI thread where the other graphs were originally created. To solve this, I have my class that is handling the devices take in an Action<Action> invoker which allows you to provide a method wrapper. In this case, I pass it Control.Invoke of the WinForms form so that the calls on the device monitoring thread are wrapped by this invoker method within the UI thread. Completely solved my graph creation issues.
I am HIGHLY SURPRISED no one else ran into this before. I couldn't find anyone else mentioning threading when discussing issues related to this error. Very strange.
I have an Arduino mega communicating over Bluetooth (bluesmirf gold device) to a C# application that I wrote. The Arduino is constantly sending a serial signal of 32 characters, the first always being an "S" and the last an "E". Using putty I can confirm that this signal is being sent correctly 99% of the time.
Now I want to read this signal with my C# application, which I am doing with the following code:
public string receiveCommandHC()
{
string messageHC = "";
if (serialHC.IsOpen)
{
while (serialHC.ReadChar() != 'S')
{
}
messageHC = serialHC.ReadTo("E");
serialHC.DiscardInBuffer();
}
return messageHC;
}
serialHC is of the serial class.
Sometimes this works perfectly but other times I'm having problems, I cannot find out why it works sometimes but others not.
The problem that I seem to be having is that sometimes I get a rather large Lag in the data that I am reading from the arduino. I notice this because I am sending button states and they only change a few seconds after I actually press or release the button on the Arduino. I used the standard baud rate of the Bluetooth device, which is 115200, and was wondering if changing that to a much lower rate could yield better results? What if any advantage would that have? I do not need hight communication rates, even updating the state 4-5 times a second would be acceptable for my application.
Is it possible the lag is coming from my code? I think it may be from the while loop that is waiting for the incoming "S" but then I don't see why it should hang there since there are new signals always coming in at a high rate.
I'm using the DiscardInBuffer() because I do not care about outdated data and just want to skip over that. It is much more important that I am reading current up to date data and acting on that fresh data.
Thank you for your help!
Best regards,
Bender
Update:
Just found out a bit more information while debugging. The problem only seems to appear:
When connected over Bluetooth (over USB cable there is absolutely NO Lag)
When a second Bluetooth connection is established from the PC to another device (different COM port and different baud rate)
Does anybody have any experience running two different devices off the same Bluetooth dongle on the PC? I can manage to connect to both no problem but still having the lag issue mentioned before.
Thanks for any help
You are not really using a physical serial port here. The BlueTooth driver merely emulates one. This is common, the Windows API has a well defined set of api functions to talk to a serial port. Emulating one makes the interface to the driver simple, the vendor doesn't have to supply an interface DLL or document a complicated DeviceIoControl() protocol.
Which means for one thing that the actual communication settings don't matter. Baudrate is meaningless in this scenario, it is the BlueTooth radio signaling that sets the transfer rate. The driver will accept whatever you select but will otherwise ignore it. Handshake signals might be interpreted, it's up to the driver to implement them. Communication error reporting is very rarely implemented, BlueTooth has an error correcting protocol, unlike a real serial port.
No, the loss of data here is entirely self induced. Clearly the driver does implement DiscardInBuffer(). Which accomplishes nothing but throw away any data that the driver received. This goes wrong if your code runs a bit late or gets interrupted by a thread context switch.
Delete the DiscardInBuffer() call.