Example #1
1
function setupSerial(){

  serialport.list(function (error, ports) {
    if(!error){
      ports.forEach(function(port) {
        if(port.comName.indexOf('Blue')<0){
          myPort = new SerialPort(port.comName, { 
            baudRate: 9600,
            open: false,
            parser: serialport.parsers.readline("\r\n")
          });
          createHandlers();
        }
      });
    }
    if(!myPort){
      myPort = new SerialPort('/dev/ttyAMA0', { 
        baudRate: 9600,
        open: false,
        parser: serialport.parsers.readline("\r\n")
      });
      createHandlers();
      console.log('NO ARDUINO PORT FOUND');
    }
  });
}
Example #2
1
  async connect (serialPort) {

    serialPort = await getPort(serialPort)

    // The default is options.port
    serialPort = serialPort || this.port || this.options.port || null
    // If it's connected or connecting, return last promise
    if(this._connect){
      return await this._connect
    }

    // Must know which serialport to connect to
    if (!serialPort || _.isEmpty(serialPort)){
      throw new Error('No Serial port name or pattern provided')
    }

    // If serialPort is a string, use it as a object {comName: String}
    if(_.isString(serialPort)){
      serialPort = {comName: serialPort}
    }else{
      serialPort = serialPort
    }

    //Try to find port
    let portList = await SerialPort.list()
    let portProp = _.find(portList, serialPort)

    //Reject promise if port not found
    if (!portProp){
      throw new Error('Port not found: ' + JSON.stringify(serialPort))
    }

    this._connect = new Promise(async(resolve, reject) => {
      try{
        //Open Serial Port
        this.port = new SerialPort(portProp.comName, this.options)

        //Bufferize Line and use as dataReceived
        let lineBuffer = new Readline({delimiter: '\n'})

        //Proxy all data received by serial port to the line Buffer
        this.port.pipe(lineBuffer)

        //Once there's data in line buffer, pass to dataReceived
        lineBuffer.on('data', (data) => {
          this.dataReceived(data)
        })
        //Every time it opens/closes, reset the current queue
        this.port.on('open', () => this.resetQueue())
        this.port.on('close', () => this.resetQueue())
        resolve()
      } catch (e) {
        reject(e)
      }
    })

    await this._connect
  }
Example #3
0
 (resolve, reject) => {
     serialport.list(
         (err, ports) => {
             if (err) reject(err);
             resolve(ports.map((port) => port.comName));
         });
 });
