MQTT on Parse platform (Open source parse Server) - mqtt

Hi I am using the hosted version of the open source parse platform (hosed version on Back4app) for my IoT project. Am using HTTP (REST) Api to communicate with the parse server and upload data. Does anyone know if it is possible to use the MQTT protocol instead of HTTP for the same with the parseplatform. I couldn't find any relevant doc for this. Apparently there's a way to install the MQTTjs on cloud code section of the platform but do not know if this really works ... Thanks in advance

Yes, it's possible, I just tested it now and it worked for me. Here are the steps that you need to follow:
1 - You only need to install this npm module as you can see at this guide.
Here is my package.json:
{
"dependencies": {
"mqtt": "2.18.8"
}
}
2 - After that, on Back4app, you need to upload the code in your cloud code and check your Server System Logs at Server Settings > Logs > Settings.
Here's a simple code that you can use to test it. I put this code in my main.js:
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
client.subscribe('presence', function (err) {
if (!err) {
client.publish('presence', 'Hello mqtt')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
});

Related

How to use Websocket (socket.io) with Ruby?

I need to implement WebSocket synchronization in our Rail project. MetaApi project's use Socket.Io as default support. Only found 2 projects (websocket-client-simple) and outdated with native socket.io. We try to implement this with Faye-Websocket and socketcluster-client-ruby but without success.
Code Example
import ioClient from 'socket.io-client';
const socket = ioClient('https://mt-client-api-v1.agiliumtrade.agiliumtrade.ai', {
path: '/ws',
reconnection: false,
query: {
'auth-token': 'token'
}
});
const request = {
accountId: '865d3a4d-3803-486d-bdf3-a85679d9fad2',
type: 'subscribe',
requestId: '57bfbc9f-108d-4131-a300-5f7d9e69c11b'
};
socket.on('connect', () => {
socket.emit('request', request);
});
socket.on('synchronization', data => {
console.log(data);
if (data.type === 'authenticated') {
console.log('authenticated event received, you can send synchronize now');
}
});
socket.on('processingError', err => {
console.error(err);
});
Socket.io protocol is a bit more complicated than a simple websocket connection, with the latter being only one of the used transports, see description in official repository. Websockets are used only after initial http handshake, so you need a somewhat full client.
I'd start with trying to consume events with a js client stub from browser, just to be sure the api is working as you expect and determine used and compatible socket.io versions (current is v4, stale ruby clients are mostly for v1). And you can peek into protocol in browser developer tools.
Once you have a successful session example and have read protocol spec above - it will be easier to craft a minimal client.

Ktor-websocket library do nothing when trying to receive data on client

I am currently trying to connect our Kotlin Multiplatform Project to websockets. I would like to use ktor-websockets library to receive some updates from our backend but onfortunately when I run this code, nothing happens:
client.webSocket(
port = 80,
method = HttpMethod.Get,
host = "https://uat-betws.sts.pl",
path = "/ticket?token=eyJzdWIiOiI0ZmY5Y2E1Mi02ZmEwLTRiYWYtODlhYS0wODM1NGE2MTU0YjYiLCJpYXQiOjE2MTk4MDAwNzgsImV4cCI6MTYxOTgwMzY3OH0.oIaXH-nFDpMklp4FSJWMtsM7ECSIfuNF99tTQxiEALM"
)
{
for (message in incoming) {
message as? Frame.Text ?: continue
val receivedText = message.readText()
println(receivedText)
}
// Consume all incoming websockets on this url
this.incoming.consumeAsFlow().collect {
logger.d("Received ticket status websocket of type ${it.frameType.name}")
if (it is Frame.Text) {
Json.decodeFromString<TicketStatusResponse>(it.readText())
}
}
}
Does somebody have any experience with ktor-websockets library? There is almost no documentation so maybe I am doing something wrong.
Thank you
As the documentation says
Ktor provides Websocket client support for the following engines: CIO, OkHttp, Js.
This means that it works only on JVM/JS, you're probably targeting iOS. It's not yet supported, you can follow issue KTOR-363 for updates
For sure the team is working on it, but for now you had to implement it by yourself using expect/actual, you can check out official example
An other possible problem in your code: host shouldn't include https://, if you're using ssl, you should add an other parameter:
request = {
url.protocol = URLProtocol.WSS
}
Or use client.wss(...) - which is just a short form for the same operation

Call Graph API from SharePoint

I need to call Graph API from spfx webpart.
Previously we used the following method:
import { MSGraphClient } from '#microsoft/sp-client-preview';
But later we got to know that MSGraphClient is depreciated now in sp-client-preview.
I checked the following method which is mentioned in Microsoft docs also.
import { MSGraphClient } from '#microsoft/sp-http';
But it is giving an error as following:
Module '"d:/O365/upload-onedrive/node_modules/#microsoft/sp-http/dist/index-internal"' has no exported member 'MSGraphClient'
SPFx version we are using now is 1.6
Is there any way call Graph API from spfx now?
Of course we can use Graph in SPFx.
Graph+adal+SPFx steps:
Create an application in Azure portal. Click the manifest, then change "oauth2AllowImplicitFlow" value to true
Go to Settings->Required Permissions->ADD->Select an API->Microsoft Graph, select the permission and then Grant Permissions.
Build HelloWorld SPFx project : https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part
Add and IAdalConfig.ts and WebPartAuthenticationContext.js patch files
Tips: If you have no adal module in node_modules/#types folder, you'd better manually install the module using the command : npm install #types/adal#1.0.29
Add the following code to render()
// Make an AJAX request to the Graph API and print the response as JSON.
var getToken;
var getCurrentUser = function (access_token) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://graph.microsoft.com/v1.0/me', true);
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Do something with the response
getToken=JSON.stringify(JSON.parse(xhr.responseText), null, ' ');
console.log('get Graph APi information=='+getToken);
} else {
// TODO: Do something with the error (or non-200 responses)
// console.log(' error');
}
};
xhr.send();
There is actually no reason to create any applications in the Azure side, it's all automatic and taken care of by SharePoint. See following documentation for details. We did change the API structure slightly between preview and GA, but the basics have remained the same with MSGraphClient usage and no reason for any manual access token handling.
https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-msgraph

