How to use the azure-iot-device.Message function in azure-iot-device

To help you get started, we’ve selected a few azure-iot-device examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Azure / azure-iot-sdk-node / device / samples / simple_sample_device_with_sas.js View on Github external
var sendInterval = setInterval(function () {
      var windSpeed = 10 + (Math.random() * 4); // range: [10, 14]
      var temperature = 20 + (Math.random() * 10); // range: [20, 30]
      var humidity = 60 + (Math.random() * 20); // range: [60, 80]
      var data = JSON.stringify({ deviceId: 'myFirstDevice', windSpeed: windSpeed, temperature: temperature, humidity: humidity });
      var message = new Message(data);
      message.properties.add('temperatureAlert', (temperature > 28) ? 'true' : 'false');      
      console.log('Sending message: ' + message.getData());
      client.sendEvent(message, printResultFor('send'));
    }, 2000);
github Azure-Samples / azure-iot-samples-node / iot-hub / Quickstarts / simulated-device / SimulatedDevice.js View on Github external
setInterval(function(){
  // Simulate telemetry.
  var temperature = 20 + (Math.random() * 15);
  var message = new Message(JSON.stringify({
    temperature: temperature,
    humidity: 60 + (Math.random() * 20)
  }));

  // Add a custom application property to the message.
  // An IoT hub can filter on these properties without access to the message body.
  message.properties.add('temperatureAlert', (temperature > 30) ? 'true' : 'false');

  console.log('Sending message: ' + message.getData());

  // Send the message.
  client.sendEvent(message, function (err) {
    if (err) {
      console.error('send error: ' + err.toString());
    } else {
      console.log('message sent');
github Azure / iotc-device-bridge / IoTCIntegration / lib / engine.js View on Github external
} else {
        throw new StatusError('Invalid format: a device specification must be provided.', 400);
    }

    if (!validateMeasurements(measurements)) {
        throw new StatusError('Invalid format: invalid measurement list.', 400);
    }

    if (timestamp && isNaN(Date.parse(timestamp))) {
        throw new StatusError('Invalid format: if present, timestamp must be in ISO format (e.g., YYYY-MM-DDTHH:mm:ss.sssZ)', 400);
    }

    const client = Device.Client.fromConnectionString(await getDeviceConnectionString(context, device), DeviceTransport.Http);

    try {
        const message = new Device.Message(JSON.stringify(measurements));

        if (timestamp) {
            message.properties.add('iothub-creation-time-utc', timestamp);
        }

        await util.promisify(client.open.bind(client))();
        context.log('[HTTP] Sending telemetry for device', device.deviceId);
        await util.promisify(client.sendEvent.bind(client))(message);
        await util.promisify(client.close.bind(client))();
    } catch (e) {
        // If the device was deleted, we remove its cached connection string
        if (e.name === 'DeviceNotFoundError' && deviceCache[device.deviceId]) {
            delete deviceCache[device.deviceId].connectionString;
        }

        throw new Error(`Unable to send telemetry for device ${device.deviceId}: ${e.message}`);
github Azure-Samples / iot-devkit-web-simulator / src / data / GetStarted / mockedSample.js View on Github external
function sendMessage() {
    if (!sendingMessage) { return; }
    var tempature = HTS221.getTempature();
    var humidity = HTS221.getHumidity();
    var messageObject = JSON.stringify({
        messageId: messageId,
        deviceId: 'Devkit playground',
        temperature: tempature,
        humidity: humidity
    });
    var message = new Message(messageObject);
    message.properties.add('temperatureAlert', (tempature > 30).toString());
    console.log("Sending message: " + messageObject);
    client.sendEvent(message, async function (err) {
        if (err) {
            console.error('Failed to send message to Azure IoT Hub');
        } else {
            await blinkSendConfirmation();
            console.log('Message sent to Azure IoT Hub');
        }
    });
    console.log("IoTHubClient accepted the message for delivery");
}
function onStart(request, response) {
github Azure / azure-iot-sdk-node / device / samples / module_send_event.js View on Github external
const generateImportantMessage = messageId => new Message(
    JSON.stringify({ 
        messageId : messageId,
        data : 'beep boop bopity bop',
    })
);
github codefoster / iot-workshop / device / index.js View on Github external
return new Promise((resolve, reject) => {
        let device = require('azure-iot-device');
        let message = new device.Message(content);
        client.sendEvent(message, (err, res) => {
            if (err) reject(err);
            resolve(res);
        });
    });
}
github codefoster / iot-workshop / device / index.ts View on Github external
.then(result => {
                                fs.unlinkSync('picture.png'); //delete the picture

                                //sending message to iot hub
                                log('sending message to iot hub...');
                                let message = new device.Message(JSON.stringify({ deviceId: 'device1', tags: ['foo', 'baz', 'bar'] }));
                                hubClient.sendEvent(message, (err, res) => {
                                    if (err) log(err.message);
                                    else {
                                        log(`Sent ${JSON.stringify(result.tags)} to your IoT Hub`);
                                        log('READY');
                                    }
                                    led.stop().off();
                                });
                            })
                            .catch(err => {
github microsoft / vscode-azure-iot-toolkit / src / simulator.ts View on Github external
private async sendD2CMessageCore(
    client: Client,
    message: any,
    status: SendStatus,
    totalStatus: SendStatus,
  ) {
    let stringify = Utility.getConfig(
      Constants.IoTHubD2CMessageStringifyKey,
    );
    await client.sendEvent(
      new Message(stringify ? JSON.stringify(message) : message),
      this.sendEventDoneCallback(
        client,
        Constants.IoTHubAIMessageDoneEvent,
        status,
        totalStatus,
      ),
    );
  }
github Azure / azure-iot-sdk-node / device / samples / send_batch_http.js View on Github external
data.forEach(function (value) {
  messages.push(new Message(JSON.stringify(value)));
});