Azure IoT Device: Type error in client.js - azure-iot-sdk

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.

Related

Using TwilioClient to execute Studio Flow from a Runtime Function

I have created a Twilio Studio Flow to make an outbound call that is triggered via REST API. I'd like to trigger this from a Twilio Runtime Function, but am having encountering errors when using the TwilioClient library.
Triggering the Studio Flow via the command line works successfully as follows:
curl -X POST "https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions" -d "To=+1XXXXXXXXX" -d "From=+1XXXXXXXXXX" -u ACCOUNT_SID:AUTH_TOKEN
But trying to do the equivalent via a Runtime Function fails:
exports.handler = function(context, event, callback) {
const twilioClient = context.getTwilioClient();
console.log(twilioClient.studio);
twilioClient.studio.flows('FWXXXXXXXXXXXXXXXXXXXXXXXXXX').executions.create({
to: '+1XXXXXXXXX',
from: '+1XXXXXXXXXX',
parameters: JSON.stringify({
name: "Client"
})
})
.then(function(execution) {
console.log(execution.sid);
callback(null, execution.sid);
})
.catch(error => {
console.error(`problem with request: ${error.message}`);
callback(error.message);
});
};
The error encountered is:
{ message: 'Cannot read property \'flows\' of undefined',
name: 'TypeError',
stack: 'TypeError: Cannot read property \'flows\' of undefined\n at Object.exports.handler (/var/task/handlers/ZF3ef70f4f38cfdf1c656da43214c01e18.js:6:19)\n at Object.exports.handler (/var/task/node_modules/enigma-lambda/index.js:306:10)\n at exports.handler (/var/task/enigma.js:17:9)' }
I have been playing around with it for a number of hours and don't seem to be any closer to a solution. Any help in pointing me in the right direction would be super appreciated!
Please make sure you are using a current version of the Twilio helper library. You can view your current versions under Twilio Functions, Configure: https://www.twilio.com/console/runtime/functions/configure (under: twilio), 3.6.3 is old.
The latest version can be found here:
https://github.com/twilio/twilio-node/releases (currently 3.31.0).

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

MQTT on Parse platform (Open source parse Server)

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()
});

Azure Notification Hub with Cordova app(iOS)

I'm trying to use Notification Hub to push Cordova app(iOS)
Azure side is as below.
Source code on client side is as below.
I'm sure Azure client is correctly connected and registration is successful.
function initPushNotification(){
var push = PushNotification.init({
android: {
senderID: "12345679"
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
});
var registrationSuccess = function () {
alert('Registered with Azure!');
};
var registrationFailure = function (error) {
alert('Failed registering with Azure: ' + error);
};
push.on('registration', function(data) {
client.push.apns.registerTemplate(handle,
'myTemplate', template, null)
.done(registrationSuccess, registrationFailure);
});
push.on('notification', function(data) {
alert('Push Received: ' + data.message);
});
push.on('error', function(e) {
alert(e.message);
});
But when I execute Test Send from notification hub page, nothing happens.
I tried from simple ruby script to APNS directly and notification comes to iPhone correctly.
Does anyone know how to fix it or any information?
My environment is
MacBook Pro
OS X ElCapitan
Cordova 6.0.0
com.microsoft.azure-mobile-services 1.2.9 "Windows Azure Mobile Services"
phonegap-plugin-push 1.6.2 "PushPlugin"
Most likely the call to client.push.register() is not succeeding for some reason. I'm not using the particular plugin you're using, I'm using azure-mobile-apps-cordova-client combined with phonegap-plugin-push. So far, this combination is working for my purposes.
You can find a more complete example here: Add Push Notifications to your Apache Cordova App.
One thing I would add is that when you call the push.register() API in the azure-mobile-apps-cordova-client plugin, you can give it an error function callback that gets called if the API call fails. It would look like this:
push.register('apns', data.registrationId, null, null, function(err)
{console.log(err);});
Lastly, in Visual Studio, you can also connect to your notification hub and list and manage the registrations. This is useful to determine if the APNS registration is really accepted.

Backbone Model from Hub in SignalR

How can i create/convert this script into model in Backbone that can use SignaR Hubs? For example:
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addMessage = function (message) {
alert("message");
};
// Start the connection
$.connection.hub.start();
});
</script>
EDIT
I did come up with this:
window.Message = Backbone.Model.extend({
hub: undefined,
initialize: function () {
this.hub = $.connection.message;
},
addMessage: function (message) {
alert(message);
},
connect: function () {
$.connection.hub.start();
var messages = this.hub.getAll();//get messages
}
});
but this is not working due to the following error:
this error: :55885 Unexpected response code: 200
If you use default settings SignalR will first try to send a websockets poll to the server. The :55885 is simply the port number of your server. Websockets protocol expects a response status code of 101 (see http://dev.w3.org/html5/websockets/).
If running IIS, unless you run Windows 8 with ASP.NET 4.5 your webserver, it will not recognize a web sockets request and (begin speculation) treat it as a normal get request and return status code 200 (OK) (end speculation) which is an unexpected response in the eyes of the websockets initiator. When this happens SignalR falls back to longpolling instead.
This might not answer your question but it will help you understand the error you get (which is likely not the reason why your code doesn't work)
Also, check out http://srtsolutions.github.com/backbone.signalr/ which is a Backbone.js/SignalR integration Nuget package.

Resources