まずraspberry pi ZEROで人感センサが反応したときGmailが送信されるスクリプトが以下のものです。
code
1import requests 2import RPi.GPIO as GPIO 3import time 4 5 6import smtplib 7from email.mime.text import MIMEText 8from email.utils import formatdate 9 10 11 12SLEEPTIME = 60 13 14 15GPIO_PIN = 16 16GPIO.setmode(GPIO.BCM) 17GPIO.setup(GPIO_PIN,GPIO.IN) 18 19def main(): 20 sendAddress = '×××@gmail.com' 21 password = '×××' 22 23 subject = '見守りIoTデバイス 在室通知' 24 bodyText = '在室が検知されました' 25 fromAddress = '×××@gmail.com' 26 toAddress = '×××@gmail.com' 27 28# SMTPサーバに接続 29 smtpobj = smtplib.SMTP('smtp.gmail.com', 587) 30 smtpobj.starttls() 31 smtpobj.login(sendAddress, password) 32 33# メール作成 34 msg = MIMEText(bodyText) 35 msg['Subject'] = subject 36 msg['From'] = fromAddress 37 msg['To'] = toAddress 38 msg['Date'] = formatdate() 39 40# 作成したメールを送信 41 smtpobj.send_message(msg) 42 smtpobj.close() 43 44try: 45 while True: 46 if(GPIO.input(GPIO_PIN) == GPIO.HIGH): 47 main() 48 time.sleep(SLEEPTIME) 49 50finally: 51 GPIO.cleanup()
この実行ファイルは「kk.py」という名前で保存しました。
その後、ラズパイが起動した時、自動でこのプログラムが実行可能にするため、ラズパイのターミナル内で「$ sudo nano /etc/rc.local」コマンドを入力すると以下の文面が表示されます。
#!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. # Print the IP address _IP=$(hostname -I) || true if [ "$_IP" ]; then printf "My IP address is %s\n" "$_IP" fi python3 /home/pi/Desktop/kk.py exit 0
この構文のうち、下から2行目の
「python3 /home/pi/Desktop/kk.py」は自分で付け足しました。
これで編集を完了し保存した後、ラズパイを再起動すると、センサが反応したとき自動でメールが送信されました。
それでここからが本題で、これらはパソコンにラズパイを接続して起動することで自動実行されていますが、これをパソコンでではなく、モバイルバッテリーにさして起動する際、自動実行できるようにしたいわけです。
そこで試したことが、「$ sudo nano /etc/rc.local」にて、実行ファイルの前に「while ! /sbin/ifconfig eth0 | grep -q 'inet [0-9]'; do sleep 3 done」を加えることで改善されるという情報をもとに内容を修正しました。
※無線 LAN の場合は、eth0 を wlan0に変更するみたいなので、自分の場合はwlan0を使用していますhttps://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q12256934807
#!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. # Print the IP address _IP=$(hostname -I) || true if [ "$_IP" ]; then printf "My IP address is %s\n" "$_IP" fi while ! /sbin/ifconfig wlan0 | grep -q 'inet [0-9]'; do sleep 3 python3 /home/pi/Desktop/kk.py exit 0
これで、モバイルバッテリーにさして起動して試したところメールが来ませんでした。
なぜできないのか原因がわからないというのが現状です。
どなたかご教授よろしくお願いします。

回答1件
あなたの回答
tips
プレビュー