未捕获的类型错误:无法读取未定义的属性“open”
2018-05-11
5698
我创建了一个名为 Sensors 的函数,并在其中实例化了 serialport 对象。我还创建了一个原型 find,理论上应该可以访问要打开、写入和绑定的端口对象。
我收到错误:
Uncaught TypeError: Cannot read property 'open' of undefined
我不确定为什么....
代码:
<script>
var sp = require('serialport');
var comports = [];
//Object to connect to a specific comport and send the 'i' command
function Sensors(com) {
this.find();
this.address = com;
this.port = new sp(com, {
baudrate: 9600,
autoOpen: false
});
}
Sensors.prototype.find = function() {
console.log("ran");
this.port.open(function(err) {
if (err) {
return console.log('Error opening port: ', err.message);
}
this.port.write('i' + String.fromCharCode(13), function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
this.port.on('data', function(data) {
var sensorData = data;
var splitString = sensorData.toString().split(',');
console.log(splitString[1]);
if (sensorData.length > 0) {
if (splitString[1] == 'pH' || splitString[1] == 'EC' || splitString[1] == 'RTD') {
console.log(splitString[1]);
}
this.port.close(function(err) {
console.log('port closed', err);
});
}
});
});
};
function findSensors() {
sp.list(function(err, ports) {
for (i = 0; i < ports.length; i++) {
var sensor = new Sensors(ports[i].comName);
sensor.find();
}
});
}
//startup function to find comports and find the sensor(s)
function startUp() {
findSensors();
}
</script>
1个回答
在构造函数中,您在分配
this.port
之前调用了
this.find();
,因此
find
中的
this.port.open
行会导致错误。请进行更改,使
this.find
在
port
属性填充
之后
运行。
function Sensors(com) {
this.address = com;
this.port = new sp(com, {
baudrate: 9600,
autoOpen: false
});
this.find();
}
CertainPerformance
2018-05-11