esp8266 发送消息给钉钉机器人-Arduino中文社区 - Powered by Discuz! Archiver

zengwh 发表于 2022-9-4 15:26

esp8266 发送消息给钉钉机器人

钉钉机器人使用大家可以从官网了解如何添加一个钉钉机器人 https://open.dingtalk.com/document/robots/custom-robot-access源码直接附上源码,webhookUrl 为钉钉机器人的webhook地址,格式类似这种:“https://oapi.dingtalk.com/robot/send?access_token=XXXXXX”
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
#include <ArduinoJson.h>

//WiFi连接信息(注意:需要自行修改以下内容否则ESP8266无法连接WiFi)
#define ssid "xxxx"   //WiFi名称
#define password "xxxxxxx"//WiFi密码


String webhookUrl = "https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx";

int PIR_sensor = 12;    //指定PIR模拟端口 A5
int LED = 2;         //指定LED端口 13
int val = 0;            //存储获取到的PIR数值


void httpPostRequest(String requestUrl, String body) {
Serial.println("http post " + String(requestUrl) + " body \n" + String(body));
WiFiClientSecure client;
HTTPClient httpClient;
client.setInsecure();
httpClient.begin(client, requestUrl);
httpClient.addHeader("Content-Type", "application/json");
int httpResponseCode = httpClient.POST(body);;
Serial.println("http post " + String(requestUrl) + " code: " + httpResponseCode);
if (httpResponseCode == HTTP_CODE_OK){
      String resp = httpClient.getString();
      Serial.println("Send post success, resp " + String(resp));      
}
else{
      Serial.println("Send post request failed!");
}

httpClient.end();

}


void send_dingding_msg(String msg){
   String body = "{\"msgtype\": \"text\",\"text\": {\"content\":\""+msg+"\"}}";
   httpPostRequest(webhookUrl, body);
}

//Wifi init
void wifi_init(){
Serial.begin(9600);
WiFi.mode(WIFI_STA);      //设置ESP8266为无线终端工作模式

WiFi.begin(ssid, password); //连接WiFi
Serial.println("");
Serial.println("Connecting"); Serial.println("");

// 等待连接
while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
}

//成功连接后通过串口监视器显示WiFi名称以及ESP8266的IP地址。
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}

void setup() {
pinMode(PIR_sensor, INPUT);   //设置PIR模拟端口为输入模式
pinMode(LED, OUTPUT);         //设置端口2为输出模式
wifi_init();

}

void loop() {
val = digitalRead(PIR_sensor);    //读取A0口的电压值并赋值到val
            //串口发送val值
delay(2000);
if (val == HIGH)//判断PIR数值是否大于150,
{
    digitalWrite(LED,HIGH);//大于表示感应到有人
    Serial.println("detect !!!!");
    send_dingding_msg("告警:detect a human!");
}
else
{
    digitalWrite(LED,LOW);   //小于表示无感应到有人
}
}钉钉机器人发送示例
欢迎关注我的公众号“玩转esp8266”,原创技术文章第一时间推送。原文链接https://mp.weixin.qq.com/s/BjlUmcrUdqxLKo0pjeyaJw
页: [1]
查看完整版本: esp8266 发送消息给钉钉机器人