how to display Commands results in IoT Central - Commands page?
Flow:
Command sent to Device
Device received the command and returns Payload:
{
"status": 200,
"payload": {
"command": "ping",
"result_code": "ok",
"result_data": "ping 5 ms"
}
}
How to display this data in IoT Central?
Now IoT Central shows only default "Sent at ..." message.
If you set a reported property with the same name as the command when you handle the command on the device, then you can set a value that displays in the IoT Central UI. For example, using Node.js you can create a handler for a countdown method like this:
function onCountdown(request, response) {
console.log('received a request for Countdown');
console.log(JSON.stringify(request.payload, null, 2));
var fakeResponsePayload = {
key: 'value'
};
response.send(200, fakeResponsePayload, function (err) {
if (err) {
console.error('Unable to send method response: ' + err.toString());
} else {
console.log('response to Countdown sent.');
client.getTwin(function(err, twin) {
if (err) {
console.error('could not get twin');
} else {
console.log('twin created');
var patch = {
countdown:{
value: 18
}
};
twin.properties.reported.update(patch, function(err) {
if (err) {
console.error('unable to update twin: ' + err.toString());
} else {
console.log('twin state reported');
}
});
}
});
}
});
}
client.onDeviceMethod('countdown', onCountdown);
Note that the name of the field name of the command is countdown.
There is also a C++ example here: https://github.com/Azure/iot-central-firmware/blob/master/MXCHIP/mxchip_advanced/src/registeredMethodHandlers.cpp
Related
Im using fcm-node i tried to send a push notification and it perfectly works locally, however when i try to send it using the server, it fails
var message = {
//this may vary according to the message type (single recipient, multicast, topic, et cetera)
to: notificationToken,
notification: {
bla bla
},
};
fcm.send(message, function (err, response) {
console.log("inside");
if (err) {
console.log("Something has gone wrong!", err);
} else {
console.log("Successfully sent with response: ", response);
}
});
Response for server:
Successfully sent with response: {
results: [ { error: [FirebaseMessagingError] } ],
canonicalRegistrationTokenCount: 0,
failureCount: 1,
successCount: 0,
multicastId: 502625035652113000
}
Tried to get the device notified
I'm successfully launching a webauthflow to an social OAuth provider from a service worker background script (as per manifest v3 requirements, background scripts are now full blown service workers)
However I'm unable to send a message back to my content script in what should be the simplest scenario.
Here is my service worker (background.js)
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "login") {
if (user_signed_in) {
console.log("already signed in");
} else {
chrome.identity.launchWebAuthFlow({
url: createOAuthEndpoint(),
interactive: true,
}, function (redirect_uri) {
if (chrome.runtime.lastError) {
sendResponse({
message: "fail"
});
} else {
if (redirect_uri.includes("error")) {
sendResponse({
message: "fail"
});
} else {
//we get here but this message is never sent
sendResponse({
message: "success",
profile: "blah"
});
}
}
});
}
}
return true;
});
And here is my content script...(popupsignin.js)
document.querySelector('#sign-in').addEventListener('click', () => {
chrome.runtime.sendMessage({ message: 'login' }, (response) => {
console.log('got the response'); //this log is never written
if (response.message === 'success'){
console.log(response.profile);
}
});
});
Turns out there was nothing wrong with code. There was(is) just nowhere for me to read the console.log(...) output in the callback method for some reason. I added an alert instead and it fired just fine.
Azure Notification Hub Exception: not able to register device entries.. the request could not be completed. we are using node js to register
You can use below code to register device entries.
Related posts and documents:
1. Issue with notification hub
2. createRegistrationId(callback)
/**
* Creates a registration identifier.
*
* #param {Function(error, response)} callback `error` will contain information
* if an error occurs; otherwise, `response`
* will contain information related to this operation.
*/
NotificationHubService.prototype.createRegistrationId = function (callback) {
validateCallback(callback);
var webResource = WebResource.post(this.hubName + '/registrationids');
webResource.headers = {
'content-length': null,
'content-type': null
};
this._executeRequest(webResource, null, null, null, function (err, rsp) {
var registrationId = null;
if (!err) {
var parsedLocationParts = url.parse(rsp.headers.location).pathname.split('/');
registrationId = parsedLocationParts[parsedLocationParts.length - 1];
}
callback(err, registrationId, rsp);
});
};
Using the azure-sb node.js module, you should be able to register a device and send to it directly. This requires a connection string and hub, as well as a device token, depending on the platform such as APNS.
import { NotificationHubService } from 'azure-sb';
const CONNECTION_STRING = ''; // Full Access Connection String
const HUB_NAME = ''; // Notification Hub Name
const APNS_TOKEN = ''; //APNS Token
const APNS_MESSAGE = {
aps: {
alert: "Notification Hub test notification"
}
};
service.apns.createNativeRegistration(APNS_REGISTRATION_ID, SAMPLE_TAG, (err, response) => {
if (err) {
console.log(err);
return;
}
console.log('Registration success');
console.log(JSON.stringify(response));
service.apns.send(SAMPLE_TAG, APNS_MESSAGE, (error, res) => {
if (error) {
console.log(error);
return;
}
console.log('Message sent');
console.log(JSON.stringify(res));
});
});
When this runs, it should register the device and send to it. I have run this very recently and works without a hitch. The older azure module might be tied to earlier TLS 1.0/1.1, which has since been deprecated for usage on Azure.
I am using MEAN Stack for our project. To generate pdf using pdfmake,
scenario goes like, At first have images from local server so every thing works fine. For scalibility have to move images to AWS and data from other server.
Now processs is like, first download images from aws then make buffer, convert it to base64 and give it to pdfmake. Now issue arises for client-server connection.
client makes http request for pdf, server process it but it takes too much time to download image from aws, so client connection breaks mean while
server processing the request and send response back but no one is there to listen.
/** client **/
function logicTriplogs() {
$rootScope.isLoading = true;
AssignsService.logicTriplogs({
driverId: vm.driver
}, {
_ids: vm.selectedTrips,
scheduleTime: vm.scheduleTime,
companyImage: vm.companyImage
},
function(response) {
console.log(response);
$rootScope.isLoading = false;
var Name = response.pdfName;
var data = response.content;
SaveFile.downloadURI(Name, data);
console.log('PDF Name:', Name);
},
function(err) {
console.log(err);
vm.error = err.data.message;
$rootScope.isLoading = false;
});
}
/** Server **/
getAssignedTripQuery(query, type)
.exec(function(err, assigns) {
if (err) {
console.log('Manifest');
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
if (assigns.length) {
logicMan(req.body, user, driver, assigns, function(docDefinition) {
var pdfName = `${moment_tz.tz(startDay, req.user.timeZone).format('MM-DD-YYYY')}.pdf`;
config.pdfBuffer(docDefinition, function(err, pdfDoc) {
console.log('EROROR PDF: ', err);
if (err) {
console.log('pdfmake function call error');
return res.status(400).send({
message: 'Error while generate pdf'
});
}
console.log('PDF Name:', pdfName);
return res.json({
message: 'Generated Susscessfuly',
pdfName: pdfName,
content: pdfDoc
});
});
});
} else {
return res.status(400).send({
message: 'Some thing went wrong. Please try later.'
});
}
});
I've got the following code that can send push notifications using Azure Notification Hubs. When a new item is inserted into the database, this code sends a push notification to the devices registered with the tag.
I'm using Ionic/Phonegap for the iOS app and the ngCordova Push Plugin. I want to add badge counts for iOS devices, but I can't seem to find a way to do this. I've tried using the push.apns.send function, but can't get it to work.
Azure Mobile Services
function insert(item, user, request) {
// Execute the request and send notifications.
request.execute({
success: function() {
// Create a template-based payload.
var payload = '{ "message" : "This is my message" }';
push.send("My Tag", payload, {
success: function(pushResponse){
// Send the default response.
request.respond();
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
// Send the an error response.
request.respond(500, { error: pushResponse });
}
});
}
});
}
Phonegap
var iosConfig = {
"badge": true,
"sound": true,
"alert": true
};
$cordovaPush.register(iosConfig).then(function (deviceToken) {
var hub = new NotificationHub(mobileClient);
// This is a template registration.
var template = "{\"aps\":{\"alert\":\"$(message)\"}}";
// Register for notifications.
// (deviceId, ["tag1","tag2"], templateName, templateBody, expiration)
hub.apns.register(deviceToken, myTags, "myTemplate", template, null).done(function () {
// Registered with hub!
}).fail(function (error) {
alert("Failed registering with hub: " + error);
});
}, function (err) {
alert("Registration error: " + err)
});
I've searched through dozens of articles/tutorials and none of them work. Any help would be greatly appreciated.
I finally figured it out. The issue was that the template registration needed to include the badge. Here's what works:
Azure Mobile Services
function insert(item, user, request) {
// Execute the request and send notifications.
request.execute({
success: function() {
// Create a template-based payload.
var payload = '{ "message" : "' + originalMessage + '", "badge" : "100" }';
push.send("My Tag", payload, {
success: function(pushResponse){
// Send the default response.
request.respond();
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
// Send the an error response.
request.respond(500, { error: pushResponse });
}
});
}
});
}
Phonegap
var iosConfig = {
"badge": true,
"sound": true,
"alert": true
};
$cordovaPush.register(iosConfig).then(function (deviceToken) {
var hub = new NotificationHub(mobileClient);
// This is a template registration.
var template = "{\"aps\":{\"alert\":\"$(message)\",\"badge\":\"#(badge)\" }}";
// Register for notifications.
// (deviceId, ["tag1","tag2"], templateName, templateBody, expiration)
hub.apns.register(deviceToken, myTags, "myTemplate", template, null).done(function () {
// Registered with hub!
}).fail(function (error) {
alert("Failed registering with hub: " + error);
});
}, function (err) {
alert("Registration error: " + err)
});