Mr-Markus / ZigbeeNet

A .NET Standard library for working with ZigBee
Eclipse Public License 1.0
131 stars 47 forks source link

Avoid while (!_closeHandler) { ... } in XBeeFrameHandler.Start() #49

Open nicolaiw opened 5 years ago

nicolaiw commented 5 years ago

This might be resolved with a TaskCompletionSource. This might be a breaking change because we have to change the Start() method to return a Task instead of void.

Here is an example of a refactored while loop with a TaskCompletionSource: https://github.com/zigbeenet/ZigbeeNet/blob/master/src/ZigBeeNet/Transaction/ZigBeeTransaction.cs#L82

andreasfedermann commented 5 years ago

Hello @nicolaiw,

I will refactor this as soon as possible. I think there are some more refactoring actions necessary. Some code is not very c# style I think. First of all I will check all existing while loops and refactor this if appropriate.

nicolaiw commented 5 years ago

This issue is not just related to Xbee

image

This is the CPU usage of the PlayGround app with a TIC2531 while waiting for input. So you are right .. removing or avoid while loops where ever we can should be our next Task :D

nicolaiw commented 5 years ago

perf

I could reduce the CPU usage (same machine) by refactor the while loop which reads from the serial port. The previous versions always checked for BytesToRead in a while loop which is not necessary and very inefficient. The refactored version waits until data available through ReadByte(). After that it reads the rest of the data. I think it could be done even more elegant. Instead of using ReadByte() to wait for data we might use the SerialPort.Read(byte[] buffer, int offset, int count) methode to read the header, parse it for the payload length and read the payload. I'm not sure but this might be Hardware/Dongle dependent (size of the header). I guess this won't be decrease the cpu usage but might be more elegant.

About 34% CPU usage still seems too high. I think there is another loop or something like that which utilizes the CPU.

@Mr-Markus @andreasfedermann Maybe you could help me to find those places in the code.

@andreasfedermann Could you please pull the latest version and try out if this version still works with your Xbee hardware ?

Best regards

nicolaiw commented 5 years ago

Found one:

https://github.com/zigbeenet/ZigbeeNet/blob/master/src/ZigBeeNet.Transport.SerialPort/ZigBeeSerialPort.cs#L157

nicolaiw commented 5 years ago

perf

Looks much better to me and that's about what I would expect when there is no data to read :)

best regards

andreasfedermann commented 5 years ago

Hi Nicolai,

sorry for being offline that long but I’ve moved. So I had less time to write some code. My aim for this week is to test your code changes.

Best regards!

Mr-Markus commented 5 years ago

Hi @andreasfedermann, good luck with your new home. I hope you will use this library for your smart home solution there :-)

Best, Markus