gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'open' of undefined

转载 作者:行者123 更新时间:2023-12-03 01:54:56 24 4
gpt4 key购买 nike

我创建了一个名为 Sensors 的函数,并在其中实例化了串行端口对象。我还创建了一个原型(prototype) find,理论上应该访问端口对象以打开、写入和绑定(bind)。

我收到错误:

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>

最佳答案

在构造函数中,您在分配给 this.port 之前调用 this.find();,因此 this.port 行find 内的 .open 会导致错误。更改它,以便 this.find 在填充 port 属性之后运行。

function Sensors(com) {
this.address = com;
this.port = new sp(com, {
baudrate: 9600,
autoOpen: false
});
this.find();
}

关于javascript - 未捕获的类型错误 : Cannot read property 'open' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50283667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com