I had created a module to receive cloud to device message, but no message was received on the module, is there any coding I missing?
var Transport = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').ModuleClient;
Client.fromEnvironment(Transport, function (err, client) {
if (err) {
throw err;
} else {
client.on('error', function (err) {
throw err;
});
// connect to the Edge instance
client.open(function (err) {
if (err) {
throw err;
} else {
console.log('IoT Hub module client initialized');
client.on('message', function (msg) {
client.complete(msg, printResultFor('Receiving message'));
var message = msg.getBytes().toString('utf8');
console.log('----');
console.log(message);
console.log('----');
var outputMsg = new Message(message);
client.sendOutputEvent('output1', outputMsg, printResultFor('Sending received message'));
});
client.on('error', function (err) {
console.error(err.message);
});
console.log('now listening for C2D messages...');
}
});
}
});
Monitor
[C2DMessageMonitor] Message Received: "[{\"machine\":{\"temperature\":40.750164436176497,\"pressure\":1.0854617712099808},\"ambient\":{\"temperature\":40.450729128416036,\"humidity\":26},\"timeCreated\":\"2018-08-06T13:28:52.0375008Z\"}]"
[C2DMessageMonitor] Status: MessageCompleted
C2D messages are not yet officially supported by IoT edge. It may work for some protocols as the support is being built out but nothing has been validated at this time.
Related
Facing issue while adding the non chat participants using the JS SDK in twilio conversation
I have done following things to add the non chat participants in the JS SDK
Twilio.Conversations.Client.create(token).then(client => {
console.log(client);
client.on("stateChanged", (state) => {
if (state === "failed") {
console.log("fail");
// The client failed to initialize
return;
}
if (state === "initialized") {
console.log("init");
// Use the client
}
});
client.createConversation().then(async function(conversation) {
console.log(conversation, 'conversation');
await conversation.join();
const proxyAddress = "twilio number";
const address = "phone Number";
const attributes = {
identity: address
};
const messeges = await conversation.getMessages();
console.log(messeges, 'messeges')
conversation.addNonChatParticipant(proxyAddress, address, attributes).then(function(a) {
console.log(a, 'a');
}).catch(function(err) {
console.log(err, 'while adding the Participant');
});
}).catch(function(err) {
console.log(err, 'con');
});
});
It gives me following and its not that much explained anywhere. moreover I got the client object and the conversation object as well but after that I can't add Participant
Error: Conflict at e.<anonymous> (twilio-conversations.min.js:129:209472)at Qc (twilio-conversations.min.js:129:30955)at Generator._invoke (twilio-conversations.min.js:129:30737)at forEach.e.<computed> [as next] (twilio-conversations.min.js:129:31399)at t (twilio-conversations.min.js:129:117709)at o (twilio-conversations.min.js:129:117920) 'while adding the Participant'
after a lot of investigation i have no clue of what could be the problem here. I have an iOS app developed with cordova and using Firebase (cordova-plugin-firebase) for notifications.
When i run my app on my device with Xcode for the first time everything works fine, the notifications arrive and the app works great. The problem starts when i stop the app on Xcode and try to open it on my device without using Xcode, the app crashes on the splash screen. If i send any notification, it arrives with no issue, but when i open one notification the app just crashes on the splash screen again.
I have created all certificates and the development, production and ad-hoc provisioning profiles on my apple developer account, created and APNs Key to store on my Firebase Account, I have the file GoogleService-Info.plist on my Resources folders (platforms/ios/AppName/Resources & platforms/ios/AppName/Resources/Resources).
The only error that i can see on my log is this one
Unable to connect to FCM. Error Domain=com.google.fcm Code=2001 "FIRMessaging is already connected"
and this one
The object does not respond to -messaging:didReceiveRegistrationToken:, nor -messaging:didRefreshRegistrationToken:. Please implement -messaging:didReceiveRegistrationToken: to be provided with an FCM token.
This errors are shown when i accept the notification permission bubble.
Here is my JS for handling notifications:
function firebasePUSH() {
if (device.platform === "iOS") {
window.FirebasePlugin.hasPermission(function (data) {
if (!data.isEnabled) {
window.FirebasePlugin.grantPermission();
}
});
}
window.FirebasePlugin.onNotificationOpen(function (notification) {
console.log("tipo de notificacion " + notification.tipo);
console.log(notification);
if (notification.tipo === "alerta") {
var parametros = {
id: notification.numero,
categoria: "rescato"
};
myApp.request.post("http://190.98.210.41/comuna/app/contactos.php", parametros, function (data) {
var json = JSON.parse(data);
console.log(json);
if (json.error === false) {
mostrarSOS(json.alerta);
}
});
} else if (notification.tipo === "chat" || notification.tipo === "salud" || notification.tipo === "seguridad" || notification.tipo === "contacto" || notification.tipo === "oficina") {
aceptarLlamada();
} else if (notification.tipo === "publicidad") {
mostrarPublicidad(notification.numero);
} else if (notification.tipo === "sondeo") {
mostrarSondeo(notification.numero);
}
}, function (error) {
console.error("onResume>>" + error);
});
window.FirebasePlugin.getToken(function (token) {
try {
var jsonToken = JSON.parse(token);
token = jsonToken.token;
console.warn("venia json: " + jsonToken.token);
}
catch (err) {
console.warn("viene json limpio: " + token);
}
console.log("getToken js: " + token);
localStorage.setItem('registrationId', token);
/*PEGRUNTA SI YA ESTA LOGEADO*/
if (localStorage.getItem("correo") !== null && localStorage.getItem("clave") !== null) {
//pasa a la pantalla principal
var parametros = {
"id": localStorage.getItem("id"),
"token": localStorage.getItem('registrationId'),
"categoria": "token",
format: "json",
callback: function () {
return true;
}
};
myApp.request.json("http://190.98.210.41/comuna/app/usuario_get.php", parametros, function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
}
}, function (error) {
console.error("getToken error: " + error);
});
window.FirebasePlugin.onTokenRefresh(function (token) {
try {
var jsonToken = JSON.parse(token);
token = jsonToken.token;
console.warn("token json: " + jsonToken.token);
}
catch (err) {
console.warn("token limpio: " + token);
}
console.log("onTokenRefresh js: " + token);
localStorage.setItem('registrationId', token);
/*PEGRUNTA SI YA ESTA LOGEADO*/
if (localStorage.getItem("correo") != null && localStorage.getItem("clave") != null) {
//pasa a la pantalla principal
var parametros = {
"id": localStorage.getItem("id"),
"token": localStorage.getItem('registrationId'),
"categoria": "token",
format: "json",
callback: function () {
return true;
}
};
myApp.request.json("http://190.98.210.41/comuna/app/usuario_get.php", parametros, function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
}
}, function (error) {
console.error(error);
});
}
I could use some help on this issue because i have been on this for weeks and i'm getting so frustrated. Thank you very much guys.
EDIT:
I spotted a third error when i launch the app.
[Firebase/Messaging][I-FCM002023] The object does not respond to -messaging:didReceiveRegistrationToken:, nor -messaging:didRefreshRegistrationToken:. Please implement -messaging:didReceiveRegistrationToken: to be provided with an FCM token.
I had a problem very similar..
and I discovered that the problem was when i called window.FirebasePlugin.grantPermission() in second time.
do one test without asking permission more than once..
I try to push a file to the IPFS, and I have converted to the Buffer. I got this error " content.once is not a function".
I am using this library in node.
var Buffer = require('buffer/').Buffer;
const doc = new jsPDF();
doc.fromHTML('test',10,10);
var covnertedBuffer = Buffer.from(doc.output('arraybuffer');
Then, I take the convertedBuffer and pass it to the IPFS api.
Any idea?
Updated test:
I have successfully pushed a file to the IPFS via the API with this code below.
const filename = '/home/administrator/Downloads/5HP8LWKHLV.pdf';
this.ipfsApi = ipfsApi('localhost', '5001');
let readablestream = fs.createReadStream(filename);
readablestream.on('readable', () => {
let result = readablestream.read();
console.log(result);
if (result) {
this.ipfsApi.files.add(result, function(err, files) {
if (err) {
res.json('err');
console.log(err);
}
res.json(files);
});
}
});
But, when I get the arrayBuffer from the doc.output and convert to the Buffer object and push to the IPFS and it failed. Please see below.
var _buffer = Buffer.from(req.buffer);
console.log('Converted to buffer:' + _buffer);
this.ipfsApi = ipfsApi('localhost', '5001');
this.ipfsApi.files.add(_buffer, function(err, files) {
if (!err) {
res.status(500);
console.log(err);
} else {
res.json(files);
res.status(200);
}
});
Thank you
Adding Buffer.from(your_buffer) to your buffer before doing ipfs push works.
ipfs.files.add(Buffer.from(put_your_buffer_here), (error, result) => {
if(error) {
console.error(error)
return
}
console.log("upload is successful");
});
I'm facing some very strange memory issues since a couple of days.
The problem is, that ocassionally the apps is stuck and starts to increase the memory usage very fast until it crashes. While the memory is increasing, the app is freezing completly.
After some debugging I identified that this code is causing the error:
angular.module('app.shared').factory('PushNotificationService', PushNotificationService);
PushNotificationService.$inject = [
'$q',
'MessagingService'
];
function PushNotificationService($q, MessagingService) {
var me = this;
initialize();
return {
getStartupMessage: getStartupMessage,
fetchToken: fetchToken
};
/**
* Constructor
* #return {[type]} [description]
*/
function initialize() {
me.pusher = null;
me.deviceToken = null;
me.startupMessage = null;
}
/**
* Fetches the push token through device interface
*
* #return {$q} Promises
*/
function fetchToken() {
if (me.pusher != null) {
return $q(function(resolve, reject) {
console.log('PushService.fetchToken(): Got pusher', me.pusher);
// when pusher was already initialized, we do not need to fetch it again
console.log('PushService.fetchToken(): Token was already retrieved', me.deviceToken);
resolve(me.deviceToken);
});
}
console.log('PushService.fetchToken(): Needs to fetch token bc not retrieved yet');
return $q(function(resolve, reject) {
document.addEventListener('deviceready', function() {
console.log('PushService.fetchToken(): Device is ready', typeof resolve, typeof reject);
resolve(true);
}, false);
}).then(function() {
console.log('PushService.fetchToken(): No pusher retrieved yet, do it now');
return __initialize();
}).then(function(push) {
console.log('PushService.fetchToken(): Got pusher and start attaching events to it', push);
return $q(function(resolve, reject) {
push.on('error', function(error) {
console.log('PushNotificationService.fetchToken(): Error while retrieving token', error.message, error);
reject(error);
});
push.on('registration', function(data) {
console.log('PushNotificationService.fetchToken(): Successfully retrieved token', data);
me.deviceToken = data.registrationId;
resolve(data.registrationId);
});
console.log('PushNotificationService.fetchToken(): Eventhandlers of pusher', push._handlers);
});
});
}
/**
* Initializes the push notifications and tries to fetch the Push token
* #return {Cordova.Pusher} [description]
*/
function __initialize() {
me.pusher = PushNotification.init({
android: {
senderID: "288503736094"
},
ios: {
alert: true,
badge: true,
sound: true,
clearBadge: true
},
windows: {}
});
me.pusher.on('notification', __incomingNotification);
return me.pusher;
}
// additional code which is not relevant here...
// .....
// .....
}
It happens only on iOS and is completly random, there is no way of finding a system in the crashes.
Debugging log looks like that:
PushService.fetchToken(): Needs to fetch token bc not retrieved yet
PushService.fetchToken(): Device is ready function function
PushService.fetchToken(): No pusher retrieved yet, do it now
PushService.fetchToken(): Got pusher and start attaching events to it {"_handlers":{"registration":[],"notification":[null],"error":[]},"options":{"android":{"senderID":"288503736094"},"ios":{"alert":true,"badge":true,"sound":true,"clearBadge":true},"windows":{}}}
PushNotificationService.fetchToken(): Eventhandlers of pusher {"registration":[null],"notification":[null],"error":[null]}
It was an issue in the cordova-ios which caused massive memory leaks in random locations.
Upgrading to latest version fixed it!
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);
});
}
});