Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9146

Node.js: MQTT クライアントのサンプル

$
0
0
こちらで定めた仕様を満たすクライアントです。 IOT: MQTT クライアントのサンプル プログラム subscribe.js #! /usr/local/bin/node // --------------------------------------------------------------- // subscribe.js // // Oct/05/2021 // // --------------------------------------------------------------- 'use strict' console.error ("*** 開始 ***") var mqtt = require('mqtt') const client = mqtt.connect('mqtt://example.com') const topic = 'example/test01' var Gpio = require('onoff').Gpio var led = new Gpio(16, 'out') // --------------------------------------------------------------- client.on('connect', function () { client.subscribe(topic) }) // --------------------------------------------------------------- client.on('message', function (topic, message) { const json_str = message.toString() const dict_aa = JSON.parse (json_str) if ('desired' in dict_aa['state']) { const desired = dict_aa['state']['desired'] led_proc(desired) } }) // --------------------------------------------------------------- function led_proc(desired) { console.log(desired) console.log(desired['led']) const on_off = desired['led'] if (on_off == "on") { led.writeSync(1) } else if (on_off == "off") { led.writeSync(0) } report_proc(on_off) } // --------------------------------------------------------------- function report_proc(on_off) { var dict_aa = new Object () dict_aa["state"] = new Object () dict_aa["state"]["reported"] = new Object() dict_aa["state"]["reported"]["led"] = on_off const json_str = JSON.stringify(dict_aa) console.log(json_str) console.log() client.publish(topic, json_str) } // --------------------------------------------------------------- 実行スクリプト export NODE_PATH=/usr/local/lib/node_modules ./subscribe.js 次のパージョンで確認しました。 $ node -v v14.17.6

Viewing all articles
Browse latest Browse all 9146

Trending Articles