1.申请公共平台测试帐号
2.获取access_token
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
把APPID和APPSECRET换成图上的,即可获取Access_token
3.创建自定义菜单
使用网页调试工具调试该接口
打开调试接口, body部分填写
{
"menu": {
"button": [
{
"type": "click",
"name": "查询设备",
"key": "V1001_TODAY_MUSIC",
"sub_button": [ ]
},
{
"name": "菜单",
"sub_button": [
{
"type": "click",
"name": "第一路:开",
"key": "v1_on",
"sub_button": [ ]
},
{
"type": "click",
"name": "第一路:关",
"key": "v1_off",
"sub_button": [ ]
},
{
"type": "click",
"name": "第二路-开",
"key": "v2_on",
"sub_button": [ ]
},
{
"type": "click",
"name": "第一路-关",
"key": "v2_off",
"sub_button": [ ]
}
]
}
]
}
}
菜单效果
4.回到树莓派上
4.1 安装webpy
pip install web.py
4.2 创建main.py文件
sudo nano mainpy
#!/usr/local/bin/python
#coding=utf-8
import web
from handle import Handle
urls = (
'/wx', 'Handle',
)
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
4.3 创建receive.py
sudo nano receive.py
# -*- coding: utf-8 -*-
# filename: receive.py
import xml.etree.ElementTree as ET
def parse_xml(web_data):
if len(web_data) == 0:
return None
xmlData = ET.fromstring(web_data)
msg_type = xmlData.find('MsgType').text
if msg_type == 'text':
return TextMsg(xmlData)
elif msg_type == 'image':
return ImageMsg(xmlData)
elif msg_type == 'event':
return gpioMsg(xmlData)
class Msg(object):
def __init__(self, xmlData):
self.ToUserName = xmlData.find('ToUserName').text
self.FromUserName = xmlData.find('FromUserName').text
self.CreateTime = xmlData.find('CreateTime').text
self.MsgType = xmlData.find('MsgType').text
class gpioMsg(Msg):
def __init__(self, xmlData):
Msg.__init__(self, xmlData)
self.EventKey = xmlData.find('EventKey').text.encode("utf-8")
class TextMsg(Msg):
def __init__(self, xmlData):
Msg.__init__(self, xmlData)
self.MsgId = xmlData.find('MsgId').text
self.Content = xmlData.find('Content').text.encode("utf-8")
class ImageMsg(Msg):
def __init__(self, xmlData):
Msg.__init__(self, xmlData)
self.MsgId = xmlData.find('MsgId').text
self.PicUrl = xmlData.find('PicUrl').text
self.MediaId = xmlData.find('MediaId').text
4.4 创建 reply.py
sudo nano reply.py
# -*- coding: utf-8 -*-
# filename: reply.py
import time
class Msg(object):
def __init__(self):
pass
def send(self):
return "success"
class TextMsg(Msg):
def __init__(self, toUserName, fromUserName, content):
self.__dict = dict()
self.__dict['ToUserName'] = toUserName
self.__dict['FromUserName'] = fromUserName
self.__dict['CreateTime'] = int(time.time())
self.__dict['Content'] = content
def send(self):
XmlForm = """
{CreateTime}
"""
return XmlForm.format(**self.__dict)
class ImageMsg(Msg):
def __init__(self, toUserName, fromUserName, mediaId):
self.__dict = dict()
self.__dict['ToUserName'] = toUserName
self.__dict['FromUserName'] = fromUserName
self.__dict['CreateTime'] = int(time.time())
self.__dict['MediaId'] = mediaId
def send(self):
XmlForm = """
{CreateTime}
"""
return XmlForm.format(**self.__dict)
4.5 创建handel.py
sudo nano handle.py
注意token的填写
#!/usr/local/bin/python
#coding=utf-8
import hashlib
import reply
import receive
import web
import gpio
class Handle(object):
def GET(self):
try:
for k, v in web.ctx.env.items():
print(k, v)
data = web.input()
if len(data) == 0:
return "hello, this is handle view"
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
token = "xxxxxxxxxxxxxxxxxx" #请按照公众平台官网\基本配置中信息填写
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)
hashcode = sha1.hexdigest()
print ("handle/GET func: hashcode, signature: ", hashcode, signature)
if hashcode == signature:
return echostr
else:
return ""
except Exception as Argument:
return Argument
def POST(self):
try:
webData = web.data()
print "Handle Post webdata is ", webData # 后台打日志
recMsg = receive.parse_xml(webData)
if isinstance(recMsg, receive.Msg):
toUser = recMsg.FromUserName
fromUser = recMsg.ToUserName
if recMsg.MsgType == 'text':
content = "test"
replyMsg = reply.TextMsg(toUser, fromUser, content)
return replyMsg.send()
if recMsg.MsgType == 'image':
mediaId = recMsg.MediaId
replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
return replyMsg.send()
if recMsg.MsgType == 'event':
if recMsg.EventKey == 'v1_on':
print '第1一路:开'
gpio.handel(16,1)
print '成功'
content = "成功打开第一路灯"
replyMsg = reply.TextMsg(toUser, fromUser, content)
return replyMsg.send()
if recMsg.EventKey == 'v1_off':
gpio.handel(16, 0)
print '第1一路:关'
content = "成功关闭第一路灯"
replyMsg = reply.TextMsg(toUser, fromUser, content)
return replyMsg.send()
if recMsg.EventKey == 'v2_on':
gpio.handel(20, 1)
print '第二路:开'
content = "成功打开第二路灯"
replyMsg = reply.TextMsg(toUser, fromUser, content)
return replyMsg.send()
if recMsg.EventKey == 'v2_off':
print '第二路:关'
gpio.handel(20, 0)
content = "成功关闭第二路灯"
replyMsg = reply.TextMsg(toUser, fromUser, content)
return replyMsg.send()
else:
print "暂且不处理"
return "success"
except Exception, Argment:
return Argment
4.6 sudo nano gpio.py
#!/usr/local/bin/python
#coding=utf-8
try:
import RPi.GPIO as GPIO
except RuntimeError:
print("Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script")
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
def handel(LED,power):
GPIO.setup(LED,GPIO.OUT)
GPIO.output(LED,power)
if __name__ == '__main__':
handel(16,0)
4.7 sudo python main.py 80
推荐一个linux命令行网站:https://rootopen.com
需要内网穿透请看http://www.jianshu.com/p/c76aba56abe2