LoginSignup
3
4

More than 5 years have passed since last update.

植物の育成データの取得 センサーからのデータ取得

Posted at

前回までで材料の購入とラズパイの設定までが完了。

1.植物の育成環境のデータを取得する。
2.植物の育成データの取得 Raspberry Pi2 Model B環境構築

今回はセンサーのデータを変換して人間が理解できる数値にしてWebサーバへ連携する。

TSL2561の取得データ変換にはこちらを使用させて頂きました。
https://github.com/aike/SimpleTSL2561.py

spi_get.py
#!/usr/bin/env python

import time
import sys
import spidev
import signal
import RPi.GPIO as GPIO
import pprint
import json
import requests
import tsl2561
from tsl2561 import SimpleTSL2561

# Sensor position#
moist_channel = 0
temp_channel = 1
#light_channel = 2

# LED GPIO
led = 4

# SPI bus open
spi = spidev.SpiDev()
spi.open(0,0)

def readAdc(channel):
# Get sendor data via MCP3008
# MCP3008 input channel count is 0-7
    adc = spi.xfer2([1,(8+channel)<<4,0])
    data = ((adc[1]&3) << 8) + adc[2]
    return data

def exit_handler(signal, frame):
    print("\nExit")
    spi.close()
    GPIO.cleanup()
    sys.exit(0)

# End logic
signal.signal(signal.SIGINT, exit_handler)

# LED ON
GPIO.setmode(GPIO.BCM)
GPIO.setup(led, GPIO.OUT)

while True:

    # Get Temp
    v = 0.0
    offset = 0.424
    vc = 0.00625

    #温度を取得して摂氏変換
    temp = readAdc( temp_channel )
    # temp = (temp*3.3/1024-0.5)/0.01
    v  = (float(temp)/1024*3.3)
    temp = (v - offset) / vc

    # Get Light
    # light = readAdc( light_channel )
        tsl2561class = SimpleTSL2561()
        light = tsl2561class.readData()

    # Get Moist
    # the moisture sensor value description
    # 0  ~300     dry soil
    # 300~700     humid soil
    # 700~950     in water
    moist = readAdc( moist_channel )

    # Sent Post request
    # WebアプリにPOST
    payload = {'growdatum':{"device_id": 1,"moisture": moist,"temp": temp,"sublight": light,"air":0,"nutrient":0}}
    headers = {'Content-Type': 'application/json'}

    # LED ON
    GPIO.output(led, True)
    time.sleep(1)

    response = requests.post('http://hogehoge.com/api/growdatas',
                             data=json.dumps(payload),
                             headers=headers)

    print response

    # LED Off (10min)
    # LEDを消して10分スリープ
    GPIO.output(led, False)
    time.sleep(600)

Rasperry pi2 起動時にSlackへwebhook通知する。
ここではDHCPで割り当てられたIPを通知している。
Slackのwebhookはここがわかりやすいかと。
http://qiita.com/satoshi03/items/14495bf431b1932cb90b

welcome.py
#!/usr/bin/env python

# Welcome slack post script for Raspberry pi2

import slackweb
import socket
import fcntl
import struct

slack = slackweb.Slack(url="https://hooks.slack.com/services/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")

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

def getserial():
    # Extract serial from cpuinfo file
    cpuserial = "0000000000000000"
    try:
        f = open('/proc/cpuinfo','r')
        for line in f:
            if line[0:6]=='Serial':
                cpuserial = line[10:26]
        f.close()
    except:
        cpuserial = "ERROR000000000"

    return cpuserial

slack.notify(text="I'm wake up and join quad network.\nIP is " + get_ip_address('wlan0') + " cobit Raspi " + getserial() +".")

起動スクリプト

autorun_script.sh
#!/bin/sh

python /home/pi/python_apps/welcome.py

python /home/pi/python_apps/spi_get.py

この起動スクリプトをRaspberry Piの起動時に走るように設定する。
ラズパイにログインして下記ファイルを編集

$ sudo vi /etc/rc.local
/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

sleep 20
sudo -u pi /home/pi/autorun_script.sh &

exit 0

これで、ネットワーク内のIPアドレスが分かるので、動かしつつデバッグも可能になります。
この仕様で10000mAhバッテリーで駆動すると8時間も持たない。
Pythonスクリプトでスリープするより、一度実行したら終了。
サイクリックの実行はシェルをCronで実行するほうが良さそう。
電源がシビアなら、実行時に起動&終了時にシャットダウンが良いかもしれない。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4