樹莓派 微信控制GPIO

1.申請(qǐng)公共平臺(tái)測(cè)試帳號(hào)

截圖00.png
截圖01.png

2.獲取access_token

截圖02.png

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
把APPID和APPSECRET換成圖上的,即可獲取Access_token

3.創(chuàng)建自定義菜單

使用網(wǎng)頁(yè)調(diào)試工具調(diào)試該接口

打開調(diào)試接口, body部分填寫

{
    "menu": {
        "button": [
            {
                "type": "click", 
                "name": "查詢?cè)O(shè)備", 
                "key": "V1001_TODAY_MUSIC", 
                "sub_button": [ ]
            }, 
            {
                "name": "菜單", 
                "sub_button": [
                    {
                        "type": "click", 
                        "name": "第一路:開", 
                        "key": "v1_on", 
                        "sub_button": [ ]
                    }, 
                    {
                        "type": "click", 
                        "name": "第一路:關(guān)", 
                        "key": "v1_off", 
                        "sub_button": [ ]
                    }, 
                    {
                        "type": "click", 
                        "name": "第二路-開", 
                        "key": "v2_on", 
                        "sub_button": [ ]
                    }, 
                    {
                        "type": "click", 
                        "name": "第一路-關(guān)", 
                        "key": "v2_off", 
                        "sub_button": [ ]
                    }
                ]
            }
        ]
    }
}

菜單效果

webwxgetmsgimg.jpg

4.回到樹莓派上

4.1 安裝webpy
pip install web.py

4.2 創(chuàng)建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 創(chuàng)建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 創(chuàng)建 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 = """
        <xml>
        <ToUserName><![CDATA[{ToUserName}]]></ToUserName>
        <FromUserName><![CDATA[{FromUserName}]]></FromUserName>
        <CreateTime>{CreateTime}</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[{Content}]]></Content>
        </xml>
        """
        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 = """
        <xml>
        <ToUserName><![CDATA[{ToUserName}]]></ToUserName>
        <FromUserName><![CDATA[{FromUserName}]]></FromUserName>
        <CreateTime>{CreateTime}</CreateTime>
        <MsgType><![CDATA[image]]></MsgType>
        <Image>
        <MediaId><![CDATA[{MediaId}]]></MediaId>
        </Image>
        </xml>
        """
        return XmlForm.format(**self.__dict)

4.5 創(chuàng)建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" #請(qǐng)按照公眾平臺(tái)官網(wǎng)\基本配置中信息填寫

            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  # 后臺(tái)打日志
            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一路:關(guān)'
                        content = "成功關(guān)閉第一路燈"
                        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 '第二路:關(guān)'
                        gpio.handel(20, 0)
                        content = "成功關(guān)閉第二路燈"
                        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

推薦一個(gè)linux命令行網(wǎng)站:https://rootopen.com

需要內(nèi)網(wǎng)穿透請(qǐng)看http://www.itdecent.cn/p/c76aba56abe2

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容