あれ、なんかIoTっぽいことしてなくない?(2回目)
なんかこう、IoTってスマホやパソコンから指示を出したらその結果が通知されたり、家電が動いたりするっていうイメージがあるじゃないですか?(あるよね?)
友達に聞いたところ、水耕栽培ではLEDを証明に使って栽培するイメージがあるようで、ライトの実装をすることにした。
そこで番外編②では、IoTっぽくスマホからライトを操作して植物に光を与える作業を行うことにする。
実装
早速実装する。まずはLINEからスプレッドシートに書き込む処理を行う。 参考記事
function doPost(e) {
var userMessage = JSON.parse(e.postData.contents).events[0].message.text;
if(userMessage == "on") {
} else if (userMessage == "off"){
} else if (userMessage == "ちりやちゃーん"){
lineAssigned()
return
}
var response = e.postData.getDataAsString();
var spreadsheetId = "your_sheetname";
var sheetName = "yoursheet";
var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
var sheet = spreadsheet.getSheetByName(sheetName);
var arr = userMessage.split(/\s/);
var lastRow = dsheet.getLastRow();
sheet.getRange(lastRow,D_LSH,1,1).setValue(arr);
return ContentService.createTextOutput(JSON.stringify({'content': 'post ok'})).setMimeType(ContentService.MimeType.JSON);
}
こうすることでLINEからスプレッドシートに値が書き込まれるようになるので、あとはラズパイ側からon/offを読み取って動かしてあげればいける。
main.py
function doPost(e) {
import _light as li
import _gspread as gs
import RPi.GPIO as GPIO
import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.OUT)
_isOn = gs.retonff()
try:
while True:
dt_now = datetime.datetime.now()
curhour = int(dt_now.strftime('%H'))
cursec = int(dt_now.strftime('%S'))
if(_isOn == "on"):
li.light_on()
elif(_isOn == "off"):
li.light_off()
elif(curhour > 4 & curhour < 6):
break
if(cursec % 10 == 0):
_isOn = gs.retonff()
print("get")
except KeyboardInterrupt:
print("forced")
GPIO.cleanup()
print("owata")
light.py
import RPi.GPIO as GPIO
import time
def light_on():
GPIO.output(16, GPIO.HIGH)
def light_off():
GPIO.output(16, GPIO.LOW)
gspread.py
import gspread
from oauth2client.service_account import ServiceAccountCredentials
def retonff():
key_name = 'abs/path/credentials.json'
sheet_name = 'console'
terminalID = "time"
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name(key_name, scope)
gc = gspread.authorize(credentials)
wks = gc.open(sheet_name).sheet1
records = wks.col_values(14)
curinfo = records[-1]
return curinfo
結果
成功。最初の起動に時間がかかっているのは10秒おきにon/offを判断するためなので問題なし。
前回:番外編①LINE通知機能