Example #4
0
exports.getAllPorts = function(onlyOpened, callback) {
  serialPort.list(function(err, ports) {
    if (err) {
      var error = new AtomError(3, err);

      ports = [];
    }

    if (onlyOpened) {
      var openedPorts = [];
      for (var i=0; i < ports.length; i++) {
        var currentPort = ports[i];
        for (var j=0; j < global.app.serialPorts.length; j++) {
          var openedPort = global.app.serialPorts[j];
          if (currentPort.comName == openedPort.path && openedPort.isOpen()) {
            openedPorts.push(currentPort);
          }
        }
      }
      callback(error, openedPorts);
    }
    else {
      callback(error, ports);
    }
  });
}
var scan = function() {
  serialport.list(function(err, info) {
    var i, j;

    if (!!err) return logger2.error('insteon-9761', { diagnostic: err.message });

    for (i = 0; i < info.length; i++) {
      for (j = fingerprints.length - 1; j !== -1; j--) {
        if ((info[i].pnpId.indexOf(fingerprints[j].pnpId) === 0)
              || ((     fingerprints[j].manufacturer === info[i].manufacturer)
                    && (fingerprints[j].vendorId     === parseInt(info[i].vendorId, 16))
                    && (fingerprints[j].productId    === parseInt(info[i].productId, 16)))) {
          info[i].vendor = fingerprints[j].vendor;
          info[i].modelName = fingerprints[j].modelName;
          info[i].description = fingerprints[j].description;
          if (!info[i].vendorId)     info[i].vendorId     = fingerprints[j].vendorId;
          if (!info[i].productId)    info[i].productId    = fingerprints[j].productId;
          if (!info[i].manufacturer) info[i].manufacturer = fingerprints[j].manufacturer;
          if (!info[i].serialNumber) info[i].serialNumber = info[i].pnpId.substr(fingerprints[j].pnpId.length).split('-')[0];
          scan1(info[i]);
        }
      }
    }
  });

  setTimeout(scan, 30 * 1000);
};
Example #6
0
var detectPLMPort = exports.detectPLMPort = function(callback){
  serialPort.list(function(err,ports){
    console.log(ports);
    if(err){
      if(callback){
        callback(err);
      }
      return;
    } else {
      for(var pIndex in ports){
        //scan over all available ports for PLM identifier
        var port = ports[pIndex];
        if((port.pnpId && port.pnpId.indexOf("usb-FTDI_FT232R_USB_UART_A501LDGJ") > -1)
           || (port.manufacturer === 'FTDI' && port.serialNumber === 'A501LDGJ')){
          //found the PLM
          //console.log("Found " + port.pnpId + " on port " + port.comName);
          if(callback){
            callback( null, port.comName);
          }
          return;
        }
      }

      callback(new Error("No PLM found"));
      return;
    }
  });
};
function main(params) {
    var currentPort = undefined;
    console.log("Available ports:");
    serialport.list(function (err, ports) {
        ports.forEach(function (port) {
            ports += port.comName + "\n";
            console.log(port.comName);
            if (port.comName === params[2]) {
                currentPort = port;
            }
        });
        console.log("Port " + currentPort.comName + " selected");
        var activeSerialPort = new serialport.SerialPort(currentPort.comName, {
            baudrate: 9600
        });
        activeSerialPort.on("open", function () {
            var comInServer = new ComInServer();
            comInServer.setSerialPort(activeSerialPort);
            comInServer.setCallback(function (data) {
                console.log(data.toString());
                currentLog += data.toString();
            });
        });
    });
}
Example #8
0
function checkBoard(cb) {
  var last = false;
  serialPort.list(function (err, ports) {
    // check ports on computer
    ports.forEach(function(port, i, stop) {
      if (i == ports.length - 1){
        last = true;
      }
      COM = port.comName;
      // check to see if arduino plugged in and open connection
      if ((COM.search('cu.usbmodem') != -1) ||
          (COM.search('cu.wchusbserial') != -1) ||
          (COM.search('tty.usbmodem') != -1) || 
          (COM.search('cu.usbserial') != -1) ||
          (COM.search('COM') != -1)) {
        cb(true);
      } else {
        if (last === true) {
          connection.close(function (error) {
            cb(false);
          });
        }
      }
    });
  });
}
Example #9
0
    start: function (port) {
        SP.list(function (err, ports) {
            if (err) throw new Error(err);

            console.log(ports);
        });

        this.sp = new SP(port, {
            baudRate: 9600,
            dataBits: 8,
            parity: 'none',
            stopBits: 1,
            flowControl: false,
            parser: SP.parsers.readline('\r\n')
            // parser: SP.parsers.raw
        });

        this.sp.on('open', function () {
            console.log('serial connection established with', port);
        })

        this.sp.on('error', function (err) {
            console.log(err);
        })

        this.sp.on('disconnect', function (err) {
            console.log('serial connection was disconnected', err);
        });

        this.sp.on('close', function () {
            console.log('serial connection was closed.');
        });
    },
