树莓派、Arduino配合上传onenet

接线如图:

树莓派python代码:

# -*- coding:utf-8 -*- File: ceshitianqi

# -*- coding:utf-8 -*-
# File: ceshitianqi

import urllib2
import json
import time
import datetime
import serial  
import random
import os

APIKEY = 'ZPdLylplRvWMioB2=p4BnQvK9jI='  #改成你的APIKEY

def read(key):
    ser=serial.Serial("/dev/ttyUSB1",9600,timeout=1)
    ser.write(key)
    print("output:"+key)
    time.sleep(1)
    response = ser.readall()
    print(response)
    print(type(response))
    return response

def http_put(key):
    val = read(key) #获取Arduino的数据
    CurTime = datetime.datetime.now()
    url='http://api.heclouds.com/devices/26666451/datapoints'
    #values={'datastreams':[{"id":"temp","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]}
    print(type(val))
    if key== "a" :
      values={'datastreams':[{"id":"humidity","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]}
    if key== "b" :
      values={'datastreams':[{"id":"temperature","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]}
    jdata = json.dumps(values)                  # 对数据进行JSON格式化编码
    #打印json内容
    print jdata
    request = urllib2.Request(url, jdata)
    request.add_header('api-key', APIKEY)
    request.get_method = lambda:'POST'          # 设置HTTP的访问方式
    request = urllib2.urlopen(request)
    return request.read()   

str = ("a","b")
while True:
    for i in str:     
        resp = http_put(i)
              time.sleep(2)

 

你可能感兴趣的:(树莓派、Arduino配合上传onenet)