Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async function doInit() {
const IOT_HUB_CONNECTION_STRING = getEnvironmentVariable('IOT_HUB_CONNECTION_STRING');
registry = Registry.fromConnectionString(IOT_HUB_CONNECTION_STRING);
const client = await EventHubClient.createFromIotHubConnectionString(IOT_HUB_CONNECTION_STRING);
const hubInfo = await client.getHubRuntimeInformation();
console.log(`Connected to IoT Hub at ${hubInfo.path}`);
client.receive(
'1',
(eventData) => { // on 'message
if (eventData.annotations) {
const enqueuedTime = eventData.annotations['x-opt-enqueued-time'];
console.debug(`Received message from IoT Hub, enqueued at ${enqueuedTime}`);
} else {
console.debug(`Received message from IoT Hub`);
}
updateState(eventData.body);
},
(error) => {
console.error(`Error receiving message from Event Hubs: ${error}`);
const run = async() => {
try {
console.log('Initializing Module Client.');
const moduleClient = ModuleClient.fromConnectionString(process.env.DEVICE_CONNECTION_STRING, Mqtt);
// We use the iot hub connection string to create the client rather than the actual event hub end point
console.log('Initializing Event Hub Client.');
const eventHubClient = await EventHubClient.createFromIotHubConnectionString(process.env.IOTHUB_CONNECTION_STRING);
console.log('Initializing HTTP Device Client.');
const httpClient = HttpClientFromConnectionString(process.env.DEVICE_CONNECTION_STRING);
console.log('Initialized clients!');
console.log('Getting information from Event Hub.');
const partitionIds = await eventHubClient.getPartitionIds(); //read more about partitions https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-features#partitions
const startingPosition = EventPosition.fromEnqueuedTime(Date.now() - 1000); //subtracting a second to account for delay
const eventLabel = 'beepBoop'; //label our events
const sendDummyMessage = m => moduleClient.sendOutputEvent(eventLabel, m); //send helper
console.log('Creating messages to send to via Module Client');
//generate some messages
const messageCount = 10;
const importantMessages = [...Array(messageCount).keys()].map(generateImportantMessage);
// - The device can add arbitrary application properties to the message
// - IoT Hub adds system properties, such as Device Id, to the message.
var printMessage = function (message) {
console.log('Telemetry received: ');
console.log(JSON.stringify(message.body));
console.log('Application properties (set by device): ')
console.log(JSON.stringify(message.applicationProperties));
console.log('System properties (set by IoT Hub): ')
console.log(JSON.stringify(message.annotations));
console.log('');
};
// Connect to the partitions on the IoT Hub's Event Hubs-compatible endpoint.
// This example only reads messages sent after this application started.
var ehClient;
EventHubClient.createFromIotHubConnectionString(connectionString).then(function (client) {
console.log("Successfully created the EventHub Client from iothub connection string.");
ehClient = client;
return ehClient.getPartitionIds();
}).then(function (ids) {
console.log("The partition ids are: ", ids);
return ids.map(function (id) {
return ehClient.receive(id, printMessage, printError, { eventPosition: EventPosition.fromEnqueuedTime(Date.now()) });
});
}).catch(printError);
static async createFromIotHubConnectionString(
hostName: string,
storageConnectionString: string,
storageContainerName: string,
iotHubConnectionString: string,
options?: FromIotHubConnectionStringOptions
): Promise {
if (!options) options = {};
validateType("hostName", hostName, true, "string");
validateType("storageConnectionString", storageConnectionString, true, "string");
validateType("storageContainerName", storageContainerName, true, "string");
validateType("iotHubConnectionString", iotHubConnectionString, true, "string");
validateType("options", options, false, "object");
const client = await EventHubClient.createFromIotHubConnectionString(iotHubConnectionString);
/* tslint:disable:no-string-literal */
const eventHubConnectionString = client["_context"].config.connectionString;
const ephOptions: EventProcessorHostOptions = {
...options,
storageConnectionString: storageConnectionString,
storageContainerName: storageContainerName,
eventHubConnectionString: eventHubConnectionString,
eventHubPath: client.eventhubName
};
return new EventProcessorHost(hostName, ephOptions);
}
serviceConnection.open(function(err) {
if (err) {
logger.fatal('Unable to open connection to Eventhub: ' + err.message);
return;
}
logger.trace('Test service open.');
EventHubClient.createFromIotHubConnectionString(iothubConnectionString)
.then(function (ehClient) {
eventHubConnection = ehClient;
return eventHubConnection.getPartitionIds();
})
.then(function (partitionIds) {
return partitionIds.map(function (partitionId) {
eventHubConnection.receive(
partitionId,
messageReceivedCb,
errorCb,
{
consumerGroup: consumerGroup,
eventPosition: EventPosition.fromEnqueuedTime(Date.now())
}
);
return null;
const onEventHubError = (err) => {
throw err;
};
const onEventHubMessage = (receivedMsg) => {
debug('EH Client: Message received');
if (uuidBuffer.toString(receivedMsg.properties.message_id) === testMessage.messageId) {
debug('EH Client: Message OK');
receiveOK = true;
if (sendOK && receiveOK) {
ehClient.close()
.then(() => testCallback());
}
}
};
EventHubClient.createFromIotHubConnectionString(process.env.IOTHUB_CONNECTION_STRING)
.then((client) => ehClient = client)
.then(() => ehClient.getPartitionIds())
.then((partitionIds) => {
partitionIds.forEach((partitionId) => {
ehClient.receive(partitionId, onEventHubMessage, onEventHubError, { eventPosition: EventPosition.fromEnqueuedTime(startAfterTime) });
});
return new Promise((resolve) => setTimeout(() => resolve(), 3000));
}).then(() => {
debug('EH Client: Receivers created');
const deviceClient = DeviceClient.fromConnectionString(testDeviceCS, transportCtor);
deviceClient.sendEvent(testMessage, (sendErr, result) => {
if (sendErr) throw sendErr;
debug('Device Client: Message sent');
assert.instanceOf(result, results.MessageEnqueued);
sendOK = true;
if (sendOK && receiveOK) {
function startHub(options) {
return EventHubClient.createFromIotHubConnectionString(
options.connectionString
)
.then(client => (ehClient = client))
.then(() => ehClient.getPartitionIds())
.then(partitionIds => filterPartitions(options, partitionIds))
.then(partitionIds => generateReceivers(options, partitionIds));
}
this.outputLine(Constants.IoTHubMonitorLabel, "There is a running job to monitor built-in event endpoint. Please stop it first.");
return;
}
let iotHubConnectionString = await Utility.getConnectionString(Constants.IotHubConnectionStringKey, Constants.IotHubConnectionStringTitle);
if (!iotHubConnectionString) {
return;
}
let config = Utility.getConfiguration();
let consumerGroup = config.get(Constants.IoTHubConsumerGroup);
try {
this._outputChannel.show();
const deviceLabel = deviceItem ? `device [${deviceItem.deviceId}]` : "all devices";
this.outputLine(Constants.IoTHubMonitorLabel, `Start monitoring message arrived in built-in endpoint for ${deviceLabel} ...`);
this._eventHubClient = await EventHubClient.createFromIotHubConnectionString(iotHubConnectionString);
TelemetryClient.sendEvent(Constants.IoTHubAIStartMonitorEvent, { deviceType: deviceItem ? deviceItem.contextValue : "" });
await this.startMonitor(Constants.IoTHubMonitorLabel, consumerGroup, deviceItem);
this.updateMonitorStatus(true);
} catch (e) {
this.updateMonitorStatus(false);
this.outputLine(Constants.IoTHubMonitorLabel, e);
TelemetryClient.sendEvent(Constants.IoTHubAIStartMonitorEvent, { Result: "Exception", Message: e });
}
}