Example #10
0
var guessSerialPort = function(wantedPortName, callback) {
    serialport.list(function (err, ports) {
        if (err) {
            callback(err);
            return;
        } else {
            if (ports.length === 0) {
                callback("No serial port found", undefined, undefined);
                return;
            }

            var p = undefined;
            ports.forEach(function(port) {
                if (wantedPortName && wantedPortName !== "auto"
                        && wantedPortName === port.comName) {
                    p = port.comName;
                }
            });
            if (p) {
                callback(err, p, ports);
                return;
            } else if (wantedPortName && wantedPortName !== "auto") {
                console.log("WARN: unable to find serial port: ", wantedPortName);
            }

            var preferred = ports.filter(isLikelyArduinoSerial)
            p = preferred.length > 0 ? preferred[0].comName : ports[0].comName;
            callback(err, p, ports);
            return;
        }
    });
}
Example #11
0
            socket.on('list', () => {
                log.debug('[cncserver] socket.list():', { id: socket.id });

                serialport.list((err, ports) => {
                    if (err) {
                        log.error(err);
                        return;
                    }

                    ports = ports.concat(_.get(settings, 'cnc.ports') || []);

                    let portsInUse = _(this.controllers)
                        .filter((controller) => {
                            return controller && controller.isOpen();
                        })
                        .map((controller) => {
                            return controller.port;
                        })
                        .value();
                    
                    ports = _.map(ports, (port) => {
                        return {
                            port: port.comName,
                            manufacturer: port.manufacturer,
                            inuse: _.includes(portsInUse, port.comName) ? true : false
                        };
                    });

                    socket.emit('serialport:list', ports);
                });
            });
Example #12
0
    findCores: function (callback) {
        var cores = [];
        SerialPortLib.list(function (err, ports) {

            //grab anything that self-reports as a core
            for (var i = 0; i < ports.length; i++) {
                var port = ports[i];

                //not trying to be secure here, just trying to be helpful.
                if ((port.manufacturer && port.manufacturer.indexOf("Spark") >= 0) ||
                    (port.pnpId && port.pnpId.indexOf("Spark_Core") >= 0) ||
                     port.pnpId && port.pnpId.indexOf("VID_1D50") >= 0) {
                    cores.push(port);
                }
            }

            //if I didn't find anything, grab any 'ttyACM's
            if (cores.length == 0) {
                for (var i = 0; i < ports.length; i++) {
                    var port = ports[i];

                    //if it doesn't have a manufacturer or pnpId set, but it's a ttyACM port, then lets grab it.
                    if (port.comName.indexOf('/dev/ttyACM') == 0) {
                        cores.push(port);
                    }
                    else if (port.comName.indexOf('/dev/cuaU') == 0) {
                        cores.push(port);
                    }
                }
            }

            callback(cores);
        });
    },
Example #13
0
RED.httpAdmin.get("/serialports",function(req,res) {
    serialp.list(function (err, ports) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write(JSON.stringify(ports));
        res.end();
    });
});
Example #14
0
SpheroCollection.prototype.connect = function() {
  var self = this;

  var setupConnection = function(dev){
    var b = new Sphero(dev);
    b.on("open", function(err, ret) {
      self.balls.push(b);
      self.emit('connected', b);
    });
  };

  if (process.platform === 'win32') {
    serialport.list(function (err, ports) {
      ports.forEach(function(port) {
        setupConnection(port.comName);
      });
    });
  }else{
    fs.readdir('/dev', function onDevicesListed(err, devs) {
      if (err) {
        self.emit("error", err);
      }else {
        devs.filter(function looksLikeSphero(dev) {
          return /cu.*sphero/i.test(dev);
        }).map(function addDirectory(dev) {
          dev = path.join('/dev', dev);
          setupConnection(dev);
        });
      }
    });
  }
};
Example #15
0
SerialDeviceLoader.prototype.lookup = function(callback) {
  if (this.useGlobal) {
    this.globalSerialDeviceLoader.lookup(callback);
  } else {
    var self = this;
    sp.list(function(err, ports) {
      if (err) { return callback(err); }

      var resPorts = self.filter(ports);

      var devices = _.map(resPorts, function(p) {
        var found = _.find(self.oldDevices, function(dev) {
          return dev.get('portName') === p.comName;
        });
        if (found) {
          return found;
        } else {
          var newDev = new s.Device(p.comName);
          newDev.set(p);
          return newDev;
        }
      }) || [];

      callback(null, devices);
    });
  }
};
Example #16
0
/**
 * open serial port.  if you pass a port name, it will
 * use that port.  if not, it will attempt to locate the
 * board via the VID/PID or the bus description (the call
 * that serialport uses on different platforms returns
 * different information).
 *
 * @param use_port - override location, and just use the named port
 */
