Да, вы можете включить заголовки C в код C ++. Это нормально, чтобы добавить это:
#ifdef __cplusplus
extern "C"
{
#endif
// C header here
#ifdef __cplusplus
}
#endif
, чтобы компилятор C ++ знал, что объявления функций и т. Д. Должны рассматриваться как C, а не C ++.
Ждите в цикле для полного ответа после того, как вы напишите первый кадр.
// Set read timeout to value recommended in the communication protocol specification
// so serial port operations don't stuck.
_port.WriteTimeout = 200;
_port.ReadTimeout = 200;
public void OnClick()
{
// Write first frame.
_port.Write(...);
// Now wait for the full response.
// Expected response length. Look for the constant value from the device communication
// protocol specification or extract from the response header (first response bytes) if
// there is any specified in the protocol.
int count = ...;
var buffer = new byte[count];
var offset = 0;
while (count > 0)
{
var readCount = _port.Read(buffer, offset, count);
offset += readCount;
count -= readCount;
}
// Now buffer contains full response or TimeoutException instance is thrown by SerialPort.
// Check response status code and write other frames.
}
Чтобы не блокировать поток пользовательского интерфейса, вам, скорее всего, все еще нужно использовать синхронный API и Task.Run()
. См. C # ожидание события и тайм-аута в последовательном порту связи обсуждение StackOverflow.
Для получения дополнительной информации проверьте Top 5 SerialPort Tips статья Кима Гамильтона.