RabbitMQ and Sails.js - node.js

I'm having trouble using RabbitMQ with my Sails app. I'm unsure of where to place the subscriber code. What I'm trying to do is build a notifications system so that when an administrator approves a user's data request, the user's dashboard will pop a notification similar to how Facebook pops a notification. The problem is, putting the subscriber code in my dashboard controller's display route seems to never grab a published message.
Any advice would be greatly appreciated. Currently using rabbit.js package to connect to RabbitMQ.

To answer the original question, if one for some reason wanted to use Rabbit MQ instead of Sails' built-in resourceful pubsub, the best thing would be to use rabbit.js.
First, npm install rabbit.js.
Then, in your Sails project's config/sockets.js (borrowed liberally from the rabbit.js socket.io example):
var context = require('rabbit.js').createContext();
module.exports = {
onConnect: function(session, socket) {
var pub = context.socket('PUB');
var sub = context.socket('SUB');
socket.on('disconnect', function() {
pub.close();
sub.close();
});
// NB we have to adapt between the APIs
sub.setEncoding('utf8');
socket.on('message', function(msg) {
pub.write(msg, 'utf8');
});
sub.on('data', function(msg) {
socket.send(msg);
});
sub.connect('chat');
pub.connect('chat');
}
}

Here's an npm package that implements a RabbitMQ adapter for SailsJS.

Related

How to connect to RouterOS via Nodejs WebSocket?

I'm learning websocket nodejs, I want to connect to routeros via websocket like the https://github.com/aluisiora/node-routeros/ package, the package is too broad, I just want to know how to connect.
I've read the official documentation https://wiki.mikrotik.com/wiki/Manual:API, but I'm having trouble understanding it.
I have tried it this way, but did not get any response:
client.connect(port, host, function () {
console.log("Connected");
client.write(encodeString("/login"));
client.write(encodeString(`=name=${user}`));
client.write(encodeString(`=password=${password}`));
});
client.on("data", function (data) {
console.log("Received: " + data); // not excetue
});
I'm looking for code samples to connect to routeros via nodejs socket, hopefully someone shares here.
Thanks in advance, I really appreciate any answer.
Take into consideration the next things:
RouterOS API has it's own protocol, it has a bit of complexity. The official wiki tell us how to interact with it at LOW LEVEL. For these reason it's very difficult to understand. Isn't for a High Level programmer. Don't worry, We have all been through here.
Routeros v7 have a REST API, that will make the job easier, the exchange language is HTTP protocol, easy right? Actually is at beta stage.
RouterOS Wiki have other package for node.js that seems more easy: Mikronode
solution
Install mikronode package
$ npm install mikronode
use it:
var api = require('mikronode');
var connection = new api('192.168.0.1','admin','password');
connection.connect(function(conn) {
var chan=conn.openChannel();
chan.write('/ip/address/print',function() {
chan.on('done',function(data) {
var parsed = api.parseItems(data);
parsed.forEach(function(item) {
console.log('Interface/IP: '+item.interface+"/"+item.address);
});
chan.close();
conn.close();
});
});
});

The Things Network: Cannot publish/subscribe to my device up/down link topics

