gilmaimon / ArduinoWebsockets

A library for writing modern websockets applications with Arduino (ESP8266 and ESP32)
GNU General Public License v3.0
482 stars 97 forks source link

Connection to Home Assistant WebSocket server fails #121

Open bphermansson opened 3 years ago

bphermansson commented 3 years ago

I use the "Esp8266-Client" as base to get data from a Home Assistant server. I changed my Wifi credentials, and as HA needs a token I added this line:

client.addHeader("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc<cut>"); But the connection fails :

connected with BrandstorpWifi, channel 6
dhcp client start...
..ip:192.168.1.189,mask:255.255.255.0,gw:192.168.1.1
Connected to Wifi, Connecting to server.
Not Connected!
pm open,type:2 0

I've tried different formats for the url, but no success. Any ideas?

gilmaimon commented 3 years ago

Weird.. Can you share more of the connection code? Also you can try to turn on more verbose board logs

bphermansson commented 3 years ago

Ok, I made a simple example and set debug level to HTTP_CLIENT. The code:

#include <ESP8266WiFi.h>
#include <ArduinoWebsockets.h>

const char* ssid = "BrandstorpWifi";
const char* password = "hidden";
const char* websockets_server_host = "http://192.168.1.10"; 
const uint16_t websockets_server_port = 8123; 

using namespace websockets;
WebsocketsClient client;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  for(int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
      Serial.print(".");
      delay(1000);
  }
  if(WiFi.status() != WL_CONNECTED) {
      Serial.println("No Wifi!");
      return;
  }
  Serial.println("Connected to Wifi.");

  client.addHeader("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIwYWNlYTYwMmQwNWE0YWJlYjQ3NGFmODk1Y2Nj6<cut>");

  bool connected = client.connect(websockets_server_host, websockets_server_port, "/");
  if(connected) {
      Serial.println("Connecetd!");
      client.send("Hello Server");
  } else {
      Serial.println("Not Connected!");
  }
}

void loop() {
  if(client.available()) {
      client.poll();
  }
  delay(500);
}

Serial output:

SDK:2.2.2-dev(38a443e)/Core:2.7.3-3-g2843a5ac=20703003/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
.scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 7
cnt 

connected with BrandstorpWifi, channel 6
dhcp client start...
..ip:192.168.1.189,mask:255.255.255.0,gw:192.168.1.1
Connected to Wifi.
Not Connected!
pm open,type:2 0
bphermansson commented 3 years ago

This curl command works:

curl -X GET -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIwYWNlYTYwMmQwNWE0YWJlYjQ3NGFmODk1Y2NjZTIxYyIsImlhdCI6M<cut>" http://192.168.1.10:8123/api/

{"message": "API running."}
gilmaimon commented 3 years ago

Sorry for the delay. Looks like you are requesting to /api in your curl script but to / in your arduino code...