'use strict';

var serialport = require('serialport');
var SerialPort = require('serialport').SerialPort;
exports.portList = function(req,res){

   res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

  serialport.list(function (err, ports) {
  if (err) {
    return res.json(500,err);
  }
  return res.json(ports);
  });
};

exports.calWeight = function(req,res){
  //var baudrate = req.query.baudrate || 9600;

  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  var baudrate = req.params.baudrate || 9600;

  //var port = req.query.port || 'COM27';
  var port = req.params.port || '0';
   
  var machinetype = req.params.machinetype;
  //return res.send(baudrate+' '+port);

  var comPort = new SerialPort(port, {
    baudrate: String(baudrate),
   parser: serialport.parsers.readline('\n')
  }, false);
  comPort.open(function(err){
    if (err) {
      return res.json(err);
    }  
    //console.log('pass w');
    console.log('pass '+machinetype);
    comPort.write(machinetype); //comPort.write('W1');
    console.log('write done');
    comPort.on('data',function(w){
    	console.log('found data : '+w);
      comPort.close();
   //return res.json({weight:w.replace(/[^\d\.]*/g,'').trim()});
    return res.json({weight:w.trim()});
    //});
  });
  })
}
