SerialPortSimulator
串行端口模拟器进行开发是一种便捷、安全、高效的驱动程序开发方式,无需真实设备,且更易控制测试环境,尤其适合早期开发阶段和需要进行各种测试场景的开发。 用于模拟串行端口的硬件行为,包括接收和发送数据、控制信号等。SerialPortSimulator继承于DeviceSimulator。
SerialPortSimulator
构造函数,创建一个 serialPortSimulator 实例
constructor(config, state = null)
- config: 配置参数
- state: 初始状态
SerialPortSimulator.onOpen
端口打开事件。
派生类需要端口打开后的事件处理,则重写此函数。
SerialPortSimulator.onReceiveData
接收来自驱动的数据,驱动使用SerialPort.write(data) 方法发送数据。
派生类需要重写此函数以便处理各自的协议。
serialPortSimulator.onReceiveData(data)
- data: 收到数据,类型为Buffer
SerialPortSimulator.emitData
向驱动发送数据,参数data类型为Buffer。驱动在SerialPort.on('data',(data)=>{}) 函数中接收数据。
serialPortSimulator.emitData(data)
- data: 发出数据,类型为Buffer
举例:
serialPortSimulator.emitData(Buffer.from([0xF5, 0x09, 0x00, 0x00, 0x00, 0x00, 0x09, 0xF5]))
下文以体检机身高体设备驱动为例介绍模拟器的开发
| 名称 | 描述 | 下载 | 
|---|---|---|
| device-height-weight-scale-v3.3.3 | 体检机身高体重设备驱动 | 下载 | 
simulator/device-height-weight-scale-simulator.js
const fs = require('node:fs');
const {Buffer} = require("node:buffer");
const path = require('node:path');
const config = require('../config.json');
const {SerialPortSimulator} = require('@cutos/drivers')
const {request, response} = require('../device-height-weight-scale-protocol')
class DeviceHeightWeightScaleSimulator extends SerialPortSimulator {
    constructor() {
        super(config, {height: 170, weight: 70});
        this.responsing = false;
    }
    switchOn() {
        if (this.timer) return
        this.timer = setInterval(() => {
            if (!this.responsing) {
                let weight = +this.state.weight
                this.emitData(response.generate_weight_data(weight))
            }
        }, 1000)
    }
    switchOff() {
        clearInterval(this.timer)
    }
    onReceiveData(data) {
        this.responsing = true
        if (!Buffer.compare(request.GET_HEIGHT_WEIGHT, data)) {
            let count = 0
            let timer = setInterval(() => {
                let height = +this.state.height
                let weight = +this.state.weight
                this.emitData(response.generate_height_weight_data(height, weight))
                if (++count === 3) {
                    clearInterval(timer)
                    this.responsing = false
                }
            }, 1000)
        }
        if (!Buffer.compare(request.SWITCH_ON, data)) {
            this.switchOn()
            this.emitData(response.SWITCH_ON)
            this.responsing = false
        }
        if (!Buffer.compare(request.SWITCH_OFF, data)) {
            this.switchOff()
            this.emitData(response.SWITCH_OFF)
            this.responsing = false
        }
    }
    getInfo() {
        const readme = fs.readFileSync(path.join(__dirname, 'README.md'), 'utf8')
        return {readme}
    }
}
module.exports = {
    DeviceHeightWeightScaleSimulator
}