Bye Bye Moore

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

AzureのIoT系をつかう その10:RasPi用Grove拡張基盤と連動した動きをつくる

これまでの総決算としてRasPi用Grove拡張基盤を経由したサンプルを作ります。

実際のところ

装置まわり

これまでと同様、機体はRaspberry Pi 3B+にRaspberryOS 64bitを使用。

これに、SeeedStudioのGroveBaseHATを追加します。

Groveポートには出力用としてLED GREEN


入力用としてロータリーエンコーダー

config.json

index.js

const mraa = require('mraa');
const rotaryEncoder = require('jsupm_rotaryencoder');
const Client = require('azure-iot-device-mqtt').clientFromConnectionString;

const fs = require('fs');
const config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));

let messageId = 0;
const targetDeviceId = 'RP3';
let interval = config.interval || 2000;

const connectionString = config.connectionString;
const client = Client.fromConnectionString(connectionString);

// Initialize the GPIO for the LED
let led = new mraa.Gpio(18);
led.dir(mraa.DIR_OUT);

// Initialize the Rotary Encoder on A2
let encoder = new rotaryEncoder.RotaryEncoder(2);

client.open(connectCallback);

function connectCallback(err) {
  if (err) {
    console.error('Could not connect: ' + err.message);
  } else {
    console.log('Client connected');

    client.on('message', function(msg) {
      console.log('Id: ' + msg.messageId + ' Body: ' + msg.data);
      let data = JSON.parse(msg.data);
      if (data.value === 'HIGH') {
        led.write(1);
      } else if (data.value === 'LOW') {
        led.write(0);
      }

      let message = {
        messageId: data.messageId,
        targetDeviceId: targetDeviceId,
        value: encoder.position()
      };

      client.sendEvent(new Message(JSON.stringify(message)), printResultFor('send'));
    });
  }
}

function printResultFor(op) {
  return function printResult(err, res) {
    if (err) console.log(op + ' error: ' + err.toString());
    if (res) console.log(op + ' status: ' + res.constructor.name);
  };
}

参考もと