Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

AzureのIoT系をつかう その7:実物RasPiからデータを送る

実際のところ

shuzo-kino.hateblo.jp
でデバイス登録とRasPiにIoT Hub用のnodeJs環境が構築されている状態を想定します。

config.json

{
    "connectionString": "Your Primary Connection String Here",
    "interval": 2000
}

index.js(node.js版)

const fs = require('fs');
const device = require('azure-iot-device');
const Mqtt = require('azure-iot-device-mqtt').Mqtt;
let config;

try {
    config = JSON.parse(fs.readFileSync('config.json', 'utf8'));
} catch (err) {
    console.error("Failed to load config.json", err);
    process.exit(1);
}

const connectionString = config.connectionString;
let interval = config.interval || 2000;
let messageID = 0;

if (isNaN(interval) || interval < 0) {
    console.error("Invalid sendInterval value in config.json");
    process.exit(1);
}

const client = device.Client.fromConnectionString(connectionString, Mqtt);

setInterval(() => {
    const messageJson = JSON.stringify({
        deviceId: "RP3",
        messageId: messageID++,
        value: Math.floor(Math.random() * 256)
    });

    const message = new device.Message(messageJson);
    client.sendEvent(message, (err) => {
        if (err) {
            console.error('Failed to send message to Azure IoT Hub', err);
        } else {
            console.log('Message sent to Azure IoT Hub');
        }
    });
}, interval);

sendData2AzureIoT.py(Python3版)

$ pip install azure-iot-device
import json
import time
import random
from azure.iot.device import IoTHubDeviceClient, Message

# Load connection string from config
with open('config.json') as f:
    config = json.load(f)

CONNECTION_STRING = config['connectionString']
MESSAGE_TIMEOUT = config['interval'] or 2000

def iothub_client_init():
    # Connect to the IoT Hub
    client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
    return client

def send_message_to_hub(client, msg_id):
    value = random.randint(0, 255)
    msg_txt_formatted = json.dumps({"messageId": msg_id, "value": value, "deviceId": "RP3"})
    message = Message(msg_txt_formatted)

    # Send the message.
    print("Sending message: {}".format(message))
    client.send_message(message)
    print("Message sent")

def main():
    print("Starting the IoT Hub Python sample using protocol MQTT...")
    print("IoT Hub Device sending periodic messages")

    client = iothub_client_init()

    message_id = 0
    while True:
        send_message_to_hub(client, message_id)
        message_id += 1
        time.sleep(MESSAGE_TIMEOUT / 1000)

if __name__ == "__main__":
    main()