Search code examples
javascriptserial-portgoogle-chrome-appnw.js

How to setup serial port connection using NW.js and chrome.serial API?


I think I can communicate with serial ports in NW.js without such dependencies as node-serialport with precompiled binaries for different platforms.

Pure Node.js can't accomplish this task. But there's integrated Chrome API in NW.js and it has chrome.serial API, that can be used directly in JavaScript to setup serial port connection.

How to implement this?


Solution

  • List

    First of all let's fetch list of devices available to communicate with:

    chrome.serial.getDevices(function(ports) {
        for (let port of ports) {
            if (port.vendorId) {
                console.log(port);
            }
        }
    });
    

    You will get list of all ports with vendorId specified, i.e. existing devices.

    Example result:

    {
        displayName: 'Arduino Uno'
        path: 'COM7',
        productId: 67,
        vendorId: 9025
    }
    

    Property path then used for connection.


    Connect

    To connect with default settings:

    var path = 'COM7';
    
    chrome.serial.connect(path, {}, function(CI) {
        console.log('Connection ID: '+ CI.connecionId);
        console.log(CI);
    });
    

    Now you're ready!