使用esp8266做一個微信提示按鈕

Screen Shot 2019-01-06 at 17.43.30.png
周末使用esp82866這個wifi芯片做一個帶微信提示功能的WiFI按鈕.
通過按動不同的按鈕,WiFi芯片發(fā)送消息到制定的人的手機微信上(基于企業(yè)微信API),達(dá)到無服務(wù)器實現(xiàn)按動按鈕觸發(fā)手機消息的功能.
ESP8266
esp8266的確是一款超值的芯片,不僅可以是一款WIFI的芯片,可以兼容arduino,還可以使用micropython編程. 價廉物美,小巧靈活.在IOT領(lǐng)域有很好的前景.
01. 微信發(fā)送消息API
本次通過企業(yè)微信主動發(fā)送消息API實現(xiàn)的.
詳細(xì)的API開發(fā)文檔可以參考微信企業(yè)號開發(fā)文檔.
大致步驟如下:
- 申請你的微信企業(yè)號,并獲取 corpid 和 corpsecret.
- 添加你的應(yīng)用,并記住你的應(yīng)用的 agentid.
- 通過 corpid 和 corpsecret.調(diào)用 gettoken API并獲取 access_token. 這個access_token很重要,以后的調(diào)用就靠這個了.
- 調(diào)用發(fā)送信息的API,把響應(yīng)信息通過微信企業(yè)號發(fā)送到相關(guān)人員手中
- WiFi芯片 獲取針腳的按鈕狀態(tài),根據(jù)按鈕發(fā)送不同消息給相應(yīng)的人員
02. 代碼
采用了 micropython編程,調(diào)用企業(yè)微信主動發(fā)送消息API實現(xiàn)此功能.
import urequests as requests
import ujson as josn
import network
from machine import Pin
import time
# WLAN
essid = '你的wifi名稱'
password = '你的wifi密碼'
# 企業(yè)微信主動發(fā)送消息函數(shù)的參數(shù)
tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
sendMsg = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
corpid = "你申請的corpid "
corpsecret = "你申請的corpsecret"
agentid = "你生成的app的agentid"
p0 = Pin(0, Pin.OUT) # create output pin on GPIO0
p2 = Pin(2, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
p5 = Pin(5, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
def init():
p0.on() # set pin to "on" (high) level
time.sleep(1)
p0.off() # set pin to "off" (low) level
def do_connect():
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect(essid, password)
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
def get_token():
gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
req = requests.get(gettoken_url)
data = req.json()
return data["access_token"]
def send_msg(user, msg):
url = sendMsg + get_token()
values = """{"touser" : "%s" ,
"msgtype":"text",
"agentid":"%s",
"text":{
"content": "%s"
},
"safe":"0"
}""" % (user, agentid, msg)
headers = {'Content-Type': 'application/json; charset=UTF-8'}
r = requests.post(url, data=values.encode("utf-8"), headers=headers)
print(r.text)
print(values)
if __name__ == '__main__':
do_connect()
# users ='user1|user2|user3' 多用戶可以通過|符號隔開
while True:
if p2.value()==0:
send_msg('gaosheng','我需要幫助,請馬上過來.')
if p4.value()==0:
send_msg('gaosheng','幫我?guī)б环蒿嬃?')
if p5.value()==0:
send_msg('gaosheng','測試一下.')
03. 我的小目標(biāo)
其實做這個wifi按鈕,我也是有原因的.我的父親耳聾,母親行動不便,希望做個緊急按鈕,可以通知到我們也可以把消息發(fā)送到父親的手機上同時也可以把消息發(fā)送給我.(我給父親配置了一個藍(lán)牙手表,可以接受微信的消息,一有消息,手表通過震動提醒.)

Screen Shot 2019-01-06 at 17.39.57.png
這個小的DIY產(chǎn)品花費也就20元,如果對你有幫助,歡迎索要硬件和軟件詳細(xì)資料.