function connect( use_port )
{
	if( use_port )
	{
		connectport( use_port );
	}
	else
	{
		SerialPort.list(function (err, ports) {
			var pname = null;
			for( var i in ports )
			{
				if( ports[i].pnpId && 
					( ports[i].pnpId.match( /usb\-nfc/i )
					|| ports[i].pnpId.match( /VID_04D8\&PID_000A/i )))
				{
					pname = ports[i].comName;
				}
			}
			if (null == pname)
			{
				events.emit('comms-event', 
					{ message: "Port not found", type: COMMS_EVENT_TYPE.CONNECT_EVENT });
			}
			else connectport(pname);

		});
	}
};
Example #17
0
exports.scan_usb = function(logger2, tag, fingerprints, callback) {
  serialport.list(function(err, info) {
    var i, j;

    var f = function(comName) {
      return function(err) { if (!!err) delete(scanning[comName]); };
    };

    if (!!err) return logger2.error(tag, { diagnostic: err.message });

    for (i = 0; i < info.length; i++) {
      for (j = fingerprints.length - 1; j !== -1; j--) {
        if ((info[i].pnpId.indexOf(fingerprints[j].pnpId) === 0)
              || ((     fingerprints[j].manufacturer === info[i].manufacturer)
                    && (fingerprints[j].vendorId     === parseInt(info[i].vendorId, 16))
                    && (fingerprints[j].productId    === parseInt(info[i].productId, 16)))) {
          info[i].vendor = fingerprints[j].vendor;
          info[i].modelName = fingerprints[j].modelName;
          info[i].description = fingerprints[j].description;
          info[i].deviceType = fingerprints[j].deviceType;
          if (!info[i].vendorId)     info[i].vendorId     = fingerprints[j].vendorId;
          if (!info[i].productId)    info[i].productId    = fingerprints[j].productId;
          if (!info[i].manufacturer) info[i].manufacturer = fingerprints[j].manufacturer;
          if (!info[i].serialNumber) info[i].serialNumber = info[i].pnpId.substr(fingerprints[j].pnpId.length).split('-')[0];

          if (!!scanning[info[i].comName]) continue;
          scanning[info[i].comName] = true;

          callback(info[i], f(info[i].comName));
        }
      }
    }
  });
};
  lookup: function(callback) {
    sp.list(function(err, ports) {
      if (err && callback) { return callback(err); }

      async.forEach(subscribers, function(s, callback) {
        if (s) {
          var resPorts = s.filter(ports);

          var devices = _.map(resPorts, function(p) {
            var found = _.find(s.oldDevices, function(dev) {
              return dev.get('portName') === p.comName;
            });
            if (found) {
              return found;
            } else {
              var newDev = new s.Device(p.comName);
              newDev.set(p);
              return newDev;
            }
          }) || [];

          s.newDevices = devices;
        }

        callback(null);
      }, function(err) {
        if (callback) { return callback(err); }
      });
    });
  },
