Bye Bye Moore

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

AzureのIoT系をつかう その8:実物RasPiで指令データをうける

実際のところ

config.json

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

index.js(node.js版)

新しいライブラリとしてonoffを導入します

$ npm install onoff

この状態で

const fs = require('fs');
const device = require('azure-iot-device');
const Mqtt = require('azure-iot-device-mqtt').Mqtt;
const Gpio = require('onoff').Gpio;
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 gpio21 = new Gpio(21, 'out');

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

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

const receiveMessage = () => {
    client.receive((err, msg, res) => {
        if (err) {
            console.error('Failed to receive message from Azure IoT Hub', err);
        } else {
            const message = JSON.parse(msg.getData().toString('utf8'));
            if (message.targetDeviceID === 'RP3') {
                switch (message.value) {
                    case 'HIGH':
                        gpio21.writeSync(1);
                        break;
                    case 'LOW':
                        gpio21.writeSync(0);
                        break;
                    default:
                        console.error('Unknown value: ' + message.value);
                        break;
                }
            }

            client.complete(msg, (err) => {
                if (err) {
                    console.error('Failed to complete the message', err);
                }
            });
        }
    });
}

setInterval(receiveMessage, interval);

receiveDataFromAzureIoT.py(python3版)

import json
import time
import random
from azure.iot.device import IoTHubDeviceClient, Message

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

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

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)

if __name__ == "__main__":
    main()