お遊びTech

ITで遊んでみたり、ガジェットで遊んでみたり。その遊びは様々な効果があるかもしれません。

Nature RemoのセンサーデータをLineに通知

前回に引き続き、今度はNatureRemoで取得した値の閾値を設けて必要に応じてLineに通知するようにします。


LineAPIトークン取得

こちらからLineのAPIを取得します。
https://notify-bot.line.me/ja/

f:id:kleonids:20210828125310p:plain


curにてテストします。

curl -X POST -H "Authorization: Bearer 取得したToken" -F "message=ABC" https://notify-api.line.me/api/notify
{"status":200,"message":"ok"
スクリプトに反映

前回作成したスクリプトに追記して通知できるようにします。

import requests
import json

def main():
  remoheaders = {
    'Accept' : 'application/json',
    'Authorization' : 'Bearer [トークン]'
  }
  try:
    res= requests.get('https://api.nature.global/1/devices', headers=remoheaders)
    res.raise_for_status()
    remodata = json.loads(res.text)
    #print(remodata[0])
    hu = remodata[0]['newest_events']['hu']['val']
    il = remodata[0]['newest_events']['il']['val']
    mo = remodata[0]['newest_events']['mo']['val']
    te = remodata[0]['newest_events']['te']['val']
    print('humidity:' + str(hu) + ' illminance:' + str(il) + ' motion:' + str(mo) + ' temperature:' + str(te))
  except requests.exceptions.RequestException as e:
    print("APIエラー: ",e)
    hu='nodata'
    il='nodata'
    mo='nodata'
    te='nodata'

#ここから追加
  lineheaders = {
    'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8',
    'Authorization' : 'Bearer [トークン]'
  }

  if type(te) is str or type(hu) is str:
     msg = '\nNatureRemoのデータが取得できませんでした'
     payload = {'message': msg}
     lineres = requests.post('https://notify-api.line.me/api/notify',headers=lineheaders,
       data=payload)
     #print(lineres.text)
  else:
    if te > 29 or hu < 40:
      # 文頭に[bot]が入るため改行
      msg = '\nリビングアラート(29.0度以上40%以下)\n温度:' + str(te) + ' 湿度: ' + str(hu)
      payload = {'message': msg}
      #print(msg)
      lineres = requests.post('https://notify-api.line.me/api/notify',headers=lineheaders,
         data=payload)
      #print(lineres.text)


if __name__ == "__main__":
  main()
Lineで結果を確認

スクリプトの値を一時的に修正して確認します。

    if te > 20 or hu < 40:

スクリプトを実行しLineに通知が届けば成功です。
スクリプトの実行はCactiが実行してくれるため特に何も行いません。