Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save robertschnuell/8e2378e1b169afe3183131ff2f8816d0 to your computer and use it in GitHub Desktop.
Save robertschnuell/8e2378e1b169afe3183131ff2f8816d0 to your computer and use it in GitHub Desktop.
Authenticating to a matrix protocol api endpoint and posting a specific message at a room -example
#include "Arduino.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
////// Network ////////
const String wifiSsid = "YourWifi";
const String wifiSecret = "YourWifiPassword";
TimerHandle_t wifiReconnectTimer;
////// Matrix ////////
const String matrixAdress = "your.address.tdl";
const String matrixUser = "YourUsername";
const String matrixPassword = "YourPassword";
////// DO NOT TOUCH (except you really really know what you are doing) ////////
String matrixReturnHome_server = "";
String matrixReturnAccess_token = "";
String matrixReturnUser_id = "";
String matrixReturnDevice_id = "";
bool matrixLoggedIn = false;
//replace the CA with your root CA of your matrix homeserver you want to communicate with.
const char* root_ca= \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/\n" \
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \
"DkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow\n" \
"PzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD\n" \
"Ew5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\n" \
"AN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmTrE4O\n" \
"rz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEq\n" \
"OLl5CjH9UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9b\n" \
"xiqKqy69cK3FCxolkHRyxXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw\n" \
"7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40dutolucbY38EVAjqr2m7xPi71XAicPNaD\n" \
"aeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV\n" \
"HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQMA0GCSqG\n" \
"SIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69\n" \
"ikugdB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXr\n" \
"AvHRAosZy5Q6XkjEGB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZz\n" \
"R8srzJmwN0jP41ZL9c8PDHIyh8bwRLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5\n" \
"JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubSfZGL+T0yjWW06XyxV3bqxbYo\n" \
"Ob8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ\n" \
"-----END CERTIFICATE-----\n";
////// DO NOT TOUCH END ////////
void setup() {
Serial.begin(115200);
Serial.println("beginning");
delay(5000);
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
WiFi.onEvent(WiFiEvent);
connectToWifi();
}
void loop() {
if(matrixLoggedIn) {
matrixMessageToRoom("your room address like '!somerandomecode:yourserver.tdl", "diene nachricht");
} else {
matrixAuth();
}
delay(10000);
}
void connectToWifi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(wifiSsid.c_str(), wifiSecret.c_str());
}
void WiFiEvent(WiFiEvent_t event) {
Serial.printf("[WiFi-event] event: %d\n", event);
switch(event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("MAC:");
Serial.println(WiFi.macAddress());
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStart(wifiReconnectTimer, 0);
break;
}
}
void matrixAuth() {
if(WiFi.status()== WL_CONNECTED){
Serial.println("Beginning POST Request");
HTTPClient http;
String serverAdd= "https://";
serverAdd += matrixAdress;
serverAdd += "/_matrix/client/r0/login";
http.begin(serverAdd,root_ca);
http.addHeader("Content-Type", "application/json");
String loginContent = "{\"type\": \"m.login.password\", \"user\": \"";
loginContent += matrixUser;
loginContent += "\",\"password\": \"";
loginContent += matrixPassword;
loginContent += "\"}";
int httpResponseCode = http.POST(loginContent);
if(httpResponseCode>0){
String response = http.getString();
if(httpResponseCode == 200) {
DynamicJsonDocument doc(1024);
deserializeJson(doc, response);
JsonObject obj = doc.as<JsonObject>();
Serial.print("ResponseCode:");
Serial.println(httpResponseCode);
matrixReturnUser_id = obj["user_id"].as<String>();
matrixReturnAccess_token = obj["access_token"].as<String>();
matrixReturnHome_server = obj["home_server"].as<String>();
matrixReturnDevice_id = obj["device_id"].as<String>();
Serial.print("usr: ");
Serial.println(matrixReturnUser_id);
Serial.print("token: ");
Serial.println(matrixReturnAccess_token);
Serial.print("server: ");
Serial.println(matrixReturnHome_server);
Serial.print("device: ");
Serial.println(matrixReturnDevice_id);
matrixLoggedIn = true;
}
}else{
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
}else{
Serial.println("Error in WiFi connection");
}
}
void matrixMessageToRoom(String roomNameId, String msg) {
if(WiFi.status()== WL_CONNECTED){
Serial.println("Beginning Sending message");
HTTPClient http;
String url= "https://";
url += matrixAdress;
url += "/_matrix/client/r0/rooms/";
url += roomNameId;
url += "/send/m.room.message?access_token=";
url += matrixReturnAccess_token;
http.begin(url,root_ca);
http.addHeader("Content-Type", "application/json");
String content = "{\"msgtype\":\"m.text\", \"body\":\"";
content += msg;
content += "\"}";
int httpResponseCode = http.POST(content);
if(httpResponseCode>0){
String response = http.getString();
Serial.print("ResponseCode:");
Serial.println(httpResponseCode);
Serial.println(response);
}else{
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
}else{
Serial.println("Error in WiFi connection");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment