我正在为我的 beaglebone black 编写一个程序,以通过网页控制啤酒酿造过程的某些方面。我正在使用 socket.io 来保持实时通信。为此,我将套接字对象传递给位于硬件类中的操作。一些类,比如我的 temp_sensor 类使用 eventEmitter 模式来允许其他对象订阅它的数据。但是,当我使用 temp_sensor 的方法订阅传入的套接字时,它告诉我对象(this)没有“on”方法。下面是我的代码:
module.exports = temp_sensor;
var fs = require("fs"),
exec = require("child_process").exec,
util = require("util"),
EventEmitter = require("events").EventEmitter;
var w1path = "/sys/bus/w1/devices/";
function temp_sensor(config){
// Put sensor verification code here//
this.name = config.name;
this.address = config.w1_address;
this.path = w1path + this.address + "/w1_slave";
this.value = null;
this.unit = config.unit;
this.emit_interval = 2000;
this.type = config.type;
this.subscribers = 0;
this.emitting = false;
this.prev_temp = null;
if (config.emit_interval){this.emit_interval = config.emit_interval;}
var self = this;
/*this.emit_data = setInterval(self.readSensor(function(temp) {
if (temp !== this.prev_temp) {
var timestamp = new Date().toJSON()
var data = {
"name": this.name,
"temp":temp,
"timestamp": timestamp
};
self.emit("temp_data", data);
this.prev_temp = temp;
};
}),this.emit_interval);*/
}
util.inherits(temp_sensor, EventEmitter);
temp_sensor.prototype.readSensor = function(callback){
var cmd = "cat " + this.path + " | grep t= | cut -f2 -d= | awk '{print $1/1000}'";
exec(cmd , function( error, stdout, stderr ) {
if (error) { callback(error); }
callback( Math.round((parseFloat(stdout) * 1.8 + 32) * 10) / 10 );
});
};
// component actions
temp_sensor.prototype.actions = [];
temp_sensor.prototype.actions["subscribe"] = function(socket) {
this.subscribers++;
this.on("temp_data",function(data) {
socket.emit("temp_sensor",data);
});
};
temp_sensor.prototype.actions["unsubscribe"] = function(socket) {
this.subscribers--;
// remove listener
};
我收到此错误:
/var/lib/cloud9/brewbone/lib/temp_sensor.js:64 this.on("temp_data",function(data) { ^ TypeError: Object has no method 'on' at Array.temp_sensor.actions.subscribe (/var /lib/cloud9/brewbone/lib/temp_sensor.js:64:7)
任何帮助将不胜感激!