-1

I'm currently writung a Win Iot app for the Raspberry Pi and I'm currently encountering some problems...

The problem I want to ask here is that I have multiple commands that I have to send out over the serial port (RS485) and I will also get a response in return. But whenever I accidently invoke the send command twice or somehow my app is doing nothing (it's doing something but I don't know what...sadly) and I press the send button again then my app crashes.

Now I want to ask if there is a method to get the current state of the serial port somehow? I wnat to know if the port is used for sending/recieving at the moment and if it is I want to block my command from being sent until the current operation is done. Or it should just give an error like "I'm busy. Try again later!".

I would really appreciate the help because I don't know how to do that :/

Daniel
  • 242
  • 2
  • 12

1 Answers1

0

https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open(v=vs.110).aspx

A serial port can only be opened once. If it's already open you, and you try to open it a second time, you should get an UnauthorizedAccessException exception, which you should handle. You could interpret this as another command operation still being in progress.

If you have a single com port instance, and are sharing that instance between the commands, you should pend on some kind of locking mechanism in order to protect the comport. E.g. take a semaphoreslim initialized to 1, and when you'd like to use the comport, wait on the semaphore. When you're done, release the semaphore. This way, only one command will use the stream simultaneously.

Lanting
  • 3,060
  • 12
  • 28
  • Ok this really did the job of blocking other commands to use the port while one is already using it. That directly solved another problem I had where I had to fire two commands directly in a row because I needed both results. So thanks for your help :) The only problem now is that my app crashes when I fire the third command...I put every command into a try/catch block but that doesnt prevent it from crashing... – Daniel Jan 30 '18 at 14:15