[PYTHON] Acquisition of plant growth data Acquisition of data from sensors

By the last time, the purchase of ingredients and the setting of Raspberry Pi have been completed.

  1. Obtain data on the plant growing environment.
  2. Acquisition of plant growth data Raspberry Pi2 Model B environment construction

This time, we will convert the sensor data into numerical values that humans can understand and link them to the Web server.

I used this to convert the acquired data of 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

    #Get temperature and convert to Celsius
	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
    #POST to web app
	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)
	#Turn off the LED and sleep for 10 minutes
	GPIO.output(led, False)
	time.sleep(600)
	

Notify Slack of webhook when Rasperry pi2 starts. Here, the IP assigned by DHCP is notified. Is Slack's webhook easy to understand here? 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() +".")

Startup script

autorun_script.sh


#!/bin/sh

python /home/pi/python_apps/welcome.py

python /home/pi/python_apps/spi_get.py

Set this startup script to run when the Raspberry Pi starts. Log in to Raspberry Pi and edit the following file

$ 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

Now that you know the IP address in your network, you can debug while it's running. With this specification, it will not last for 8 hours when driven by a 10000mAh battery. Rather than sleeping with a Python script, run it once and it's done. It seems better to run the shell in Cron for cyclic execution. If the power supply is severe, it may be better to start & shut down at runtime.

Recommended Posts

Acquisition of plant growth data Acquisition of data from sensors
[Data science basics] Data acquisition from API
Sensor data acquisition and visualization for plant growth with Intel Edison and Python
Acquisition of time series data (daily) of stock prices
Detect General MIDI data from large amounts of MIDI
Automatic acquisition of stock price data with docker-compose
The transition of baseball as seen from the data
DataNitro, implementation of function to read data from sheet
[Basics of data science] Collecting data from RSS with python
Numerical summary of data
Extract data from S3
Preprocessing of prefecture data
Selection of measurement data
SIGNATE Quest ② From creation of targeting model to creation of submitted data
Visualize plant activity from space using satellite data and Python
[Python] Extract text data from XML data of 10GB or more.
The story of copying data from S3 to Google's TeamDrive
Meteorology x Python ~ From weather data acquisition to spectrum analysis ~