Example #19
0
  detectRadio(resolve, reject) {
    log.warn('No radio device supplied, attempting to detect');

    serialport.list((err, ports) => {
      if (err) {
        reject(err);
        return;
      }

      if (os.type() === 'Darwin') {
        _.remove(ports, port => {
          return port.comName === '/dev/cu.Bluetooth-Modem' ||
                 port.comName === '/dev/cu.Bluetooth-Incoming-Port';
        });
      }

      if (ports.length === 0) {
        reject('No detected serial ports');
        return;
      }

      ports = _.pluck(ports, 'comName');

      if (ports.length > 1) {
        log.warn('Multiple serial ports found, choosing first');
      }

      log.info('Detected serial port: %s', ports[0]);
      resolve(ports[0]);
    });
  }
Example #20
0
Connection.prototype._listPorts = function(callback) {
  var foundPorts = [];

  // list all available ports
  Serialport.list(function(err, ports) {
    if (err) { return callback(err); }

    // iterate through ports
    for (var i = 0; i < ports.length; i += 1) {
      var pid;

      // are we on windows or unix?
      if (ports[i].productId) {
        pid = ports[i].productId;
      } else if (ports[i].pnpId) {
        try {
          pid = '0x' + /PID_\d*/.exec(ports[i].pnpId)[0].substr(4);
        } catch (err) {
          pid = '';
        }
      } else {
        pid = '';
      }

      ports[i]._standardPid = pid;
      foundPorts.push(ports[i]);
    }

    return callback(null, foundPorts);
  });
};
        function waiting_for_serial(){
            //console.log("Waiting for "+ s_port);
            serialport_module.list(function (err, ports) {
                ports.forEach(function(port) {
                    if(port.comName == s_port){
                        clearInterval(intervalId);
                        serial.open(function () {
                            serial.on('close', function (err) {
                                console.log("Serial port ["+s_port+"] was closed");

                                //handle board disconnection
                                if(elementsList){
                                    for(var i in elementsList){
                                        removeFunction(i, elementsList[i].element.sa);
                                    }
                                    elementsList = [];
                                }
                                //start listening for incoming boards
                                intervalId = setInterval(waiting_for_serial,2000);
                            });

                            serial.on('error', function (err) {
                                if(err.path == s_port){
                                    //console.log("Serial port ["+port+"] is not ready. Err code : "+err.code);
                                    setTimeout(init_serial,2000);
                                }
                            });
                            start_serial();
                        });
                      }
                });
            });       
        }
Example #22
0
	Detect.prototype.searchArduinos = function() {
		// On check tous les ports disponibles
		serialPort.list(function (err, ports) {
			var nb_found = 0;
			for(var i in ports) {
				sp[i] = new SerialPort(ports[i].comName, { baudrate: 57600 });
				sp[i].on('open', function (i) {
					sp[i].write('O\n');
				}.bind(this, i));

				sp[i].on("data", function (i, data) {
					data = data.toString();
					console.log(ports[i].comName, data);
					if (data == 'O' && !this.devicesFound.others){ // Stepper
						this.devicesFound.others = ports[i].comName;
						clearTimeout(timeout);
						this.sendSP();
					}
					sp[i].close();
				}.bind(this, i));

				sp[i].on("error", function() {}); // Node JS Error if it doesn't exist (and if an "error" event is sent)
			}
		}.bind(this));

		// On check tous les ports qui ne sont pas enregistrés
		timeout = setTimeout(function(){this.sendSP(); }.bind(this), 3000);
	};
