使用esp8266做带一个微信提示功能的WiFi按钮

使用esp8266做一个微信提示按钮

Screen Shot 2019-01-06 at 17.43.30.png

周末使用esp82866这个wifi芯片做一个带微信提示功能的WiFI按钮.
通过按动不同的按钮,WiFi芯片发送消息到制定的人的手机微信上(基于企业微信API),达到无服务器实现按动按钮触发手机消息的功能.


ESP8266

esp8266的确是一款超值的芯片,不仅可以是一款WIFI的芯片,可以兼容arduino,还可以使用micropython编程. 价廉物美,小巧灵活.在IOT领域有很好的前景.

01. 微信发送消息API

本次通过企业微信主动发送消息API实现的.
详细的API开发文档可以参考微信企业号开发文档.
大致步骤如下:

  • 申请你的微信企业号,并获取 corpid 和 corpsecret.
  • 添加你的应用,并记住你的应用的 agentid.
  • 通过 corpid 和 corpsecret.调用 gettoken API并获取 access_token. 这个access_token很重要,以后的调用就靠这个了.
  • 调用发送信息的API,把响应信息通过微信企业号发送到相关人员手中
  • WiFi芯片 获取针脚的按钮状态,根据按钮发送不同消息给相应的人员

02. 代码

采用了 micropython编程,调用企业微信主动发送消息API实现此功能.

import urequests as requests
import ujson as josn
import network
from machine import Pin
import time

# WLAN
essid = '你的wifi名称'
password = '你的wifi密码'

# 企业微信主动发送消息函数的参数
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','帮我带一份饮料.')
       if p5.value()==0:
             send_msg('gaosheng','测试一下.')

03. 我的小目标

其实做这个wifi按钮,我也是有原因的.我的父亲耳聋,母亲行动不便,希望做个紧急按钮,可以通知到我们也可以把消息发送到父亲的手机上同时也可以把消息发送给我.(我给父亲配置了一个蓝牙手表,可以接受微信的消息,一有消息,手表通过震动提醒.)


Screen Shot 2019-01-06 at 17.39.57.png

这个小的DIY产品花费也就20元,如果对你有帮助,欢迎索要硬件和软件详细资料.

你可能感兴趣的:(使用esp8266做带一个微信提示功能的WiFi按钮)