Search code examples
javascriptserial-portprogressive-web-appscom-portweb-serial-api

auto connection to serial port device with web serial API


what should I do to connect the serial device automatically with the filter device when it plug-in into the computer. I am using web serial API to connect serial devices.


Solution

  • To open a serial port, first access a SerialPort object. For this, you can either prompt the user to select a single serial port by calling navigator.serial.requestPort() in response to a user gesture such as touch or mouse click, or pick one from navigator.serial.getPorts() which returns a list of serial ports the website has been granted access to.

    document.querySelector('button').addEventListener('click', async () => {
      // Prompt user to select any serial port.
      const port = await navigator.serial.requestPort();
    });
    
    // Get all serial ports the user has previously granted the website access to.
    const ports = await navigator.serial.getPorts();
    

    If a serial port is provided by a USB device then that device may be connected or disconnected from the system. When the website has been granted permission to access a serial port, it should monitor the connect and disconnect events.

    navigator.serial.addEventListener("connect", (event) => {
      const port = event.target;
      // TODO: Automatically open port or warn user a port is available.
    });
    

    Once you have a SerialPort object, calling port.open() with the desired baud rate will open the serial port.

    // Wait for the serial port to open.
    await port.open({ baudRate: 9600 });
    

    Source: https://web.dev/serial/