简体   繁体   English

Raspberry Pi GPIO到Xively python示例?

[英]Raspberry Pi GPIO to Xively python example?

I am a non-programmer feeling my way through Xively with a Raspberry Pi running python. 我是一个非程序员,使用运行python的Raspberry Pi体验了Xively的方式。 I have successfully worked through the tutorial given on the xively site given here: https://xively.com/dev/tutorials/pi/ 我已经成功完成了xively网站上提供的教程: https ://xively.com/dev/tutorials/pi/

The next step in my project is to continuously take readings from one of the GPIO pins (simply whether it's high or low) do some calculations and once a minute supply a number to an Xively feed. 我项目的下一步是不断地从GPIO引脚之一获取读数(简单地说是高还是低),并进行一些计算,并每分钟为Xively feed提供一个数字。

I have the GPIO portion working right in a separate program. 我的GPIO部分在单独的程序中正常工作。 But I'm running into problems when I try to incorporate this into the Xively tutorial example program I got running. 但是,当我尝试将其合并到我正在运行的Xively教程示例程序中时,我遇到了问题。

I am now thinking that I should have the GPIO program and the Xively programs running simultaneously with the GPIO program writing data to a file and the Xively program reading from that file and uploading the data to the feed. 我现在想,我应该让GPIO程序和Xively程序​​同时运行,并且GPIO程序将数据写入文件,并且Xively程序​​从该文件读取并将数据上传到提要。 So my question is: Is this possible and reasonably easy to execute? 所以我的问题是:这是否可能且相当容易执行?

Alternatively, if someone could point me to an example where the Xively tutorial example was modified to accept GPIO inputs, that would also help. 另外,如果有人可以指出修改Xively教程示例以接受GPIO输入的示例,那也将有所帮助。

And if there is a better/simpler way to accomplish what I'm after, I'm open to suggestions... 如果有更好/更简单的方法来完成我要执行的任务,则欢迎提出建议...

You need to : 你需要 :

Download and Install Xively Python Library first. 首先下载并安装Xively Python库。 Download and Install httplib2 module. 下载并安装httplib2模块。

You can combine your "GPIO Sensor" script and your "Send Data to Xively" script. 您可以将“ GPIO传感器”脚本和“将数据发送到Xively”脚本结合在一起。

Here's a sample code for you (it's for Raspberry Pi and DHT 11) : 这是适合您的示例代码(适用于Raspberry Pi和DHT 11):

#!/usr/bin/python

# Import required Python libraries
import RPi.GPIO as GPIO
import time
import random
import datetime
import json
import sys
import Adafruit_DHT
# Custom HTTP Library
import httplib2

# Use BCM GPIO references
# instead of physical pin numbers
#GPIO.setmode(GPIO.BCM)

# Define GPIO to use on Pi

# Set pin as input
#GPIO.setup(GPIO_PIR,GPIO.IN)

# Define sensor state (1 by default)
SENSOR_STATE = 1

DHT_TYPE = Adafruit_DHT.DHT11
DHT_PIN  = 22
# Define URLs and API key for sending and receiving requests
sensorURL = ""
temperatureURL = ""
humidityURL = ""
API_KEY = ""

# Retrieve latest sensor state from Xively via GET request
def retrieve_sensor_state():
  try:

    global SENSOR_STATE  
    print "\nRetrieving from Xively"

    h = httplib2.Http(disable_ssl_certificate_validation=True)
    (resp_headers, content) = h.request(sensorURL, "GET", headers={'X-ApiKey':API_KEY})
    jsonData = json.loads(content)
    SENSOR_STATE = jsonData["current_value"]
    print "Sensor state: " + SENSOR_STATE
    if (SENSOR_STATE == str(1)):
       upload_to_xively()
       print "continuing!"
    else:
       print "sensor is disabled!"  

  except:
    print "Error occurred!"

# Upload sensor data to Xively via PUT request
def upload_to_xively():
  try:

    print "Uploading to Xively"

    now = str(datetime.datetime.now())
    humidity, value = Adafruit_DHT.read(DHT_TYPE, DHT_PIN)
    if humidity is not None and value is not None:
        print "temperature value :" + str(value) + "    |    " + str(now)
        print "humidity value :" + str(humidity) + "    |    " + str(now)

        jsonString = {"id":"temperature","tags":[],"unit":{},"current_value":value}
        publishString = json.dumps(jsonString)

        h = httplib2.Http(disable_ssl_certificate_validation=True)
        (resp, content) = h.request(temperatureURL, "PUT", body=publishString, headers={'X-ApiKey':API_KEY})

        jsonString1 = {"id":"humidity","tags":[],"unit":{},"current_value":humidity}
        publishString1 = json.dumps(jsonString1)
        g = httplib2.Http(disable_ssl_certificate_validation=True)
        (resp, content) = g.request(humidityURL, "PUT", body=publishString1, headers={'X-    ApiKey':API_KEY})
    else:
    print "failed to read data! Trying again"

  except:
    print "Error occurred!"

# Callback function from event handler when motion is detected
#def motion_callback(GPIO_PIR):

#  global SENSOR_STATE
  # Log the sensor data down only if sensor state = 1 (enabled)
#  if SENSOR_STATE == str(1):
#    if GPIO.input(GPIO_PIR):
#        print "\nMotion Detected! @ " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
#        upload_to_xively()
#        time.sleep(1)
#    else:
#        print "\nBack to Normal"

# Main program
print "DHT Module Test (Ctrl+C to exit)"
time.sleep(2)
print "Ready"

try:
  while True: 
    retrieve_sensor_state()
    time.sleep(10)
    continue

except KeyboardInterrupt:
  print "Quit"
  GPIO.cleanup()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM