i am need one help. i make a broker with node red and i am using mqtt ws. I tested in Hivemq website and all works good, but in my website i do publish only, and nothing received. i am using mqttws31.js. in my javascript console show conected, and i can publish but never read. Somebody help me? bellow my code. sorry for my english.\
var mqtt;
var reconnectTimeout = 2000;
var host="my_broker"; //change this
var port=9001;
function onFailure(msg) {
alert(msg);
console.log("Connection Attempt to Host "+host+"Failed");
setTimeout(MQTTconnect, reconnectTimeout);
}
function onMessageArrived(msg){
out_msg="Message received "+ msg.payloadString+"<br>";
out_msg=out_msg+"Message received Topic "+msg.destinationName;
console.log(out_msg);
document.write(msg.payloadString);
// funcoes executar
if (msg.destinationName == "voltas") {
// Temperatura
alert(msg.payloadString);
}
}
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("Connected ");
}
function MQTTconnect() {
//console.log("connecting to "+ host +" "+ port);
var x=Math.floor(Math.random() * 10000);
var cname="orderform-"+x;
mqtt = new Paho.MQTT.Client(host,port,cname);
//document.write("connecting to "+ host);
var options = {
timeout: 3,
onSuccess: onConnect,
onFailure: onFailure,
};
mqtt.onMessageArrived = onMessageArrived
mqtt.connect(options); //connect
}
Related
Is there any same method present in swift to read the input stream from HTTP request
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
This is a local server is sending two response with 207:
var http = require('http');
var express = require('express')();
var port = process.env.PORT || 3000;
var promise = new Promise(function(resolve, reject) {
const x = "geeksforgeeks";
const y = "geeksforgeeks"
if(x === y) {
console.log('resolve');
resolve();
} else {
reject();
}
});
express.post('/', function(req, res) {
console.log('send req1')
// check if network exists and user requesting is owner of it
return promise.then(() => {
// add listener to receive response from gateway and forward it
//_addGwEmitter.addGwEmitter.addEventListener(req, res, gatewayPsn);
// send the gateway trigger instructions to coco user
res.status(207).write(JSON.stringify({
status: 200,
msg: "Waiting for authorization\n",
instructionText: "devProductInfo.instructionText",
instructionImage: "devProductInfo.instructionImageURL"
}) + "\n \r End" );
// if no event is received from gateway trigger timeout after 60 seconds
res.setTimeout(6000,()=>{
console.log('send req 2');
res.status(207).write(JSON.stringify({
status: 200,
msg: "authorization done \n",
instructionText: "devProductInfo.instructionText",
instructionImage: "devProductInfo.instructionImageURL"
}));
res.end();
});
}).catch(error => {
return res.status(400).send("error.getErrorInfo()");
});
});
http.createServer(express).listen(port);
i want to read two response one by one
i have tried
uploadtask
downloadTask
dataTask
in HTTP URLSession.
I got the answer if you want to use 207 response in iOS devices then implement URL data Task with delegate and in data delegate, you will get the response data. make sure response content type is text/json
I had been working with Espruino for a bit and it is really a wonderful project. But, I am facing an issue for saving the code onto the flash, so that it can still be run when power is supplied to the board(NodeMCU), instead of the PC COM port. The code works completely fine until it is passed from the terminal. But, if I switch over the power supply it stops working.
Also, I tried the save() and E.on('init',function(){}) but to no avail. It still doesn't create a web server. If someone could help out here it could be great!
Thanks!
function main() {
var http = require('http');
var led = Pin(5);
http.createServer(function (req, res) {
var url = req.url;
res.writeHead(200);
if(url == "/on") {
digitalWrite(led, 1);
res.end("on");
} else if(url == "/off") {
digitalWrite(led, 0);
res.end("off");
} else {
res.end('Lol');
}
}).listen(80);
}
E.on('init', function(){
main();
});
Here's the code I wish to write to my flash for the IOT project I am working on
After fiddling around with the documentation and crawling the scrambled web for almost a whole day I found out a solution myself. The issue ->
function main() {
var wifi = require('Wifi');
wifi.startAP("testing");
wifi.save();
var http = require('http');
var led = Pin(5);
return http.createServer(function (req, res) {
var url = req.url;
res.writeHead(200);
if(url == "/on") {
digitalWrite(led, 1);
res.end("on");
} else if(url == "/off") {
digitalWrite(led, 0);
res.end("off");
} else {
res.end('Lol');
}
}).listen(80);
}
function test() {
console.log('Starting server');
setTimeout(function() {
var server = main();
console.log(server);
}, 5000);
}
E.on('init', function(){
test();
});
save();
The problem was that the MCU couldnot get enough time to connect to the wifi before the command for http.createServer() is executed. Since, it cannot obtain the ip address for the MCU, thus it is unable to process the http.createServer() command. Hence, a timeout was necessary to process a delay before it's execution.
So I've been building an app for quite some time and I'm running into problems in terms of scalability. I'm new to Node, and Heroku for that matter. Please bear with me.
I originally followed this tutorial to get my node service up and running. Essentially, it creates a real-time chat service. However, my question now comes with creating 'rooms'. It doesn't make sense to me that I might have 15+ chats going on, yet they all are calling the same functions on the same clientSocket, and I have to determine what UI updates go to which clients on the front end. As of now, I have upwards of 15 clients all trying to interact on different chats, but I'm pushing updates to everyone at once (for example, when a message is posted), then determining who's UI to update based on which room ID I'm cacheing on each device. Seems like a terrible waste of computing power to me.
I'm thinking that the solution involves modifying how each client connects (which is the code snippet below). Is there a way to create location based 'rooms', for example, where the clients connected are the only ones getting those updates? Any idea how to go about this solution? If anyone is also willing to just explain what I'm not understanding about Node, Express, Heroku, Socket.io or others, please do let me know.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var pg = require('pg');
var userList = [];
var typingUsers = {};
var ActiveQueue = [];
app.get('/', function(req, res){
res.send('<h1>Active RT Queue</h1>');
});
var conString = "postgres://url";
pg.defaults.ssl = true;
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
});
http.listen(process.env.PORT || 5000, function(){
console.log('Listening on *:5000');
});
io.on('connection', function(clientSocket){
console.log('a user connected');
clientSocket.on('disconnect', function(){
console.log('user disconnected');
var clientNickname;
for (var i=0; i<userList.length; i++) {
if (userList[i]["id"] == clientSocket.id) {
userList[i]["isConnected"] = false;
clientNickname = userList[i]["nickname"];
break;
}
}
delete typingUsers[clientNickname];
io.emit("userList", userList);
//io.emit("userExitUpdate", clientNickname);
//io.emit("userTypingUpdate", typingUsers);
});
clientSocket.on("exitUser", function(clientNickname){
for (var i=0; i<userList.length; i++) {
if (userList[i]["id"] == clientSocket.id) {
userList.splice(i, 1);
break;
}
}
io.emit("userExitUpdate", clientNickname);
});
clientSocket.on("connectUser", function(clientNickname) {
var message = "User " + clientNickname + " was connected.";
console.log(message);
var userInfo = {};
var foundUser = false;
for (var i=0; i<userList.length; i++) {
if (userList[i]["nickname"] == clientNickname) {
userList[i]["isConnected"] = true
userList[i]["id"] = clientSocket.id;
userInfo = userList[i];
foundUser = true;
break;
}
}
if (!foundUser) {
userInfo["id"] = clientSocket.id;
userInfo["nickname"] = clientNickname;
userInfo["isConnected"] = true
userList.push(userInfo);
}
io.emit("userList", userList);
io.emit("userConnectUpdate", userInfo)
});
///functions pertaining to transfer of messages and updating the UI follow
I would try something like this:
io.on('connection', function(clientSocket) {
clientSocket.on('room:general', function(data) {
var user = data.user;
var message = data.message;
console.log('%s sent new message: %s',user,message);
io.emit('room:general:newMessage', data);
});
//and so for each room
.........
});
and from front end you need to send JSONObject:
{
user:your_username,
message:user_message
}
,
socket.emit("room:general", json_object);
socket.on("room:general:newMessage", onYourDefinedEmiterListener);
..........
..........
//and so for each room
I never made Chat Application, hope it helps.
This is probably easy but I could not locate a solution online. I am working on a weather station project with Cylon and MQTT and attempting to pass a variable into an MQTT push but it is passing the literal text. The publish is successful but it just has "msg" instead of the sensor data. Here is the snippet..
Cylon.robot({
connections: {
edison: { adaptor: 'intel-iot' }
},
devices: {
bmp180: { driver: 'bmp180' }
},
work: function(my) {
my.bmp180.getTemperature(function(err, val) {
if (err) {
console.log(err);
return;
}
console.log("\tTemp: " + val.temp + " C");
var msg = { "temperature" : val.temp,
"pressure" : val.press,
"altitude" : val.alt
};
var msgPressure = { "pressure" : val.press };
var msgAltitude = { "altitude" : val.alt };
device
.on('connect', function() {
console.log('connect');
device.subscribe('weather/push');
device.publish('weather/push', JSON.stringify({ msg: 1}));
});
device
.on('message', function(topic, payload) {
console.log('message', topic, payload.toString());
});
});
}
}).start();
Thank you
JSON.stringify({msg:1}) will generate a string that looks like this: {'msg': 1}
You probably want JSON.stringify(msg) in your publish line to send the msg object.
What is "efficient way" to check if some room has connected clients or even exists?
socket.on('pm', function(data) {
data.from = socket.decoded_token._id;
var to = data.to;
if (_.isUndefined(io.sockets.adapter.rooms[to])) {
debug("user [%s] is not connected", to);
} else {
socket.to(to).emit('pm', message);
}
});
Is it efficient way to do it with multiple instances of socket.io and redis adapter?
I wish something like this could be used:
socket.on('pm', function(data) {
data.from = socket.decoded_token._id;
var to = data.to;
socket.to(to).emit('pm', message, function(err){
//error callback, but callback aren't supported for broadcast messages
debug("user [%s] is not connected", to);
});
}
});