如何从Esp8266发布到MS-teams Webhook?

时间:2019-04-09 08:53:18

标签: arduino iot webhooks esp8266

我有一个ESP8266,想向MS-Teams通道发送消息。将来我想发送温度数据,但现在无论如何我都可以。 现在,我可以连接到主机了,但是它不会向团队发送任何数据,也不会出错。 Postman可以毫无问题地运行它,而Python可以使用webhook。

这是我的代码:

#include "ESP8266HTTPClient.h"
#include "ESP8266WiFi.h"
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>

void setup() {
  Serial.begin(9600);                                  //Serial connection
  WiFi.begin("", ""); //WiFi connection
  while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion 
    delay(500);
    Serial.println("Waiting for connection");
  }
}

void MicrosoftTeams() {
  char host[] = "outlook.office.com"; //Specify request destination";
  WiFiClient client;
  if (client.connect(host, 443)) {
    Serial.println("connected");

    String url = "/webhook/Webhookcode";
    char json[] = "{  \"@context\": 
 \"https://schema.org/extensions\",\"@type\": 
 \"MessageCard\",\"themeColor\": \"0072C6\",\"title\": 
 \"meddelande\",\"text\": \"Hello!!\"}";
    int len = strlen(json);

    String Output = "POST " + url + " HTTP/1.1\r\n" +
                    "Host: " + host + "\r\n" +
                    "Content-Type: application/json\r\n" +
                    "User-Agent: arduino/1.0\r\n" +
                    "Content-Length: " + len + "\r\n" +
                    "\r\n" +
                    json + "\n";

    client.print(Output);
    while (client.available()) {
      String line = client.readStringUntil('\r');
      Serial.print(line);
    }
  }
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
    MicrosoftTeams();
  } else {
    Serial.println("Error in WiFi connection");
  }
  delay(30000); //Send a request every 30 seconds
}

更新: 香港专业教育学院测试了以下功能,它可以在此测试示例中工作,但不是实际情况。如果我将WiFiClient更改为WiFiClientSecure,一切将停止工作。

void WifiCliwaySecure()
{
  //Work
      WiFiClient  client;
  const int httpPort = 80;
  // //Doenst work
  //   WiFiClientSecure  client;
  // const int httpPort = 443;
  char host[] = "ptsv2.com";
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

    String url = "/t/erzs7-1555484154/post";
   Serial.print("Requesting POST: ");
   // Send request to the server:
 String data = "{ \"title\": \"meddelande\",\"text\": \"Hallå alla bk!!\"}";
  client.print(String("POST ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "User-Agent: BuildFailureDetectorESP8266\r\n" +
               "Content-Length: " + data.length() + "\r\n" +
               "Content-Type: application/json\r\n" +
               "\r\n" + 
               data +
               "\r\n");
Serial.print("url Send");

   delay(500); // Can be changed
  if (client.connected()) { 
    client.stop();  // DISCONNECT FROM THE SERVER
  }
  Serial.println();
  Serial.println("closing connection");
}

0 个答案:

没有答案