串行通訊協議的實現


1

我需要實現一個串行協議,以使用.NET(C#)與設備進行通信。此實現應為要在不同項目中使用的庫(.dll)。

我有描述協議(波特率,停止位,消息協議,命令等)的數據表,並且我知道我需要使用System.IO.Ports名稱空間中的SerialPort類。

但是我對如何構造/組織代碼有些懷疑。

以下是一些問題:

  1. 我應該擔心線程管理還是應該通過如何使用庫來管理這方面?
  2. 我可以使用字符串管理接收/發送的數據還是應該使用字節?
  3. 命令和固定內容應該使用enumsconstants或其他方式存儲嗎?

也許這些問題可能是主觀的,但是我想從比我有更多經驗的人那裡得到一些反饋。

如果有人在這個問題上有一些例子,技巧,最佳實踐等,我將非常感激。

1

Virtually all of your choices are going to be driven by the device itself and the traffic required to make use of the device. Your design will, necessarily, be driven by what the device is, how it works, how you want developers to interact with it, and how users want to use the device.

1) The question of thread management is the same everywhere--use a separate thread to keep other things from blocking if that's going to be a problem. Of course, that doesn't make the problem go away, it just changes the problem from blocking to concurrency/synchronization. But that's a different problem. All other things being equal, a separate thread for reads and writes dramatically simplifies how you decouple the IO from how you process the IO.

2) That depends entirely on what the device sends/recieves, both at the low level and at the design level.

3) Would the commands, fixed constants, or other aspects be subject to change? If the device is a work in progress, it certainly will. The most successful implimentation I've ever done was to create the IO as a read/write layer, connected to an interpreter layer that actually read the grammar from a resource, topped by an API layer for use by applications. That was for a device that was in development for a very long time and the command set changed frequently; that design made it possible to use the same code for multiple devices. Whether or not that works for you depends, again, on the device.


0
  1. It depends. If the device can send messages asynchronously, you need separate threads for sending and receiving; if it only speaks when spoken to, you should use a single thread for simplicity.

  2. It depends on the kind of information you need to send and receive, but typically you should use bytes to allow for non-ASCII control codes.

  3. Use constants of type unsigned char.