Skip to content

Instantly share code, notes, and snippets.

@punitganshani
Created September 26, 2015 05:56
Show Gist options
  • Save punitganshani/c8e0be470ff7d7971cea to your computer and use it in GitHub Desktop.
Save punitganshani/c8e0be470ff7d7971cea to your computer and use it in GitHub Desktop.
Azure Event Hub HTTPS
console.log('started');
var https = require('https');
var crypto = require('crypto');
var moment = require('moment');
var uuid= require('node-uuid');
var os = require("os");
var deviceName = "galileo"; //os.hostname();
for (var counter = 0; counter < 5; counter++){
var payload = { MeasuredValue: randomInt(25, 29), DeviceName: deviceName, RecordedAt: new Date(), SensorType: "Temperature", MessageId: uuid.v4() }
SendTemperature(payload);
}
function SendTemperature(payload) {
var payLoadString = JSON.stringify(payload);
console.log(payLoadString);
// Event Hubs parameters
var namespace = 'your_servicebus_name';
var hubname ='your_eventhub_name';
// Shared access key (from Event Hub configuration)
var deviceKey = deviceName;
var deviceKeyValue = 'your_device_shared_access_token';
var my_uri = 'https://' + namespace + '.servicebus.windows.net' + '/' + hubname + '/messages';
function create_sas_token(uri, key_name, key)
{
// Token expires in one hour
var expiry = moment().add(1, 'hours').unix();
var string_to_sign = encodeURIComponent(uri) + '\n' + expiry;
var hmac = crypto.createHmac('sha256', key);
hmac.update(string_to_sign);
var signature = hmac.digest('base64');
var token = 'SharedAccessSignature sr=' + encodeURIComponent(uri) + '&sig=' + encodeURIComponent(signature) + '&se=' + expiry + '&skn=' + key_name;
return token;
}
var my_sas = create_sas_token(my_uri, deviceKey, deviceKeyValue)
var options = {
hostname: namespace + '.servicebus.windows.net',
port: 443,
path: '/' + hubname + '/messages',
method: 'POST',
headers: {
'Authorization': my_sas,
'Content-Length': payLoadString.length,
'Content-Type': 'application/atom+xml;type=entry;charset=utf-8'
}
};
var req = https.request(options, function(res) {
});
req.on('error', function(e) {
console.error(e);
});
req.write(payLoadString);
req.end();
}
function randomInt (low, high) {
return Math.floor(Math.random() * (high - low) + low);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment