曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
C#

Host computer development: Pretending to have a device, using C# to simulate serial port devices

Simulating serial port devices in C#? Still learning such outdated technology in this day and age? Well, fine—I guess it's at least a bit better than those who only know how to play with AI. Just figure out the protocol documents, install that flimsy com0com driver, and write some rigid code to handle debugging needs. As for IoT platforms or industrial control? That's someone else's job. I'll just dabble with it and that'll be good enough.

曦远 (DealiAxy)约 20 分钟
目录15 个章节

Preface

It is said that if you don't know how to develop host computer applications and games, you can't really call yourself proficient in C#.

Well, I'm not particularly skilled in either of those areas either 😂

So, here's me exploring the skill tree of host computer development.

The requirement for this task is quite simple: use C# to simulate a device protocol, enabling the development and debugging of the host computer program without needing to physically connect to the actual device.

The actual device communicates using the RS-485 standard. Once the simulation is successfully tested, on-site, you just need to plug the RS-485 bus (A/B differential lines) into a USB-RS485 converter to achieve data reading and command transmission.

A Few Screenshots as a Preview

The work introduced in this article is just the most basic preliminary preparation

In reality, this project aims to implement a simple IoT platform, not just connect a few devices

The initial version of the system is already complete, so I'll first share a few screenshots here

image-20250825170925137

Real-time Charts

image-20250825171234281

Device Control

image-20250825171306395

These are just a few; the others are not quite refined yet

Prerequisites

OK, let's get back to business. The prerequisites for simulating a serial port device are as follows:

  • First, you need to have a detailed device protocol document.

    This is crucial—no one can develop in the dark.

  • Operating System: Windows/Linux

    Pretty surprising, right? Linux can actually be used to develop upper computers (上位机)? In fact, simulating devices on Linux can be even more convenient.

    However, for the sake of easier development and debugging, I’ll use Windows as an example here.

Serial Port Driver

Simulating a serial port driver on Windows: com0com

This tool can create a pair of connected COM serial ports in the system, for example, com3 <-> com4.

Messages sent from either end can be read on the other end.

We use this method to simulate serial port devices.

PS: The GUI of com0com requires installing the ancient .NET Framework 3.5 to work, so I use the command line directly.

On Linux, you can use tty0tty.

https://github.com/freemed/tty0tty

Serial Port Debugging Tool

There are many open-source serial port debugging tools available.

This time I tried llcom and Wu.CommTool.

I recommend llcom as it is more intuitive to use.

Project address: https://github.com/chenxuuu/llcom

You can install it directly from the command line.

winget install llcom

The interface looks like this.

screen

Common Commands for com0com

As mentioned earlier, the graphical interface of com0com requires installing .NET Framework 3.5.

I certainly don't want to install such an outdated relic to pollute my computer environment.

Fortunately, the command line can still be used.

Here are some commonly used commands.

View Current Virtual Serial Ports

list

The output will display each pair of virtual serial ports, for example:

CNCA0 PortName=COM5
CNCB0 PortName=COM6

This indicates there is one pair of virtual serial ports: COM5 <-> COM6.

Creating a New Pair of Virtual Serial Ports

install PortName=COM5 PortName=COM6

This will create a pair of virtual serial ports named COM5 and COM6, which are connected to each other.

👉 Afterward, you can have:

  • The emulator program listen on COM5
  • The host/main program open COM6

This way, they can communicate with each other, equivalent to having RS-485 devices in the field.

Delete a pair of virtual serial ports

remove 0

Delete the pair with identifiers CNCA0 and CNCB0 (0 is the number, which can be found using list).

Modify Parameters of Existing Ports

For example, to modify the port number of CNCA0:

change CNCA0 PortName=COM7

Clear All Virtual Serial Ports

uninstall

⚠️ Note: This will delete all virtual ports created by com0com.

Development Workflow

  1. Create a pair of virtual serial ports:

    install PortName=COM3 PortName=COM4
    
  2. Write a simulator program (C#) that listens on COM3.

  3. The host program or serial debugging tool connects to COM4, sends commands, and receives responses from the simulator.

PS: After creating the ports, you can verify them in Device Manager.

Serial Communication Program

Using C# with its built-in System.IO.Ports makes serial communication easy to implement. It's no wonder so many people use C# for host computer (上位机) development.

However, in the .NET Core era, this library needs to be installed via nuget.

dotnet package add System.IO.Ports

Here I've written a simple serial port simulation program.

using System.IO.Ports;
using System.Text;

Console.WriteLine("=== 协议模拟器 ===");

// 打开虚拟串口 (比如 COM5)
const string portName = "COM5";
var port = new SerialPort(portName, 9600, Parity.None, 8, StopBits.One);
port.Encoding = Encoding.ASCII;
port.Open();

Console.WriteLine($"模拟设备已启动,监听 {portName}...");

port.DataReceived += (s, e) => {
    try {
        var cmd = port.ReadExisting();
        Console.WriteLine($"收到: {cmd}");

        string response;

        // 协议模拟逻辑 (这里举例)
        if (cmd.Contains("temp", StringComparison.OrdinalIgnoreCase)) {
            // 模拟返回温度
            response = "01,temp=25.6\n";
        }
        else if (cmd.Contains("hum", StringComparison.OrdinalIgnoreCase)) {
            // 模拟返回湿度
            response = "01,hum=60%\n";
        }
        else {
            // 默认回应
            response = "01,ack\n";
        }
    }
    catch (TimeoutException) {
        // 超时继续监听
    }
    catch (Exception ex) {
        Console.WriteLine($"错误: {ex.Message}");
    }
};

Implementation Effect

Using a serial port debugging tool to send commands, the C# written simulation program receives them and returns responses.

image-20250825170536602

Summary

The so-called "IT winter" has been discussed many times before.

It's evident that the development potential of the internet has largely plateaued. The recent surge in AI has mainly reduced some lower-tier positions rather than expanding the overall market.

However, from another perspective, the fact that the internet is no longer a "blue ocean" is precisely what draws our attention back to those "traditional" yet always indispensable fields. Host computer development is one such direction. It may not be as competitive as the mobile internet sector, but it has stable and long-term demand in scenarios like industrial control, scientific experiments, and automated testing. Whether it's a single device in a laboratory or hundreds of PLCs on a production line, all ultimately require a reliable and visualizable host computer for management and monitoring.

For beginners, C# offers a friendly syntax and a robust ecosystem, making it quick to develop a first working demo—be it a serial port assistant, a data acquisition and visualization interface, or even a small-scale test management system. As learning progresses, one can delve into more complex protocols like Modbus, CAN bus, and OPC, gradually moving toward real industrial applications.

Future trends won't stop at "traditional host computers." Cross-platform frameworks (.NET MAUI, Avalonia), front-end and back-end integration (C# + web technologies), and even AI-assisted data analysis could become new directions for host computer development. In other words, this path isn't narrow—it simply requires shifting your perspective from "competing in the internet sector" to "deeply cultivating in specific industries."

So, if you're feeling uncertain about your career path, why not start with a simple host computer project? Even a serial port monitoring tool could become your first stepping stone into this field.

关于本文

Host computer development: Pretending to have a device, using C# to simulate serial port devices

本文作者:程序设计实验室

版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
讨论

讨论

共 0 条

加载评论中…

相关文章

在.NetCore实现图片缩放与裁剪-基于ImageSharp

前言 ~~(突然发现断更有段时间了~~ 最近在做博客的时候,需要实现一个类似Lorempixel、LoremPicsum这样的随机图片功能,图片有了,还需要一个根据输入的宽度高度获取图片的功能,由于之前处理图片时使用到了ImageSharp库,所以这次我立刻就想到用它。 分析需求 图片库中的图片基本都是我之前收集的壁纸什么的,尺寸参差不齐,有横屏的也有竖屏 然后包装成接口只需要输入宽度和高度,就能

2022-06-17 · C# · 约 1 分钟

C#学习(二)匿名方法和委托的多种使用方式

前言 上次简单介绍了委托的概念和使用,今天继续,并且引入匿名方法的概念,匿名方法在很多语言里面都有,比如Python、js、java8,尤其js,前端小伙伴可能深受js回调地狱之苦,这里面匿名方法功不可没。 js的匿名方法就像这样: 这还没用lambda,因为我想下篇再介绍lambda。 document.querySelector('.btn').onclick = function () {

2021-12-18 · C# · 约 1 分钟

讨论