ラズパイを通じてIoTデバイスからtwitterにつぶやいてみる(DHT11+Twython編)


はじめに

ラズパイに接続したIoTデバイスの情報を外部に発信したいので、手始めにtwitterにつぶやくことにした。対象は、安価で導入できる温度湿度計DHT11を使用する。DHT11の導入についてはこちらを参照。

pythonプラグラム

参考文献

以下の情報を参考にして、プログラムを作成した。

前提としてtwitter applicationを作っておく必要があるが、それも上記のここに記載があるので、参照してもらいたい。

作成ポイント

ライブラリ

以下のライブラリをimportして設計した。

auth key情報

まずはお手本通りに、twitterのauth key関連情報をauth_twitter.pyにまとめて記載する。

auth_twitter.py
consumer_key        = 'ABCDEFGHIJKLKMNOPQRSTUVWXYZ'
consumer_secret     = '1234567890ABCDEFGHIJKLMNOPQRSTUVXYZ'
access_token        = 'ZYXWVUTSRQPONMLKJIHFEDCBA'
access_token_secret = '0987654321ZYXWVUTSRQPONMLKJIHFEDCBA'

メインプログラム側では、上記をimportする。

from auth_twitter import(
    consumer_key,
    consumer_secret,
    access_token,
    access_token_secret
)

cronで自動実行する場合は、importパスが通っていないといけないので、以下を追加する。

/path/to/program/は、auth_twitter.pyの配置されたパスを記述する。

import sys

sys.path.append('/path/to/program/')

温度湿度情報の取り込み

DHT11_Pythonライブラリを使えば簡単。GPIO設定をして、インスタンスする。この例では、GPIO21(40番ピン)にDHT11のDATAピンを接続した。

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

instance = dht11.DHT11(pin=21)

あとはDHT11_Pythonライブラリのお手本通りに、温度湿度情報を取得する。ここでは次にやるコトを意識して、関数化した。

def getInfo():
    while True:
        result = instance.read()
        if result.is_valid():
            #print('温度:', str(result.temperature), '℃です。')
            #print('湿度:', str(result.humidity), '%です。')
            pass
        break
    time.sleep(1)
    return result

twitterに投稿

twythonのお手本通りに投稿する。こちらも次にやるコトを意識して、関数化した。

def commInfo(current_time, res):
    #Twiiter API 
    api = Twython(
        consumer_key,
        consumer_secret,
        access_token,
        access_token_secret
    )
    api.update_status(status = '【温湿情報】'+'現在時刻'
                      +current_time
                      +'\n温度:'+str(res.temperature)+'℃です。'
                      +'\n湿度:'+str(res.humidity)+'%です。')

作成結果

メインプログラム全体は以下。

dht11_tweet.py
# -*- coding: utf-8 -*

import RPi.GPIO as GPIO
import dht11
import time
import os
import sys

sys.path.append('/path/to/program/') #auth_tweet.pyのありか

from twython import Twython
from auth_twitter import(
    consumer_key,
    consumer_secret,
    access_token,
    access_token_secret
)

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

instance = dht11.DHT11(pin=21)

def getInfo():
    while True:
        result = instance.read()
        if result.is_valid():
            #print('温度:', str(result.temperature), '℃です。')
            #print('湿度:', str(result.humidity), '%です。')
            pass
        break
    time.sleep(1)
    return result

def commInfo(current_time, res):
    #Twiiter API 
    api = Twython(
        consumer_key,
        consumer_secret,
        access_token,
        access_token_secret
    )
    api.update_status(status = '【温湿情報】'+'現在時刻'
                      +current_time
                      +'\n温度:'+str(res.temperature)+'℃です。'
                      +'\n湿度:'+str(res.humidity)+'%です。')

if __name__ == '__main__':

    #time stamp
    timestamp = 'date +%F_%H:%M:%S'
    current_time=os.popen(timestamp).readline().strip()

    res = getInfo()
    rt = commInfo(current_time, res)
    print(rt)

つぶやく

以下を実行し、自分のtwitterアカウントに投稿されることを確認した。

$ python3 dht11_tweet.py

つぶやきの自動化

cronで6時間毎につぶやかせる。00分に処理が集中しないように、03分に実行する。

$ crontab -e

エディタが起動したら、6時間毎03分実行するように設定。your LOG dirはこのプログラムの場所。

03 0-23/6 * * * python3 /your LOG dir/dht11_tweet.py >/dev/null 2>&1

さいごに

pythonの記述だけで、twitterにつぶやけるようになった。

次のコトでは、投稿先の汎用化のためIFTTTを利用してみる。