为什么我的变量没有用python

时间:2018-09-02 05:48:09

标签: python raspberry-pi

在寻求帮助时,我无法弄清为什么变量没有被带入cloud4rpi流。他们打印出并写入文件就好了,而我正在同一循环中执行cloud4rpi。

#!/usr/bin/env python
#
# GrovePi Project for a Plant monitoring project.
#   *   Reads the data from moisture, light, temperature and humidity sensor 
#       and takes pictures from the Pi camera periodically and logs them
#   *   Sensor Connections on the GrovePi:
#           -> Grove Moisture sensor    - Port A0
#           -> Grove light sensor       - I2C-1
#           -> Grove Temp sensor        - I2C-2



import time
import grovepi
import subprocess
import math
import smbus
import SI1145

#Cloud4rpi
from time import sleep
import sys
import random
import cloud4rpi
import rpi


#analog sensor port number
mositure_sensor         = 1


# Get I2C bus
bus = smbus.SMBus(1)

sensor = SI1145.SI1145()

DEVICE_TOKEN = 'AH1yEtV2hXzGPJSneShYQA85m'

# Constants
# LED_PIN = 12
DATA_SENDING_INTERVAL = 30  # secs
DIAG_SENDING_INTERVAL = 60  # secs
POLL_INTERVAL = 0.5  # 500 ms

#############
#test timings
time_for_sensor     = 4     #  4 seconds
time_for_picture    = 12    # 12 seconds

#   final
# time_for_sensor       = 1*60*60   #1hr
# time_for_picture      = 8*60*60   #8hr

time_to_sleep       = 1
log_file="plant_monitor_log.csv"

#Read the data from the sensors
def read_sensor():
    try:
        moisture=grovepi.analogRead(mositure_sensor)
        # Sunlight Sensor
            vis = sensor.readVisible()
            IR = sensor.readIR()
            UV = sensor.readUV()
            uvIndex = UV / 100.0

        # SHT31 address, 0x44(68)
        # Send measurement command, 0x2C(44)
        #       0x06(06)    High repeatability measurement
        bus.write_i2c_block_data(0x44, 0x2C, [0x06])

        time.sleep(0.5)

        # SHT31 address, 0x44(68)
        # Read data back from 0x00(00), 6 bytes
        # Temp MSB, Temp LSB, Temp CRC, Humididty MSB, Humidity LSB, Humidity CRC
        data = bus.read_i2c_block_data(0x44, 0x00, 6)

        # Convert the data
        temp = data[0] * 256 + data[1]
        cTemp = -45 + (175 * temp / 65535.0)
        fTemp = -49 + (315 * temp / 65535.0)
        humidity = 100 * (data[3] * 256 + data[4]) / 65535.0

        #Return -1 in case of bad temp/humidity sensor reading
        if math.isnan(cTemp) or math.isnan(humidity):       #temp/humidity sensor sometimes gives nan
            return [-1,-1,-1,-1]
        return [moisture,vis,IR,UV,cTemp,humidity]

    #Return -1 in case of sensor error
    except IOError as TypeError:
            return [-1,-1,-1,-1]

#Take a picture with the current time using the Raspberry Pi camera. Save it in the same folder
def take_picture():
    try:
        cmd="raspistill -t 1 -o plant_monitor_"+str(time.strftime("%Y_%m_%d__%H_%M_%S"))+".jpg"
        process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
        output = process.communicate()[0]
        print("Picture taken\n------------>\n")
    except:
        print("Camera problem,please check the camera connections and settings")

#Save the initial time, we will use this to find out when it is time to take a picture or save a reading
last_read_sensor=last_pic_time= int(time.time())

while True:
    curr_time_sec=int(time.time())

    # If it is time to take the sensor reading
    if curr_time_sec-last_read_sensor>time_for_sensor:
        [moisture,vis,IR,UV,ctemp,humidity]=read_sensor()
        # If any reading is a bad reading, skip the loop and try again
        if moisture==-1:
            print("Bad reading")
            time.sleep(1)
            continue
        curr_time = time.strftime("%Y-%m-%d:%H-%M-%S")
        print(("Time: %s\nMoisture: %d\nLight: %d\nIR: %d\nUV: %d\nTemp: %.2f\nHumidity: %.2f %%\n" %(curr_time,moisture,vis,IR,UV,ctemp,humidity)))

        #Send to Cloud4rpi

        # Put variable declarations here
            # Available types: 'bool', 'numeric', 'string'
            variables = {
                'Room Temp': {
                        'type': 'string',
                        'bind': ctemp
                },
            'Humidity': {
                        'type': 'string',
                        'bind': humidity
                },
                'Soil Moisture': {
                        'type': 'string',
                        'bind': moisture
                },
            'Visible Light': {
                        'type': 'string',
                        'bind': vis
                },
            'InfraRed Light': {
                        'type': 'numeric',
                        'bind': IR
                },
            'UV Light': {
                        'type': 'numeric',
                        'bind': UV
                },
            'CPU Temp': {
                        'type': 'numeric',
                        'bind': rpi.cpu_temp
                }
            }

            diagnostics = {
                'CPU Temp': rpi.cpu_temp,
                'IP Address': rpi.ip_address,
                'Host': rpi.host_name,
                'Operating System': rpi.os_name
            }
            device = cloud4rpi.connect(DEVICE_TOKEN)


            device.declare(variables)
            device.declare_diag(diagnostics)

            device.publish_config()
                device.publish_data()
                device.publish_diag()


        # Save the sensor reading to the CSV file
        f=open(log_file,'a')
        f.write("%s,%d,%d,%d,%d,%.2f,%.2f;\n" %(curr_time,moisture,vis,IR,UV,ctemp,humidity))
        f.close()

        #Update the last read time
        last_read_sensor=curr_time_sec

    # If it is time to take the picture
    if curr_time_sec-last_pic_time>time_for_picture:
        take_picture()
        last_pic_time=curr_time_sec

    #Slow down the loop
    time.sleep(time_to_sleep}

我是如此接近,只是无法获得将值升至cloud4rpi。尝试过字符串和数字。 任何帮助将不胜感激,我不是一个优秀的程序员,所以它有点超出我的头脑了。

0 个答案:

没有答案