gpt4 book ai didi

c# - 串口通信设计模式

转载 作者:行者123 更新时间:2023-11-30 18:43:06 25 4
gpt4 key购买 nike

我目前的任务是开发与步进电机 Controller 通信的软件模块。该项目是用 C# 编写的,我有一个 C++ dll 来与 Controller 通信。通信通过串行端口运行。我打算通过 DllImport 导入必要的方法,用 C# 编写整篇文章。关键方法看起来像:

ComSendReceive(pHandle, bufferIn,sizeBufferIn,bufferOut,ref bufferOut)

有几种类型的消息:

  • 您发送消息并期待确认(每条消息都不同,有时没问题,有时已完成等。
  • 您发送消息和接收消息 - 您可以接收错误或数据(例如 GET_CONTROLLER_ID)
  • 其他几种类型

当然我需要控制通信超时。

我的问题是:是否有任何“设计模式”可用于此类问题?我敢肯定这是一个很常见的问题,许多开发人员已经解决了。

贡献一点——我在上一份工作中处理过类似的问题,我是这样解决的:

我有一个与 Com 端口通信的类和一个带有一堆重载构造函数的 AT_message 类:

class AT_Message
{
public bool DoResponseCheck;
public string ExpectedResponse;
public AT_COMMAND command;
public string data;
public bool AddCarriageReturn;
...

//Plenty of ctors
}

class UnfriendlyInterface
{
Response SendMessage(AT_Message msg)
{
//Communicates directly with C++ dll, send message, check timeouts etc....
}
}

我有一个主应用程序与之通信的类,它有像

这样的人性化方法
class FriendlyInterface
{
bool AutodetectPortAndOpenComm();

Result AnalyzeSignal(byte[] buffer)
{
Response response = UnfriendlyInterface.SendMessage(new Message(AT_Command.PrepareForSignal, (doResponseCheck)true, ExpectedResponse.Ok,Timeout.short);
Response response = UnfriendlyInterface.SendMessage(new Message(buffer,(doResponseCheck)false,Timeout.long);

//.... Other steps
}

//... other methods

}

由于上次我真的很着急,所以我实现了我想到的第一个解决方案。但是有没有办法做得更好呢?现在我要与之通信的设备比以前的设备更复杂,所以如果有更好的方法,我想那样做。

最佳答案

这看起来像是教科书外观模式。所有这些的答案是封装您的变体。例如,尝试为给出确认的命令创建一个通用接口(interface),并编写客户端代码来使用该接口(interface)。然后具体类型可以决定如何将各种确认解释为统一信号(Ok = Complete = Good,或其他)

这里有一篇关于 facade pattern 的好文章.另见 wikipedia article .

关于c# - 串口通信设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4919452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com