I am trying to make quick test for the pub/sub mechanism to my registered device on TTN so I can build my complete solution app on the data coming to the TTN broker.
At the moment I am waiting for my loRa module to arrive, that is why I want to use a simple nodeJS script to publish dummy data, and the other to subscribe and build an app using the dummy data. I use the following code for this:
var mqtt = require('mqtt')
var options = {
port: 1883,
host: ‘mqtt://eu.thethings.network’,
username: ‘xxxx’, // here I wrote my app id
password: ‘xxxx’ // here I wrote the access key
};
var client = mqtt.connect(‘mqtt://eu.thethings.network’,options)
client.on(‘connect’, function () {
client.subscribe(‘appID/devices/MyDeviceName/down’, function (err) {
if (!err) {
client.publish(‘appID/devices/MyDeviceName/down’, ‘Hello mqtt’)
}
})
})
client.on(‘message’, function (topic, message) {
// message is Buffer
console.log(message.toString())
// client.end()
})
This is however not doing anything, I was watching the data on TTN, nothing coming in.
I also tried using mqtt explorer but it did not work.
Both methods worked fine when I played the broker on my machine, eclipse and mosquittoo on cloud.
Your help is greatly appreciated.
Thanks!
Ahmed
I have encountered a similar issue in the past. I believe the issue is with trying to use "mqtt" instead of "https". For me, it worked when I called
mqtt.connect('https://thethings.network:1883', {
"username": username,
"password": password
}
However, I wasn't using the community version of the website (The Things Stack V3), so there might be a slight difference. For example, instead of "My-App-Id" I had to use "My-App-Id#My-Company-Name".
Please, try the above and let me know if it works.

How can to send POST via socket.io or call a feathersjs service via socket.io?

I have a service (find, get, create, remove) and I would like to call theme via socket.io
For example:
A user writes a message on the chat to another user. I would like to the data not sending via request but in realtime on socket because in this moment creating is a document of mongoose.
Is it posible? If yes, how can I do it?
Below is my snippet code: (Server side)
io.on('connect', function(socket){
socket.on('message', function(id, msg){
socket.to(id).emit('chat message', msg);
});
}))
http://localhost:3030/messages <-- URL of REST api to creating a document with mongoose. After sending data on the link is creating a document. I need that a document will be create via socket.io, not request.
I mean something like this:
io.on('connect', function(socket){
socket.on('message', function(id, msg){
socket.to(id).emit('chat message', msg);
// Socket call a create method of my service
socket.post('/messages', data);
});
}))
If you are not using Feathers as the client you can find the detailed documentation about how to call services via sockets here.
A messages for the /messages service can be created directly via a socket like this:
var socket = io();
socket.emit('messages::create', {
"text": "I really have to iron"
}, (error, message) => {
console.log('Todo created', message);
});
You can also listen to any created event like this:
var socket = io();
socket.on('messages created', data => console.log('Someone created a new message', data);
socket.emit('messages::create', {
"text": "I really have to iron"
}, (error, message) => {
console.log('Todo created', message);
});
Well, yes and no. There are no HTTP/REST-style verbs in Socket.io but since you can send anything you want, you can add the verbs yourself.
Additionally if you want to have a more structured way of building real-time APIs then you may want to take a look at frameworks like ActionHerp:
https://www.actionherojs.com/
In addition to HTTP, it can use WebSocket or TCP sockets as the underlying transport, and you can create custom "actions" that you can customize to your needs.
Now, if you want to use Feathers and you don't want to use anything else, then you may take a look at feathers-socketio:
https://www.npmjs.com/package/feathers-socketio
It's a Feathers Socket.io real-time API provider that exposes Feathers services through a Socket.io real-time API. It is compatible with Feathers 1.x and 2.x. And you can use Socket.io to interact with it.

receive sails.js messages on model create on a third party domain

I'm trying to workout how to receive messages from sails.js when a new entry is created via the rest api. I'm trying to receive this message outside of sails (but also for other reasons in sails)
In my sails app I can receive the message when a new entry is like so...
var socket = io.connect("http://localhost:1337");
socket.on("connect", function(){
socket.request("/job", {}, function(jobs){
console.log("jobs", jobs);
})
socket.on('message', function(message){
console.log('message', message);
})
})
When a new 'job' is created, the web app receives a message.
I would like to receive the same message outside of sails. I've used this gist https://gist.github.com/epadillas/5993856 as a guide.
Problem is I don't seem to be able to pick up messages. I tried to do the same socket.io("connect") followed by socket.request however it seems that request isn't part of the standard socket.io-client.
Hope this makes sense!
Cheers,

socket.io with express

i have a project and I'm using socket.io with express ,
so what i need (i tried) is broadcasting a message but from an express action.
is this possible i don't know how to get a reference to send or broadcast.
app.get('/', function(req, res) {
//i need to send messages from here
});
Other things like using both express+socket.io is working with me :)
As long as I understand,
Why not use the socket message type as an event instead of a http get or post? On the client side you would send a message via the websocket with let's say an event property.
So in your case:
<script>
// Initialize socket.io ...
// and then
socket.send({event: 'homepage loaded', foo: 'bar'});
</script>
And on the server side:
var io = io.listen(server);
io.on('connection', function (client) {
client.on('message', function (message) {
if (message.event == 'homepage loaded') {
client.broadcast(...);
}
});
});
You might want to have a look at my socket.io + Express primer. What you want is covered in detail there.
// Send to all connected sockets
io.sockets.send('Hello, World!');
// Send to all sockets in a specified room
io.sockets.in('room').send('Hello, Room!');
Where io is the value returned by the call to socketio.listen(). You can place that code anywhere in your application, eg in your app.get callbacks.
Check out my example repo where I use ExpressJS + Juggernaut(pubsub over socket.io):
http://github.com/shripadk/express-juggernaut-demo
This might be overkill for what you need as it uses Publish/Subscribe. But it does, to a certain extent, solve your issue of using regular ExpressJS routes. Checkout the master branch after cloning the repository:
git checkout master
I Found a nice example how to make what i need but with faye it's here http://nodecasts.org/.
I don't know the difference between Juggernaut ,Faye and direct Socket.io but Faye is good
for my case .And i think both of them use Socket.io internally.

Resources