著者:魔法少女
マイコン「ESP32」と小型コンピュータ「Raspberry Pi」を使って本格的なIoT(モノのインターネット)環境を構築してみましょう。本企画では、五つの会議室の温度、湿度、利用状況を監視・分析し、会議室内の電源を制御するシステムを構築します。
シェルスクリプトマガジン Vol.77は以下のリンク先でご購入できます。
図4 ユーザー名とパスワードの生成スクリプト(user_create.sh)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#!/bin/sh tee ~/confer_pw.txt << EOF > /dev/null pub1:passwd1 pub2:passwd2 pub3:passwd3 pub4:passwd4 pub5:passwd5 sub1:passwd6 EOF for i in $(seq 6) do sed -i -e "s|passwd${i}|$(pwgen 8 1)|" ~/confer_pw.txt done |
図5 Eclipse Mosquittoの認証設定スクリプト(mosquitto_setting.sh)
1 2 3 4 5 6 7 8 9 10 |
#!/bin/sh sudo cp ~/confer_pw.txt /etc/mosquitto/confer_pwfile sudo mosquitto_passwd -U /etc/mosquitto/confer_pwfile sudo tee /etc/mosquitto/conf.d/confer.conf << EOF > /dev/null listener 1883 allow_anonymous false password_file /etc/mosquitto/confer_pwfile EOF sudo systemctl reload mosquitto |
図7 サブスクライバのプログラム(subscriber.py)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#!/bin/env python3 import paho.mqtt.client as mqtt import time ## mqtt_topic = "confer/#" csv_file = "./room1.csv" subscriber_username = "sub1" subscriber_password = "IBehie1h" broker_hostname = "localhost" ## def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe(mqtt_topic) def on_message(client, userdata, msg): now_unixtime = time.time() iot_device = msg.topic + "," + str(msg.payload, encoding='utf-8', errors='replace') + "," + str(now_unixtime) print(iot_device) with open(csv_file, mode='a') as f: f.write(iot_device + "\n") ## client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set(username=subscriber_username, password=subscriber_password) client.connect(broker_hostname) client.loop_forever() |
図24 ESP32搭載ボートの起動時に無線LANに接続するプログラム(boot.py)
1 2 3 4 5 6 7 8 9 |
import network SSID = 'USP_OFFICE_B' PASSWORD = 'uspuspusp1234' wlan_if = network.WLAN(network.STA_IF) wlan_if.active(True) wlan_if.connect(SSID, PASSWORD) |
図25 パブリッシャのプログラム(main.py)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import time import dht from machine import Pin from umqtt.simple import MQTTClient mqtt_topic = "confer/room1" publisher_username = "pub1" publisher_password = "パスワード" publisher_id = "room1_esp32" broker_address = "192.168.1.100" interval_time = "1" hf_sensor = Pin(5, Pin.IN, Pin.PULL_UP) th_sensor = dht.DHT11(Pin(22)) time.sleep(5) while True: value1 = hf_sensor.value() th_sensor.measure() value2 = th_sensor.temperature() value3 = th_sensor.humidity() iot_value = str(value1)+","+str(value2)+","+str(value3) print(iot_value) publisher = MQTTClient(publisher_id,broker_address,user=publisher_username,password=publisher_password) publisher.connect() publisher.publish(mqtt_topic, msg=iot_value) publisher.disconnect() time.sleep(int(interval_time)) |