Skip to content

Conversation

@sroebert
Copy link

The faking of the serial port allows me to use a mocked serial port using a socket, allowing me to use the newer RFX-433EMC device over WiFi. The only thing that does not work however, is the piping of the data to the parser. This is because the pipe function is not called on the mocked serial port. This PR moves that pipe function, allowing me to fully mock the serialport.

Example of the tcp serial port
class TcpSerialPort extends EventEmitter {
    constructor(host, options = {}) {
        super()
        this.host = host
        this.port = options.port || 10001
        this.socket = null
        this.isOpen = false
    }

    open(callback) {
        this.socket = net.connect(this.port, this.host, () => {
            this.isOpen = true
            this.emit('open')
            callback && callback(null)
        })
        this.emit('socket_created', this.socket)

        this.socket.on('data', (data) => {
            this.emit('data', data)
        })
        this.socket.on('close', () => {
            this.isOpen = false
            this.emit('close')
        })
        this.socket.on('error', (err) => {
            this.emit('error', err)
            callback && callback(err)
        })
    }

    write(data, callback) {
        if (!this.isOpen) {
            return callback && callback(new Error('Connection is not open'))
        }
        
        // Convert Array to Buffer if necessary
        if (!Buffer.isBuffer(data)) {
            data = Buffer.from(data)
        }

        this.socket.write(data, callback)
    }

    pipe(destination, options) {
        if (!this.isOpen || !this.socket) {
            throw new Error('Connection is not open')
        }
        return this.socket.pipe(destination, options)
    }

    close(callback) {
        if (this.socket) {
            this.socket.end(() => {
                this.isOpen = false
                callback && callback(null)
            })
        } else {
            callback && callback(new Error('Connection is not open'))
        }
    }

    flush(callback) {
        callback && callback()
    }

    set(_options, callback) {
        callback && callback(null)
    }

    get path() {
        return `${this.host}:${this.port}`
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant