-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (63 loc) · 1.89 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env node
/* eslint-disable */
const eventHub = require('@azure/event-hubs');
const { EventHubClient, EventPosition } = eventHub;
const yargs = require('yargs');
const argv = yargs
.usage('$0 <cstr> [options]', 'Listen to Azure IoT Hub device events.', (yargs) => {
yargs.positional('cstr', {
describe: 'Azure IoTHub connection string',
type: 'string'
})
} )
.options({
'verbose': {
alias: 'v',
description: 'More verbose logging',
type: 'boolean'
}
})
.epilog('Copyright Euricom 2020')
.argv;
if (!argv.cstr.startsWith('HostName=') || !argv.cstr.includes('SharedAccessKeyName')) {
yargs.showHelp();
console.log();
console.log('ERROR: Bad or invalid connection string, must start with "HostName=');
process.exit(-1);
}
listenForMessages()
.then(() => {
console.log('Listening to Azure IoTHub events... (ctrl-c to quit)');
})
.catch((err) => {
console.log('ERROR:', err.message);
process.exit(-1);
});
async function listenForMessages() {
const eventHubClient = await EventHubClient.createFromIotHubConnectionString(argv.cstr, 'ntt-event-hub');
return listen(eventHubClient, (eventData, err) => {
if (err) {
console.log('ERROR', err);
}
const deviceId = eventData.annotations['iothub-connection-device-id'];
if (argv.verbose) {
console.log(`Event from '${deviceId}': `, eventData);
} else {
console.log(`Event from '${deviceId}': `, eventData.body);
}
});
}
async function listen(eventHubClient, callback) {
const partitionIds = await eventHubClient.getPartitionIds();
function onMessage(eventData) {
callback(eventData, null);
}
function onError(error) {
callback(null, error);
}
partitionIds.forEach((partitionId) => {
eventHubClient.receive(partitionId, onMessage, onError, {
eventPosition: EventPosition.fromEnqueuedTime(Date.now()),
});
});
}