device 串口通信
device 串口通信
功能
通过 device.open({type: 'serial', ...}) 打开串口后,可以调用 read()、read_bytes()、read_text()、write(data)、flush() 和 close()。
语法
port = device.open({ type: 'serial', port: 'COM3', baud_rate: 9600, data_bits: 8, stop_bits: 1, parity: 'none', timeout: 1000 }) port.write(bytes('010300000002c40b', 'hex')) data = port.read_bytes() port.flush() port.close()
参数
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| type | String | 否 | serial | 设备类型,当前仅支持 serial。 |
| port | String | 是 | 无 | 串口名称。 |
| baud_rate | Int | 否 | 9600 | 波特率。 |
| data_bits | Int | 否 | 8 | 数据位。 |
| stop_bits | Int | 否 | 1 | 停止位。 |
| parity | String | 否 | none | 校验位。 |
| timeout | Int | 否 | 1000 | 读写超时毫秒数。 |
返回值
| 类型 | 说明 |
|---|---|
| Device | 返回串口设备句柄。 |
示例
port = device.open({type: 'serial', port: 'COM3'}) result = type(port) // 输出:Device print result
注意事项
- 配置字段统一使用 snake_case。
- read() 返回合法 UTF-8 字符串;非 UTF-8 数据返回字节数组。
- read_bytes() 始终返回 Bytes,适合 Modbus RTU 等二进制协议。
- read_text() 严格按 UTF-8 转字符串,非法 UTF-8 返回 null。
- write(data) 可写入字符串、字节数组或 Bytes。