Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding MockPortBinding.writeToPort & MockBinding.getOpenMockPort() #20

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Lucas-C
Copy link

@Lucas-C Lucas-C commented Nov 16, 2022

Usage example
Adding those methods allows to define a synchronous function that creates a pair of communicating virtual ports:

import { MockBinding } from '@serialport/binding-mock'
import { SerialPortStream } from "@serialport/stream";

const virtualPortsPair = ({ portName1 = "/dev/ttyCOM1", portName2 = "/dev/ttyCOM2", autoOpen = true }: {portName1?: string; portName2?: string; autoOpen?: boolean } = {}): SerialPortStream[] => {
  MockBinding.createPort(portName1, { echo: false, record: false });
  MockBinding.createPort(portName2, { echo: false, record: false });

  const com1 = new SerialPortStream({ binding: MockBinding, path: portName1, baudRate: 9600, autoOpen });
  const com2 = new SerialPortStream({ binding: MockBinding, path: portName2, baudRate: 9600, autoOpen });

  com1.on("open", () => {
    com2.on("open", () => {
      const mockPort1 = MockBinding.getOpenMockPort(portName1);
      const mockPort2 = MockBinding.getOpenMockPort(portName2);
      mockPort1.writeToPort = mockPort2;
      mockPort2.writeToPort = mockPort1;
    });
  });

  return [com1, com2];
};

This is a very useful pattern for unit test suites of end applications.

@reconbot
Copy link
Member

I think this is a great idea, anything to make it easier.

I'd like to suggest you see about adding it to the ports object which is roughly an analog to the hardware, vs adding it to the open port objects which is the software listening to the hardware.

There can actually be multiple software ports reading one hardware port. (I have no idea how the mocks handle that) but at the very least being able to hook together hardware ports without them being open first would be easier.

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

Successfully merging this pull request may close these issues.

2 participants