I've been trying to get this working, but unsuccessfully. The code seems to work right on the first click, but after a few clicks it outputs an increasing number of times both the if conditions randomly.
On the server side I have on Node.js
var sys = require('sys');
var net = require('net');
var mqtt = require('mqttclient');
var io = require('socket.io').listen(5000);
var client = new mqtt.MQTTClient(1883, '192.168.1.33', 'SERVER NODO');
io.sockets.on('connection', function (socket) {
socket.on('subscribe', function (data) {
console.log('Subscribing to '+data.topic);
client.subscribe(data.topic);
});
});
io.sockets.on('connection', function (socket) {
socket.on('publish', function (data){
console.log('publishing to '+data.topic);
client.publish(data.topic,data.payload);
});
});
//Sends to Web
client.addListener('mqttData', function(topic, payload){
sys.puts(topic+'='+payload);
io.sockets.emit('mqtt',{'topic':String(topic),
'payload':String(payload)});
});
On the client side I have this page, which loads correctly, the first if block seems to be fine, is the second block where I am having troubles. I don't have any experience programming, but I'm studying hard!
Tried already different combinations to get this to work (eg putting the on click after the if contition, but with the same result.
<link rel="stylesheet" href="style2.css">
<script type="text/javascript" src="http://192.168.1.33:5000/socket.io/socket.io.js</script>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
var socket = io.connect('http://192.168.1.33:5000');
$(document).ready(function(){
socket.on('connect', function () {
socket.on('mqtt', function (msg) {
console.log(msg.topic+' '+msg.payload);
var classe = 0;
if (msg.topic == "uno"){
if (msg.payload == "a")
$('#button').addClass('on');
classe = 1;
if (msg.payload == "b")
$('#button').removeClass('on');
casse = 0;
}
$('#button').on('click', function(){
if (classe == 1)){
classe = 3;
socket.emit('publish',{topic:"unor", payload:"off"});
}
if (classe == 0){
classe = 3;
socket.emit('publish',{topic:"unor", payload:"on"});
}
});
});
socket.emit('subscribe',{topic:"uno"});
});
</script>
<tbody>
<section>
<a href="#" id="button"></a>
<span></span>
</section>
</tbody>
Your problem is may be with click event try with below code.
$('#button').off('click').on('click', function(){
if (classe == 1)){
classe = 3;
socket.emit('publish',{topic:"unor", payload:"off"});
}
if (classe == 0){
classe = 3;
socket.emit('publish',{topic:"unor", payload:"on"});
}
});
I hope this will help to you.