我想我已经在代码中游了太久了。我是socket.io,node和express的新手。现在我在服务器端有一个电位器发出消息,在客户端,我在javascript控制台接收它们(我正在使用Chrome)。我的目标是让电位计改变HTML页面上滑块的位置,这反过来会使用tone.js库改变振荡器的频率。
我已将上限设为200并打印任何内容。这是服务器端的片段,我的app.js
cylon.robot({
connections: {
edison: {
adaptor: 'intel-iot'
}
},
devices: {
button: {
driver: 'button',
pin: 2
},
sensor: {
driver: 'analogSensor',
pin: 0,
upperLimit: 200,
lowerLimit: 0
}
}
}).on('ready', cylonReady);
cylon.start()
// this will be called each time a socket is opened, so each client will receive their own events when buttons are pushed.
var registerSocketHandlers = function (my, socket) {
my.button.on('push', function () {
socket.emit('button', 'push')
})
my.button.on('release', function () {
socket.emit('button', 'release')
})
my.sensor.on('upperLimit', function (val) {
//console.log("Upper limit reached ===> " + val);
socket.emit('analogSensor', val)
});
}
我的客户端的片段,index.HTML:
var potVal = 0;
socket.on('analogSensor', function (analogVal) {
potVal = analogVal;
console.log('sensor value', potVal)
});
new Interface.Slider({
drag: function (value) {
frequency.rampTo(value, 0.1);
},
start: function () {
Tone.Master.mute = false;
},
end: function () {
Tone.Master.mute = true;
},
name: "frequency",
min: 0,
max: 1,
exp: .5,
value: potVal / 10, //original value is .5
position: 5
});
我在网上看过问答。大部分都是没有决心的。我仍然尝试过它们,并尝试在上面的代码中看到的客户端上设置一个全局变量,并在滑块中换出值。它要么滑块根本不显示,要么对它没有影响。欢迎任何建议。谢谢!
答案 0 :(得分:0)
此问题与SocketIo本身无关。您应该在收到消息时更新滑块,如以下代码所示:
var potVal = 0; // this is useless actually
//socket.on('analogSensor', function (analogVal) {
function dummy_socket_on_analogSensor (analogVal) {
potVal = analogVal;
console.log('sensor value', potVal);
$('#chance_slider').val(potVal);
};
// when a value is got from socket.io, this will happen:
var i = 0;
function simulateSocketIoMessages () {
dummy_socket_on_analogSensor(i);
i += 5;
setTimeout(simulateSocketIoMessages, 1000);
}
simulateSocketIoMessages();
这是工作的jsFiddle:http://jsfiddle.net/sRbHZ/74/