var scan = function() {
  serialport.list(function(err, info) {
    var configuration, fingerprint, i, j;

    if (!!err) return logger2.error('insteon-automategreen', { diagnostic: err.message });

    configuration = utility.configuration.serialPorts && utility.configuration.serialPorts['insteon-automategreen'];
    if (!configuration) return;
    
    for (i = 0; i < info.length; i++) {
      fingerprint = configuration[info[i].comName];
      if (!fingerprint) continue;

      info[i].vendor = fingerprint.vendor;
      info[i].modelName = fingerprint.modelName;
      info[i].description = fingerprint.description;
      if (!info[i].vendorId)     info[i].vendorId     = fingerprint.vendorId;
      if (!info[i].productId)    info[i].productId    = fingerprint.productId;
      if (!info[i].manufacturer) info[i].manufacturer = fingerprint.manufacturer;
      if (!info[i].serialNumber) info[i].serialNumber = fingerprint.serialNumber;
      if (!info[i].serialNumber) {
        j = info[i].comName.lastIndexOf('-');
        if (j !== -1) info[i].serialNumber = info[i].comName.substr(j + 1);
      }
      scan1(info[i]);
    }
  });

  setTimeout(scan, 30 * 1000);
};
Example #24
0
            socket.on('list', () => {
                log.debug(`socket.list(): id=${socket.id}`);

                SerialPort.list()
                    .then(ports => {
                        ports = ports.concat(ensureArray(config.get('ports', [])));

                        const controllers = store.get('controllers', {});
                        const portsInUse = Object.keys(controllers)
                            .filter(port => {
                                const controller = controllers[port];
                                return controller && controller.isOpen();
                            });

                        ports = ports.map(port => {
                            return {
                                port: port.comName,
                                manufacturer: port.manufacturer,
                                inuse: portsInUse.indexOf(port.comName) >= 0
                            };
                        });

                        socket.emit('serialport:list', ports);
                    })
                    .catch(err => {
                        log.error(err);
                    });
            });
Example #25
0
$('#port-sync-button').on('click', (v) => {
  SerialPort.list((err, ports) => {
    $('#port-selector').empty();
    ports.forEach((port) => {
      $('#port-selector').append("<option>" + port.comName + "</option>");
    });
  });
});
Example #26
0
 function scan (open) {
   Serial.list(function (err, list) {
     var spec = list.pop( );
     log.info("OPENING", spec);
     var serial = new Serial.SerialPort(spec.comName, {bufferSize: 64});
     serial.open(open.bind(serial));
   });
 }
Example #27
0
	return p(function (res, rej) {
		serialPort.list(function (err, ports) {
			if (resolved(err, rej)) {
				call(callback, ports);
				res(ports);
			}
		});
	});
Example #28
0
Arduino.prototype.detect = function (callback) {
  var rport = /usb|acm|^com/i,
      _this  = this, ports;

  //List serial ports
  serial.list(function (err, result) {
    var r = /arduino/i,
        ports, length, possible, found;

    ports = result.filter(function (val) {
      var available = true;

      // Match only ttyUSB#, cu.usbmodem#, COM#
      if (!rport.test(val.comName)) {
        available = false;
      }

      return available;

    }).map(function (val) {
      return {
        comName     : val.comName,
        manufacturer: val.manufacturer,
        pnpId       : ((val.pnpId) ? val.pnpId : null)
      };
    });

    //If no ports
    if (!ports.length) {
      err = new Error(_this.errorMsg);
    }

    //Try to connect each port
    ports.forEach(function (port) {
      //Test if is an arduino
      if (r.test(port.manufacturer) || r.test(port.pnpId)) {
        try {
          temp = new serial.SerialPort(port.comName, {
            baudrate: _this.baudrate,
            parser  : serial.parsers.readline('\n')
          });
        } catch (e) {
          err = e;
        }

        if (!err) {
          found = temp;
          _this.manufacturer = port.manufacturer;

        } else {
          err = new Error(_this.errorMsg);
        }
      }
    });

    callback(err, found);
  });
};
Example #29
0
 socket.on('terminal:opened', function (callback) {
     serialPort.list(function (err, ports) {
         if(err) return callback({error : err});
 		callback({ok : true, data : {
     	    ports : ports,
     	    //bauds : [9600]
     	}});
 	});
 });
Example #30
0
 function getSerialPorts() {
   if (serialPorts.length > 0) { return; }
   serialport.list(function (err, ports) {
     ports.forEach(function(port) {
       serialPorts.push(port.comName);
     });
     logger('Detected serial ports: ' + JSON.stringify(serialPorts));
   });
 }