weblab-instrument
Version:
communication with instrument through usb
1,409 lines (1,279 loc) • 541 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("debug"), require("events"), require("os"), require("async"), require("child_process"), require("fs"), require("path"), require("net"), require("serialport"), require("weblab-usb-detection"));
else if(typeof define === 'function' && define.amd)
define(["debug", "events", "os", "async", "child_process", "fs", "path", "net", "serialport", "weblab-usb-detection"], factory);
else if(typeof exports === 'object')
exports["driver"] = factory(require("debug"), require("events"), require("os"), require("async"), require("child_process"), require("fs"), require("path"), require("net"), require("serialport"), require("weblab-usb-detection"));
else
root["driver"] = factory(root["debug"], root["events"], root["os"], root["async"], root["child_process"], root["fs"], root["path"], root["net"], root["serialport"], root["weblab-usb-detection"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_5__, __WEBPACK_EXTERNAL_MODULE_6__, __WEBPACK_EXTERNAL_MODULE_12__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_14__, __WEBPACK_EXTERNAL_MODULE_15__, __WEBPACK_EXTERNAL_MODULE_42__, __WEBPACK_EXTERNAL_MODULE_43__, __WEBPACK_EXTERNAL_MODULE_44__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 32);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var chID = __webpack_require__(2).chID;
var debug = __webpack_require__(1);
var log = debug('method:log');
function checkParameterString(arg, par) {
for (var i = 0; i < par.length; i += 1) {
if (arg.toUpperCase() === par[i].toUpperCase()) {
return true;
}
}
return false;
}
function Method(id) {
var method = {
get: function get(prop, res, callback) {
var self = this;
var cmd = void 0;
if (this.dev.gdsType === '') {
callback('300', this.dev.gdsType + ': not supported');
return;
}
log('this.gdsType=' + this.dev.gdsType);
log('prop=+' + prop);
log('id=' + id);
if (this.commandObj[this.dev.gdsType][prop].command[0].length > 1) {
log('id = ' + id);
if (this.commandObj[this.dev.gdsType][prop].parameter_type === 'bind_para') {
cmd = '' + this.commandObj[this.dev.gdsType][prop].command[chID[id]] + res.toString() + '?\r\n';
} else {
cmd = this.commandObj[this.dev.gdsType][prop].command[chID[id]] + '?\r\n';
}
} else if (this.commandObj[this.dev.gdsType][prop].parameter_type === 'bind_para') {
cmd = '' + this.commandObj[this.dev.gdsType][prop].command + res.toString() + '?\r\n';
} else {
cmd = this.commandObj[this.dev.gdsType][prop].command + '?\r\n';
}
if (this.dev.gdsType === 'LCR6000') {
cmd = cmd.slice(0, -2) + '\n';
}
log('getProp cmd = ' + cmd);
if (this.commandObj[this.dev.gdsType][prop].parameter_type === 'query_only_block') {
this.dev.queryBlock = true;
} else {
this.dev.queryBlock = false;
}
this.dev.state.conn = 'query';
this.dev.state.currentCmd = cmd;
this.dev.state.currentId = id;
this.dev.state.setTimeout = true;
this.dev.state.timeoutCb = function timeoutCb() {
log('!!!!!!!query timeout: cmd =' + self.dev.state.currentCmd);
self.dev.queryBlock = false;
self.dev.state.conn = 'timeout';
if (self.dev.errHandler) {
self.dev.errHandler(self);
}
callback(['408', 'command : ' + self.dev.state.currentCmd + ',timeout']);
};
this.dev.state.timeoutObj = setTimeout(function () {
self.dev.state.timeoutCb();
}, 5000);
this.dev.cmdHandler = this[id].cmdHandler[prop].getHandler;
this.dev.handlerSelf = this[id];
this.dev.syncCallback = callback;
if (!this.dev.write(cmd)) {
clearTimeout(this.dev.state.timeoutObj);
callback(['405', 'device not avaiable']);
}
}.bind(this),
set: function set(prop, arg, callback) {
var cmd = void 0;
var rangeLimit = this.commandObj[this.dev.gdsType][prop];
var self = this;
if (this.dev.gdsType === '' || this.dev.gdsType === 'undefined') {
callback('300', this.dev.gdsType + ' : not supported');
return;
}
log(this.gdsType + ' = ' + this.dev.gdsType);
if (prop === 'delay_for_a_while') {
setTimeout(function () {
if (callback) {
callback();
}
}, arg);
return;
}
if (this.commandObj[this.dev.gdsType][prop].command[0].length > 1) {
log('id = ' + id);
cmd = this.commandObj[this.dev.gdsType][prop].command[chID[id]];
log(prop + ' command = ' + cmd);
} else {
cmd = this.commandObj[this.dev.gdsType][prop].command;
}
if (rangeLimit.parameter_type === 'string') {
if (checkParameterString(arg, rangeLimit.parameter)) {
cmd += ' ' + arg + '\r\n';
} else {
if (callback) {
callback(['100', arg + ': argument not supported', 'cmd=' + cmd]);
}
return;
}
} else if (rangeLimit.parameter_type === 'bind_para') {
if (checkParameterString(arg, rangeLimit.parameter)) {
cmd += arg + '\r\n';
} else {
if (callback) {
callback(['100', arg + ': argument not supported', 'cmd=' + cmd]);
}
return;
}
} else if (rangeLimit.parameter_type === 'user_string') {
cmd += ' "' + arg + '"\r\n';
} else if (rangeLimit.parameter_type === 'float_string') {
var i = 0;
if (isNaN(arg)) {
cmd += ' ' + rangeLimit.parameter[0] + '\r\n';
} else {
var fval = parseFloat(arg);
for (i = 0; i < rangeLimit.parameter.length; i += 1) {
if (fval === parseFloat(rangeLimit.parameter[i])) {
log('parseFloat=' + parseFloat(rangeLimit.parameter[i]));
log('arg=' + fval.toExponential(3));
cmd += ' ' + rangeLimit.parameter[i] + '\r\n';
break;
}
}
}
if (i >= rangeLimit.parameter.length) {
if (callback) {
callback(['100', arg + ': argument not supported', 'cmd=' + cmd]);
}
return;
}
} else if (rangeLimit.parameter_type === 'parameter_free') {
cmd += '\r\n';
} else if (rangeLimit.parameter_type === 'int_value') {
var val = parseInt(arg, 10);
if (isNaN(arg)) {
if (callback) {
callback(['100', arg + ': argument not supported', 'cmd=' + cmd]);
}
return;
}
cmd = cmd + ' ' + val.toString() + '\r\n';
} else if (rangeLimit.parameter_type === 'pwr_specific') {
if (rangeLimit.format === 'no_separate') {
cmd += arg + '\r\n';
} else {
cmd += ':' + arg + '\r\n';
}
} else if (isNaN(arg)) {
if (arg === 'SETTO50' || arg === 'TTL' || arg === 'ECL') {
cmd = cmd + ' ' + arg + '\r\n';
} else {
if (callback) {
callback(['100', arg + ': argument not supported', 'cmd=' + cmd]);
}
return;
}
} else {
var _fval = parseFloat(arg);
cmd = cmd + ' ' + _fval.toExponential(3) + '\r\n';
}
if (this.dev.gdsType === 'LCR6000') {
cmd = cmd.slice(0, -2) + '\n';
}
log('cmd set = ' + cmd);
this.dev.cmdHandler = null;
if (this.dev.write(cmd)) {
self[id].cmdHandler[prop].setHelper(self[id], arg);
if (callback) {
log('cmd set done');
callback(null);
}
} else if (this.dev.interf === 'net') {
this.dev.net.socket.once('drain', function () {
self.dev.write(cmd);
self[id].cmdHandler[prop].setHelper(self[id], arg);
if (callback) {
callback(null);
}
});
} else if (this.dev.interf === 'usb') {
if (callback) {
callback('usb write error');
}
}
}.bind(this)
};
return method;
}
exports.CreatMethod = Method;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = require("debug");
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// var chID = {
// 'ch1' : 0,
// 'ch2' : 1,
// 'ch3' : 2,
// 'ch4' : 3,
// 'meas1' : 0,
// 'meas2' : 1,
// 'meas3' : 2,
// 'meas4' : 3,
// 'meas5' : 4,
// 'meas6' : 5,
// 'meas7' : 6,
// 'meas8' : 7
// };
// exports.chID = chID;
// var dsoState = {
// 'disconnect' : 0,
// 'timeout' : 1,
// 'connected' : 2,
// 'query' : 3
// };
// exports.dsoState = dsoState;
// var dsoErrCode = {
// 'systemErr' : {message : 'systemErr', type : 1},
// 'timeoutErr' : {message : 'timeoutErr', type : 2},
// 'commandErr' : {message : 'commandErr', type : 3},
// 'intrefErr' : {message : 'intrefErr', type : 4}
// };
// exports.dsoErrCode = dsoErrCode;
// var supportDevice={
// GDS2002E:{vid:'0x2184',pid:'0x003f',type:'DSO'},
// DCS2002E:{vid:'0x098f',pid:'0x2204',type:'DSO'},
// AFG2225:{vid:'0x2184',pid:'0x001C',type:'AFG'}
// };
// exports.supportDevice = supportDevice;
// var supportType = ['GDS2000E'];
// exports.supportType = supportType;
module.exports = {
chID: {
ch1: 0,
ch2: 1,
ch3: 2,
ch4: 3,
meas1: 0,
meas2: 1,
meas3: 2,
meas4: 3,
meas5: 4,
meas6: 5,
meas7: 6,
meas8: 7,
am1: 0,
am2: 1,
fm1: 0,
fm2: 1,
pm1: 0,
pm2: 1,
fsk1: 0,
fsk2: 1,
sum1: 0,
sum2: 1,
sweep1: 0,
sweep2: 1
},
dsoState: {
am: 0,
timeout: 1,
connected: 2,
query: 3
},
afgModCmd: {
am1: {
type: 'AMInteFunc',
freq: 'AMInteFreq',
source: 'AMSource',
depth: 'AMDepth',
state: 'AMState'
},
am2: {
type: 'AMInteFunc',
freq: 'AMInteFreq',
source: 'AMSource',
depth: 'AMDepth',
state: 'AMState'
},
fm1: {
type: 'FMInteFunc',
freq: 'FMInteFreq',
source: 'FMSource',
deviation: 'FMDeviation',
state: 'FMState'
},
fm2: {
type: 'FMInteFunc',
freq: 'FMInteFreq',
source: 'FMSource',
deviation: 'FMDeviation',
state: 'FMState'
},
pm1: {
type: 'PMInteFunc',
freq: 'PMInteFreq',
source: 'PMSource',
deviation: 'PMDeviation',
state: 'PMState'
},
pm2: {
type: 'PMInteFunc',
freq: 'PMInteFreq',
source: 'PMSource',
deviation: 'PMDeviation',
state: 'PMState'
},
fsk1: {
freq: 'FSKInteFreq',
source: 'FSKSource',
rate: 'FSKRate',
state: 'FSKState'
},
fsk2: {
freq: 'FSKInteFreq',
source: 'FSKSource',
rate: 'FSKRate',
state: 'FSKState'
},
sum1: {
type: 'SUMInteFunc',
freq: 'SUMInteFreq',
source: 'SUMSource',
ampl: 'SUMAmpl'
},
sum2: {
type: 'SUMInteFunc',
freq: 'SUMInteFreq',
source: 'SUMSource',
ampl: 'SUMAmpl'
},
sweep1: {
state: 'SweepState',
startfreq: 'SweepFrqStart',
stopfreq: 'SweepFrqStop',
centerfreq: 'SweepFrqCenter',
markerfreq: 'SweepMarkerFreq',
span: 'SweepFrqSpan',
swptime: 'SweepTime',
marker: 'SweepMarker',
type: 'SweepSpacing',
source: 'SweepSource'
},
sweep2: {
state: 'SweepState',
startfreq: 'SweepFrqStart',
stopfreq: 'SweepFrqStop',
centerfreq: 'SweepFrqCenter',
markerfreq: 'SweepMarkerFreq',
span: 'SweepFrqSpan',
swptime: 'SweepTime',
marker: 'SweepMarker',
type: 'SweepSpacing',
source: 'SweepSource'
}
},
dmmFuncType: {
voltdc: 'VoltDC',
voltac: 'VoltAC',
voltdcac: 'VoltDCAC',
currdc: 'CurrDC',
currac: 'CurrAC',
currdcac: 'CurrDCAC',
resistance: 'Resistance'
},
dsoErrCode: {
systemErr: { message: 'systemErr', type: 1 },
timeoutErr: { message: 'timeoutErr', type: 2 },
commandErr: { message: 'commandErr', type: 3 },
intrefErr: { message: 'intrefErr', type: 4 }
},
/*
* Use to pare usb device
*/
supportDevice: {
GDS2004A: { vid: '0x2184', pid: '0x0014', baudrate: 115200, type: 'DSO' },
GDS2002A: { vid: '0x2184', pid: '0x0013', baudrate: 115200, type: 'DSO' },
GDS2002E: { vid: '0x2184', pid: '0x003f', baudrate: 115200, type: 'DSO' },
GDS2004E: { vid: '0x2184', pid: '0x0040', baudrate: 115200, type: 'DSO' },
DCS2002E: { vid: '0x098f', pid: '0x2204', baudrate: 115200, type: 'DSO' },
GDS1002B: { vid: '0x2184', pid: '0x0044', baudrate: 115200, type: 'DSO' },
GDS1004B: { vid: '0x2184', pid: '0x0043', baudrate: 115200, type: 'DSO' },
AFG2225: { vid: '0x2184', pid: '0x001C', baudrate: 115200, type: 'AFG' },
MFG2100: { vid: '0x2184', pid: '0x0050', baudrate: 115200, type: 'AFG' },
MFG2200: { vid: '0x2184', pid: '0x004E', baudrate: 115200, type: 'AFG' },
GDM8342: { vid: '0x2184', pid: '0x0030', baudrate: 115200, type: 'DMM' },
GDM835X: { vid: '0x2184', pid: '0x003B', baudrate: 115200, type: 'DMM' },
GDM826X: { vid: '0x2184', pid: '0x001a', baudrate: 115200, type: 'DMM' },
GPD4303S: { vid: '0x0403', pid: '0x6001', baudrate: 9600, type: 'PWS' },
LCR6002: { vid: '0x067b', pid: '0x2303', baudrate: 115200, type: 'LCR' },
LCR6200: { vid: '0x1a86', pid: '0x7523', baudrate: 115200, type: 'LCR' }
},
/*
* Use to find command table
*/
supportType: ['GDS2000E', 'GDS1000B', 'GDS2000A', 'AFG2200', 'MFG22X0', 'GDM8300', 'GDM8200', 'GPDX303S', 'GPD3303', 'LCR6000']
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* eslint no-restricted-syntax: 0 */
/* eslint no-await-in-loop: 0 */
/* eslint no-loop-func: 0 */
var usbDetect = __webpack_require__(44);
var UsbPort = __webpack_require__(43);
var debug = __webpack_require__(1);
var os = __webpack_require__(6);
var log = debug('usb:log');
var supportDevice = __webpack_require__(2).supportDevice;
var errCnt = 0;
function pairUsb(dev, callback) {
UsbPort.list(function (err, ports) {
if (err) {
if (callback) {
return callback(err);
}
return err;
}
log(ports);
log(ports.length);
log('=====================');
for (var i = 0, len = ports.length; i < len; i += 1) {
log('ports[%d].vendorId %x', i, ports[i].vendorId);
log('ports[%d].productId %x', i, ports[i].productId);
log('ports[%d].serialNumber %x', i, ports[i].serialNumber);
log('dev.usb.vid %x', dev.usb.vid);
log('dev.usb.pid %x', dev.usb.pid);
log('comName =', dev.usb.comName);
// if(ports[i].serialNumber === serialNumber || ports[i].productId == 24577){
if (ports[i].comName === dev.usb.comName) {
log('comName match');
if (dev.state.conn !== 'connected') {
(function () {
var port = ports[i];
setTimeout(function () {
dev.usb.device = new UsbPort(port.comName, {
baudrate: dev.usb.baudrate,
encoding: 'binary',
lock: false,
autoOpen: false
});
// util.inherits(dev.usb,events.EventEmitter);
log('---------------------');
log(dev.usb.device);
log('---------------------');
dev.interf = 'usb';
if (dev.usb.device.isOpen()) {
log('USB device already opened');
if (callback) {
callback();
}
} else {
dev.usb.device.on('error', function () {
if (dev.usb.device) {
if (dev.usb.device.isOpen()) {
dev.usb.device.close();
}
}
dev.state.conn = 'disconnected';
dev.usb.device = null;
dev.interf = 'empty';
});
dev.usb.device.open(function (error) {
if (error) {
log('error msg: ' + error);
errCnt += 1;
if (errCnt > 5) {
if (callback) {
callback(error);
}
} else {
setTimeout(function () {
dev.usb.device = null;
pairUsb(dev, callback);
}, 2000);
}
return;
}
errCnt = 0;
// dev.usb.device = device;
dev.usb.device.flush(function () {
dev.state.conn = 'connected';
log('open USB device');
dev.usb.device.on('data', dev.dataHandler);
dev.state.conn = 'connected';
dev.usb.device.on('disconnect', function (discErr) {
log('usb disconnect');
if (discErr) {
log(discErr);
}
dev.state.conn = 'disconnected';
dev.usb.device = null;
dev.interf = 'empty';
log('-----------------');
});
if (callback) {
log('paireUsb success');
callback(error);
} else {
log('paireUsb success without callback');
}
});
});
}
}, 1500);
// }
})();
} else {
log('usb pair: dev already connected');
if (callback) {
callback();
}
}
return '';
}
}
if (dev.usb.device) {
if (dev.usb.device.isOpen()) {
dev.usb.device.close();
}
}
dev.state.conn = 'disconnected';
dev.usb.device = null;
dev.interf = 'empty';
return '';
});
}
exports.openUsb = function openUsb(dev, callback) {
if (!dev.usb.device) {
pairUsb(dev, callback);
} else {
log('usd.device exist, but want to creat again');
callback();
}
};
exports.closeUsb = function closeUsb(dev, callback) {
if (dev.usb.device) {
if (dev.usb.device.isOpen()) {
dev.usb.device.close(callback);
}
} else {
log('usd.device not exist, but want to closeUsb');
callback();
}
// dev.state.conn='disconnected';
// dev.usb.device=null;
// dev.interf='empty';
};
exports.BindUsbObj = function BindUsbObj(dev, device) {
log('BindUsbObj');
log(device);
dev.interf = 'usb';
dev.usb = {
manufacturer: device.manufacturer,
deviceName: device.deviceName,
serialNumber: device.serialNumber,
comName: device.comName,
baudrate: device.baudrate,
vid: device.vendorId,
pid: device.productId,
// usbDev:{},
device: null,
// pairUsb: pairUsb,
// onChange:(function(){
// log('usb onChange event');
// pairUsb(this);
// }).bind(dev),
write: function write(data) {
if (this.usb.device === null) {
log('usb device not exist');
return false;
}
log('is open ? ' + this.usb.device.isOpen());
log('write data=' + data);
// if(this.usb.device!==null){
if (this.usb.device.isOpen()) {
this.usb.device.write(data, function (err, results) {
// log('err ' + err);
if (err) {
// TODO : error handler
log('results ' + results);
}
log('usb write done');
});
return true;
}
log('usb device not open !!');
// pairUsb(this,function(err){
// });
return false;
// }
}.bind(dev)
// onData:(function(callback){
// // let device= this.usb.device;
// // this.usb.device.on('data',callback);
// // log(this.usb.device);
// }).bind(dev)
};
// pairUsb take long time, so pair before connect to use
// pairUsb(dev);
// usbDetect.on('add:'+vid+':'+pid, dev.usb.onChange);
// usbDetect.on('remove:'+vid+':'+pid, dev.usb.onChange);
};
exports.regRemoveEvent = function regRemoveEvent(callback) {
usbDetect.on('remove', callback);
};
exports.regAddEvent = function regAddEvent(callback) {
usbDetect.on('add', callback);
};
exports.listUsbDevice = function listUsbDevice(callback) {
var i = void 0;
var len = void 0;
var j = void 0;
var validDevice = [];
log('listUsbDevice');
// console.log(os.arch() +" platform :" +os.platform());
UsbPort.list(function (err, ports) {
if (err) {
log(err);
if (callback) {
callback(validDevice);
return null;
}
return null;
}
log('get device');
log(ports);
if (os.platform() === 'win32') {
ports.forEach(function (dev) {
// pnpId return xxxxVID_0403+PID_6000xxxxxx
if (!dev.pnpId) {
return;
}
if (!dev.pnpId.match('VID')) {
return;
}
var vidIndex = dev.pnpId.match('VID').index;
var pidIndex = vidIndex + 9;
var vid = dev.pnpId.slice(vidIndex + 4, vidIndex + 8);
var pid = dev.pnpId.slice(pidIndex + 4, pidIndex + 8);
var serialNumber = dev.pnpId.slice(vidIndex + 18, vidIndex + 27);
Object.keys(supportDevice).map(function (key) {
var suppPid = supportDevice[key].pid.slice(2, 6);
if (pid.toUpperCase() === suppPid.toUpperCase()) {
validDevice.push({
manufacturer: 'GWINSTEK',
// deviceName:info[1],
serialNumber: serialNumber,
comName: dev.comName,
type: supportDevice[key].type,
baudrate: supportDevice[key].baudrate,
vendorId: vid,
productId: pid
});
}
return key;
});
});
// return validDevice;
} else {
for (i = 0, len = ports.length; i < len; i += 1) {
var port = ports[i];
for (j in supportDevice) {
if (Object.prototype.hasOwnProperty.call(supportDevice, j)) {
var info = void 0;
var k = void 0;
var lenIn = void 0;
var manuf = '';
if (parseInt(port.vendorId, 16) === parseInt(supportDevice[j].vid, 16) && parseInt(port.productId, 16) === parseInt(supportDevice[j].pid, 16)) {
info = port.serialNumber.split('_');
lenIn = info.length;
if (port.productId === '0x0030') {
info.splice(3, 2);
info.splice(0, 2, 'GW');
// FIXME
info[1] += '_VCP_PORT';
// console.log(info);
} else if (port.productId === '0x6001') {
info.splice(0, 4, 'GW');
info.splice(1, 0, 'GPD-4303S');
// console.log(info);
} else if (lenIn > 3) {
for (k = 0, lenIn -= 2; k < lenIn; k += 1) {
manuf += info[k] + '_';
}
info.splice(0, lenIn, manuf.slice(0, -1));
}
log(port.vendorId);
log(port.productId);
log(info);
validDevice.push({
manufacturer: info[0],
deviceName: info[1],
serialNumber: info[2],
comName: port.comName,
type: supportDevice[j].type,
baudrate: supportDevice[j].baudrate,
vendorId: parseInt(port.vendorId, 16),
productId: parseInt(port.productId, 16)
});
break;
}
}
}
}
}
// console.log(validDevice);
// console.log("end listUsbDevice-----------------------------")
// log(validDevice.slice());
callback(validDevice);
return true;
});
};
// exports.pairUsb = pairUsb;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
/* eslint no-restricted-syntax: 0 */
var net = __webpack_require__(42);
var debug = __webpack_require__(1);
var log = debug('base:log');
var usbDev = __webpack_require__(3);
var os = __webpack_require__(6);
var sysConstant = __webpack_require__(2);
function checkModel(dev, model, serialnum) {
var sysSupportType = sysConstant.supportType;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = sysSupportType[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var supportType = _step.value;
// console.log(`check supported type ${supportType}`)
if (dev.commandObj[supportType]) {
if (dev.commandObj[supportType].model.some(function (someModel) {
return someModel === model;
})) {
dev.gdsType = supportType;
dev.gdsModel = model;
if (dev.gdsType === 'GPD3303' || dev.gdsType === 'GPDX303S' || dev.gdsType === 'AFG2200' || dev.gdsType === 'MFG22X0') {
dev.usb.serialNumber = serialnum.slice(3);
} else {
dev.usb.serialNumber = serialnum;
}
dev.maxChNum = dev.commandObj[supportType].maxChNum[model];
break;
}
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
function getIDN(dev, data) {
log('receive data string = ' + data);
if (!data.startsWith('GW')) {
if (!data.startsWith('LCR')) {
log('getIDN data error');
return false;
}
var _data$split = data.split(','),
_data$split2 = _slicedToArray(_data$split, 4),
modelName = _data$split2[0],
verNum = _data$split2[1],
serialNum = _data$split2[2],
manufacture = _data$split2[3];
log(manufacture);
log(verNum);
checkModel(dev, modelName, serialNum);
} else {
var _data$split3 = data.split(','),
_data$split4 = _slicedToArray(_data$split3, 4),
_manufacture = _data$split4[0],
_modelName = _data$split4[1],
_serialNum = _data$split4[2],
_verNum = _data$split4[3];
log('---- check Model --------');
log(_manufacture);
log(_verNum);
log(_modelName);
log(_serialNum);
log('------------');
checkModel(dev, _modelName, _serialNum);
}
log('gdsType=' + dev.gdsType);
log('gdsModel=' + dev.gdsModel);
return true;
}
function checkDsoExist(dev, callback) {
var tcnt = void 0;
log('checkDsoExist');
log('write command to server');
dev.state.conn = 'query';
dev.cmdHandler = getIDN;
dev.handlerSelf = dev;
dev.state.setTimeout = true;
if (dev.usb.pid === 24577 || dev.usb.pid === '6001') {
tcnt = 4000;
} else {
tcnt = 2000;
}
dev.syncCallback = function syncCallback() {
if (dev.state.timeoutObj) {
clearTimeout(dev.state.timeoutObj);
}
if (dev.gdsType === '') {
callback('check device exist error');
return;
// dev.state.conn = 'query';
// dev.cmdHandler = getIDN;
// dev.handlerSelf = dev;
// dev.state.setTimeout = true;
// dev.write('*IDN?\r\n');
// dev.state.timeoutObj = setTimeout(() => {
// dev.state.timeoutCb();
// }, 5000);
}
if (dev.usb.pid !== 8963) {
dev.write('*CLS\r\n');
}
callback();
};
dev.state.timeoutCb = function timeoutCb() {
log('timeout');
dev.state.conn = 'timeout';
dev.state.timeoutObj = null;
dev.syncCallback();
};
dev.state.timeoutObj = setTimeout(function () {
dev.state.timeoutCb();
}, tcnt);
if (dev.usb.pid === 24577 || dev.usb.pid === '6001') {
if (dev.write('REMOTE\r\n')) {
setTimeout(function () {
dev.write('*IDN?\r\n');
}, 1000);
} else {
log('check device exist error: usb not ready');
clearTimeout(dev.state.timeoutObj);
callback('check device exist error');
}
} else if (dev.usb.pid === 8963 || dev.usb.pid === '2303' || dev.usb.pid === 29987 || dev.usb.pid === '7523') {
if (!dev.write('*IDN?\n')) {
log('check device exist error: usb not ready');
clearTimeout(dev.state.timeoutObj);
callback('check device exist error');
}
} else if (!dev.write('*IDN?\r\n')) {
log('check device exist error: usb not ready');
clearTimeout(dev.state.timeoutObj);
callback('check device exist error');
}
}
var Dev = function Dev() {
this.state = {
conn: 'disconnect',
currentCmd: '',
currentId: '',
setTimeout: false,
timeoutObj: {},
timeoutCb: function timeoutCbInit() {},
errCode: {
message: '',
type: '',
handler: function handlerInit() {}
}
};
this.interf = 'net';
this.gdsType = '';
this.gdsModel = '';
this.chNum = 0;
this.activeCh = '';
this.cmdHandler = getIDN;
this.handlerSelf = {};
this.syncCallback = function syncCallbackInit() {};
this.maxChNum = 0;
this.commandObj = {};
this.cmdSequence = [];
this.writeTimeoutObj = null;
this.asyncWrite = 'done';
this.queryBlock = false;
this.recData = [];
this.errHandler = function errHandlerInit() {};
this.write = function write(data) {
if (this.interf === 'usb') {
if (this.usb.write(data)) {
return true;
}
return false;
} else if (this.interf === 'net') {
this.net.socket.write(data);
return true;
}
log('error: interf not support');
return false;
};
this.dataHandler = function dataHandler(data) {
var cmdDone = false;
var self = this;
if (!this.cmdHandler) {
log('dataHandler receive :' + data + ',length= ' + data.length);
log('cmdHandler not define');
return;
}
if (this.state.setTimeout) {
clearTimeout(this.state.timeoutObj);
}
if (this.queryBlock !== true) {
// Only for GPD 3303D
if (this.usb.pid === 24577 || this.usb.pid === '6001') {
if (data[data.length - 1] === 0x0a && data.length === 1) {
delete this.recData;
this.recData = [];
return;
} else if (data[data.length - 1] === 0x0d) {
data[data.length - 1] = 0x0a;
}
}
this.recData += data.slice();
if (data[data.length - 1] === 0x0a) {
if (this.usb.pid === 24577 || this.usb.pid === '6001') {
if (this.recData.includes('Invalid')) {
log('receive invalid string');
delete this.recData;
this.recData = [];
return;
}
}
if (this.cmdHandler(this.handlerSelf, this.recData, this.syncCallback)) {
cmdDone = true;
if (this.state.setTimeout) {
// if(this.state.conn!=='timeout'){
log('clearTimeout');
clearTimeout(this.state.timeoutObj);
// }
this.state.setTimeout = false;
}
if (typeof this.syncCallback === 'function') {
log('call callback');
this.syncCallback();
delete this.recData;
this.recData = [];
}
// Only for GPD 3303D
if (this.gdsType === 'GPD3303') {
this.cmdHandler = null;
}
}
}
} else {
if (os.platform() !== 'win32') {
self.usb.device.pause();
}
if (this.cmdHandler(this.handlerSelf, data, this.syncCallback)) {
cmdDone = true;
if (this.state.setTimeout) {
// if(this.state.conn!=='timeout'){
log('clearTimeout by queryBlock');
clearTimeout(this.state.timeoutObj);
// }
this.state.setTimeout = false;
}
if (typeof this.syncCallback === 'function') {
log('call callback by queryBlock');
try {
this.syncCallback();
} catch (e) {
log(e);
}
}
}
if (os.platform() !== 'win32') {
self.usb.device.resume();
}
}
if (!cmdDone) {
if (this.state.setTimeout) {
if (this.state.timeoutObj) {
clearTimeout(this.state.timeoutObj);
}
this.state.timeoutObj = setTimeout(function () {
log('dataHandler timeout');
self.state.timeoutCb();
}, 5000);
}
}
}.bind(this);
return this;
};
Dev.prototype.onSocketErr = function onSocketErr(cb) {
var self = this;
this.net.socket.on('error', function (e) {
log('onTcpConnect: connect error!');
self.state.conn = 'disconnect';
self.net.socket.end();
if (cb) {
cb(e.message);
}
});
};
Dev.prototype.tcpConnect = function tcpConnect(Callback) {
var self = this;
if (self.state.conn === 'connected') {
if (Callback) {
Callback();
}
return;
}
this.net.socket = net.connect(this.net.port, this.net.host_addr, function () {
// 'connect' listener
log('connected to server!');
// dsoObj.net.socket.setEncoding('utf8');
self.net.socket.setMaxListeners(0);
self.state.conn = 'connected';
self.interf = 'net';
// self.net.socket.on('data',self.net.dataHandler);
self.net.socket.on('data', self.dataHandler);
self.checkDsoExist(self, Callback);
// if(Callback)
// Callback();
});
this.net.socket.on('close', function () {
log('onTcpConnect: close!');
self.state.conn = 'disconnect';
// dsoObj.net.socket.destroy();
});
};
Dev.prototype.tcpDisconnect = function tcpDisconnect(Callback) {
var self = this;
this.net.socket.removeAllListeners('close');
this.net.socket.on('close', function (e) {
log('onTcpConnect: close!');
self.state.conn = 'disconnect';
if (Callback) {
Callback(e);
}
});
this.net.socket.end();
};
Dev.prototype.usbConnect = function usbConnect(Callback, dontCheckdev) {
var self = this;
usbDev.openUsb(this, function (err) {
if (err) {
Callback(err);
} else {
log('openUsb');
// self.usb.onData(self.dataHandler);
if (!dontCheckdev) {
checkDsoExist(self, Callback);
} else {
Callback();
}
}
});
};
Dev.prototype.usbDisconnect = function usbDisconnect(Callback) {
var self = this;
if (self.state.conn !== 'disconnected') {
usbDev.closeUsb(this, function (err) {
if (err) {
log(err);
}
self.state.conn = 'disconnected';
self.usb.device = null;
self.interf = 'empty';
if (Callback) {
Callback(err);
}
});
} else if (Callback) {
Callback();
}
};
exports.Dev = Dev;
/***/ }),
/* 5 */
/***/ (function(module, exports) {
module.exports = require("events");
/***/ }),
/* 6 */
/***/ (function(module, exports) {
module.exports = require("os");
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var cmdWrite = function () {
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee2() {
var sendCmd = function () {
var _ref2 = _asyncToGenerator(regeneratorRuntime.mark(function _callee(cmdItem) {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', new Promise(function (resolve, reject) {
if (cmdItem.method === 'set') {
// log(self['sys']);
self[cmdItem.id].prop.set(cmdItem.prop, cmdItem.arg, function (err) {
if (err) {
reject(err);
return;
}
resolve();
});
} else {
self[cmdItem.id].prop.get(cmdItem.prop, cmdItem.arg, function (err) {
if (err) {
reject(err);
return;
}
resolve();
});
}
}));
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function sendCmd(_x) {
return _ref2.apply(this, arguments);
};
}();
// log(this.dev.cmdSequence);
var self, cb, cmd, i, len, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, cmdItem;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
self = this;
cb = null;
cmd = [];
if (!(this.dev.asyncWrite === 'busy')) {
_context2.next = 7;
break;
}
log('async write busy');
log(this.dev.cmdSequence);
return _context2.abrupt('return');
case 7:
i = 0, len = this.dev.cmdSequence.length;
case 8:
if (!(i < len)) {
_context2.next = 16;
break;
}
cmd[i] = this.dev.cmdSequence.shift();
if (!(cmd[i].cb !== null)) {
_context2.next = 13;
break;
}
cb = cmd[i].cb;
return _context2.abrupt('break', 16);
case 13:
i += 1;
_context2.next = 8;
break;
case 16:
if (!(self.dev.state.conn === 'disconnected')) {
_context2.next = 20;
break;
}
if (cb) {
cb('device disconnect');
}
self.dev.asyncWrite = 'done';
return _context2.abrupt('return');
case 20:
if (!(cmd.length === 0)) {
_context2.next = 23;
break;
}
self.dev.asyncWrite = 'done';
return _context2.abrupt('return');
case 23: