作者:z494627 | 更新时间:2016-05-02 | 浏览量:3278
贝壳物联上一直没有树莓派控制的文档,正好用手头的树莓派1代做一个测试
环境:
树莓派1代,Linux raspberrypi 3.6.11,python2.7.3
需要安装RPi.GPIO库
程序分析:
1.通过socket连接贝壳物联(参照API),系统会返回:{"M":"WELCOME TO BIGIOT"}\n
2.发送checkin,设备报告上线,返回{"M":"checkinok","ID":"D+设别ID","NAME":"你的设备名称","T":"1462165538"}\n表示你的设备已经上线
3.发送数据:我的数据接口定义了一个温度,目前只发送一个固定的温度,下一步DHT11接上发实际温度
4.等待接收命令,按照命令方式触发动作
下面是代码:将文件保存到文件:testBigiot.py,运行时使用root登录或者sudo python testBigiot.py(因为gpio控制需要root权限)
# -*- coding: utf-8 -*-
import socket #socket通讯
import json #命令解析
import time
import datetime #定时循环
import os #系统退出使用
import RPi.GPIO as GPIO #python的GPIO控制
#调用数据接口发送数据
def f_sendTemp(sock,DEVID,value):
jsontemp="{\"M\":\"update\",\"ID\":\""+DEVID+"\",\"V\":{\"数据接口ID\":\"数据\"}}\n"
sock.send(jsontemp)
time.sleep(1)
#checkin
def f_checkIn(sock,DEVID,DEVPWD):
jsoncheckin= "{\"M\":\"checkin\",\"ID\":\""+DEVID+"\",\"K\":\""+DEVPWD+"\"}\n"
print "jsoncheckin:",jsoncheckin
sock.send(jsoncheckin)
data = sock.recv(1024)
print 'Received', repr(data)
#接收命令
def f_recv(sock,DEVID,DEVPWD):
try:
rcvData = sock.recv(75) #接收指令稍微长于一个命令的长度
except:
return
print 'Received', rcvData
s=json.loads(rcvData)
print 'Received', s
#指令语句
if s['M'] == 'say':
print 'Command', s['C']
#亮灯
if s['C'] == 'play' :
GPIO.output(led_pin,GPIO.HIGH)
#灭灯
if s['C']=='stop' :
GPIO.output(led_pin,GPIO.LOW)
#退出程序
if s['C']=='offOn' :
jsonLogOut="{\"M\":\"logou\",\"ID\":"+DEVID+"\",\"NAME\":\"openwrt\",\"T\":\""+str(int(time.time()))+"\"}\n"
sock.send(jsonLogOut)
time.sleep(3)
#退出时关闭sock
sock.close()
os._exit(0)
#主程序
#需要替换的地方
DEVID="MyID" #贝壳物联智能设备ID
DEVPWD="My API Key" #贝壳物联智能设备API KEY
#=======
led_pin=24 #LED灯连接的GPIO号
oldTime=datetime.datetime.now()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print time.strftime('%Y-%m-%d %X',time.localtime())
sock.connect(('www.bigiot.net', 8181))
Data = sock.recv(1024)
print 'Received', repr(Data)
time.sleep(5)
f_checkIn(sock,DEVID,DEVPWD)
#初始化GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin,GPIO.OUT)
while 1==1:
now=datetime.datetime.now()
#每隔4秒发送一次温度并且等待命令
if ((oldTime - now).seconds>4):
print time.strftime('%Y-%m-%d %X',time.localtime())
f_sendTemp(sock,DEVID,DEVPWD)
f_recv(sock,DEVID,DEVPWD)
oldTime=now缺陷:
1.命令发送不要太快,小于4秒发送多个命令处理会出错.
2.长时间不发送命令会导致程序崩溃.
所以此程序只用于测试,目前还无法用于生产环境,我会持续改进.
接线图:

点亮LED