Azure IoT Device: Type error in client.js

I try to get an ARM device connected to Azure IoT Hub. I chose Node.js and got some sample code to get the device connected. I added the required NPM packages such as azure_iot_device, azure_iot_common, azure_iot_http_base.
Within the code, there is one line of code which causes an error.
The line: client.sendEvent(message, printResultFor('send'));
After this, on the debugging console I get the message:
\NodejsWebApp1\node_modules\azure-iot-device\lib\client.js:596
return new Client(new transportCtor(authenticationProvider), null, new blob_upload_1.BlobUploadClient(authenticationProvider));
^
TypeError: transportCtor is not a function
at Function.Client.fromConnectionString
(C:\Users\InterestedGuy\source\repos\NodejsWebApp1\NodejsWebApp1\node_modules\azure-iot-device\lib\client.js:596:27)
at sendmsg (C:\Users\InterestedGuy\source\repos\NodejsWebApp1\NodejsWebApp1\server.js:123:32)
at Server. (C:\Users\InterestedGuy\source\repos\NodejsWebApp1\NodejsWebApp1\server.js:48:9)
at emitTwo (events.js:87:13)
at Server.emit (events.js:172:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:529:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23)
Press any key to continue...
First guess was that I miss a library so I simply searched the Web where transportCtor should have been defined - but no success.
So the easy question is: where should this function be defined? I would expect the function is part of the Azure IoT SDK but I could not find it. Since the module client.js from azure_iot_device is reporting the error I expect it somewhere within the SDK - but where?
THX for any advice
You should install azure-iot-device-http package to communicate with Azure IoT Hub from any device over HTTP 1.1. You can use this command to get the latest version.
npm install -g azure-iot-device-http#latest
Following code is a tutorial shows how to use this package.
var clientFromConnectionString = require('azure-iot-device-http').clientFromConnectionString;
var Message = require('azure-iot-device').Message;
var connectionString = '[IoT Hub device connection string]';
var client = clientFromConnectionString(connectionString);
var connectCallback = function (err) {
if (err) {
console.error('Could not connect: ' + err);
} else {
console.log('Client connected');
var message = new Message('some data from my device');
client.sendEvent(message, function (err) {
if (err) console.log(err.toString());
});
client.on('message', function (msg) {
console.log(msg);
client.complete(msg, function () {
console.log('completed');
});
});
}
};
client.open(connectCallback);
BTW,for this tutorial you also need to install azure-iot-device package.

Can't connect to server with socket.io on both client and server

I just started building me server using socket.io for both my client and Node.js server side.
I'm writing an Objective-c project so i walk through the process of adjusting my project to use Swift alongside with Objective-c which was a pain but it seems to be ok now.
The thing is, when i try to do a simple connect to my server, which prints to log on each connection, nothing happens.
This is the code for the server (Taken from here):
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
console.log('Connected');
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
Super simple, really nothing to it.
And the Objective-c code for my client which is even more simple:
- (void) connect
{
SocketIOClient* client = [[SocketIOClient alloc]initWithSocketURL:#"http://127.0.0.1:8080/" options:nil];
[client connect];
}
But i can't see nothing on my console except the Listening at: http://localhost:8080 message.
I can't seem to find what i'm doing wrong here, and the fact that the swift debugging is horrible in this combined project, i can't really fully go through the socket.io debugging myself (but i'm pretty sure nothing's wrong with their code)
Any help would be much appreciated.
plz confirm, if you are using the simulator for iOS testing. For device, you need to assign public address to your NodeJS server, and then need to use it's ip in iOS Codebase.
I had used https://github.com/pkyeck/socket.IO-objc during my last project and it worked like a charm.
For simulator, your code should ideally work.

Resources