Giter VIP home page Giter VIP logo

aws-mqtt-websockets's People

Contributors

apicquot avatar odelot avatar rileyschuit avatar stark526 avatar svdgraaf avatar weavaer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-mqtt-websockets's Issues

Not able to connect to MQTT

Hello,

Since last few days device is not connecting to AWS. It is keep trying to connect to MQTT.

Here is the serial print.

[write] n: 536 t: 113145
[WS-Client][sendHeader] sending header... Done (59752us).
[WS-Client][handleHeader] RX: HTTP/1.1 403 Forbidden
[WS-Client][handleHeader] RX: content-type: application/json
[WS-Client][handleHeader] RX: content-length: 163
[WS-Client][handleHeader] RX: date: Wed, 13 Jun 2018 11:23:32 GMT
[WS-Client][handleHeader] RX: x-amzn-RequestId: d3debe06-10e8-713e-8148-462a35c4c9ae
[WS-Client][handleHeader] RX: connection: keep-alive
[WS-Client][handleHeader] RX: x-amzn-ErrorType: ForbiddenException:
[WS-Client][handleHeader] RX: access-control-allow-origin: *
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorMessage
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-RequestId
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorType
[WS-Client][handleHeader] RX: access-control-expose-headers: Date
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXXXXXXXXXXXXXXXXX%2Fap-southeast-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080115Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=9efa2ced93208cf0c2479f082930c26b611fa78c27561dbe94240503b581bf91
[WS-Client][handleHeader] - cKey: el8dDvCsAeAfKQdejfmB3Q==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader] - cCode: 403
[WS-Client][handleHeader] - cIsUpgrade: 0
[WS-Client][handleHeader] - cIsWebsocket: 0
[WS-Client][handleHeader] - cAccept:
[WS-Client][handleHeader] - cProtocol:
[WS-Client][handleHeader] - cExtensions:
[WS-Client][handleHeader] - cVersion: 0
[WS-Client][handleHeader] - cSessionId:
[WS-Client][handleHeader] no Websocket connection close.
[write] n: 27 t: 113519
Alert: close notify
[WS-Client] client disconnected.
[WS-Client] client disconnected.
[WS-Client] connect wss...
State: sending Client Hello (1)
State: receiving Server Hello (2)
State: receiving Certificate (11)
=== CERTIFICATE ISSUED TO ===
Common Name (CN): *.iot.ap-southeast-1.amazonaws.com
Organization (O): Amazon.com, Inc.
Location (L): Seattle
Country (C): US
State (ST): Washington
Basic Constraints: CA:FALSE, pathlen:10000
Key Usage: critical, Digital Signature, Key Encipherment
Subject Alt Name: iot.ap-southeast-1.amazonaws.com *.iot.ap-southeast-1.amazonaws.com
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Symantec Class 3 Secure Server CA - G4
Organization (O): Symantec Corporation
Organizational Unit (OU): Symantec Trust Network
Country (C): US
Not Before: Mon Nov 27 00:00:00 2017
Not After: Wed Nov 28 23:59:59 2018
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Symantec Class 3 Secure Server CA - G4
Organization (O): Symantec Corporation
Organizational Unit (OU): Symantec Trust Network
Country (C): US
Basic Constraints: critical, CA:TRUE, pathlen:0
Key Usage: critical, Key Cert Sign, CRL Sign
Subject Alt Name:
=== CERTIFICATE ISSUED BY ===
Common Name (CN): VeriSign Class 3 Public Primary Certification Authority - G5
Organization (O): VeriSign, Inc.
Organizational Unit (OU): VeriSign Trust Network
Country (C): US
Not Before: Thu Oct 31 00:00:00 2013
Not After: Mon Oct 30 23:59:59 2023
RSA bitsize: 2048
Sig Type: SHA256
State: receiving Server Hello Done (14)
State: sending Client Key Exchange (16)
State: sending Finished (16)
State: receiving Finished (16)
[WS-Client] connected to XXXXXXX.iot.ap-southeast-1.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] handshake GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXXXXXXXXXXXXXXXXX%2Fap-southeast-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080115Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=9efa2ced93208cf0c2479f082930c26b611fa78c27561dbe94240503b581bf91 HTTP/1.1
Host: XXXXXXX.iot.ap-southeast-1.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: TmzQwGpa2ix3ibcpVUrTnw==
Origin: file://
User-Agent: arduino-WebSocket-Client

Same data is repeating.

Can you please tell me what is the wrong?

Failed to connect with aws iot

wss://xxxxxxx.xxxxxx.amazonaws.com/mqtt

Here I have used above end point for the mqtt web socket server as per the amazon's document.
but the problem is I can't connect to the aws.
my program is trying to connect more than 20 times .. it prints as below

client id function has executedclient Id:⸮a2.⸮⸮⸮K⸮⸮⸮�:���EP⸮
��
failed, rc=-21229389 - conn: 24 - (39096)
client id function has executedclient Id:⸮⸮Z⸮d⸮6⸮⸮GG�z⸮⸮⸮.⸮
⸮⸮l
failed, rc=-21280398 - conn: 25 - (39064)
client id function has executedclient Id:�⸮U⸮XZ⸮�⸮⸮1⸮⸮⸮�⸮w�⸮⸮Tm
failed, rc=-21331409 - conn: 26 - (39032)
client id function has executedclient Id:r⸮⸮⸮\��B⸮�⸮⸮⸮4⸮q⸮5ʫ⸮
failed, rc=-21382421 - conn: 27 - (39000)
client id function has executedclient Id:⸮⸮,�⸮⸮⸮⸮⸮YIW⸮v⸮⸮8⸮⸮m⸮�
failed, rc=-21433928 - conn: 28 - (38928)
client id function has executedclient Id:⸮�⸮⸮⸮
S⸮⸮D�⸮G⸮⸮�Ll⸮⸮⸮
failed, rc=-21484938 - conn: 29 - (38936)
client id function has executedclient Id:⸮⸮**⸮QB,>⸮⸮⸮⸮⸮�⸮⸮�T43t

Kindly do the needful.

Problem to Publish After 6 ou 7 Times

Hello Odelot / Other Friends,

I am trying to use your solution, I can connect with AWS IOT and publish something, but I found a problem and I could not fix yet. Could you help me, please?

After publish 6 or 7 times, Its start to show "LmacRxBlk:1" at Serial and in a few seconds, I get the reset of ESP8266. I've tried to change somethings, tried from many ways to resolve this problem, without success!

I just put this code at your example:

if (connect ()){
    subscribe ();
    sendmessage(); delay(5000);
    sendmessage(); delay(5000);
    sendmessage(); delay(5000);
    sendmessage(); delay(5000);
    sendmessage(); delay(5000);
    sendmessage(); delay(5000);
    sendmessage(); delay(5000);
    sendmessage(); delay(5000);
}

And you can see the LOG:

MQTT connected
[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 57 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[WS][0][sendFrame] sending Frame Done (1758us).
[WS][0][handleWebsocketWaitFor] size: 2 cWsRXsize: 0
[readCb] n: 2 t: 7283
[WS][0][handleWebsocketWaitFor][readCb] size: 2 ok: 1
[WS][0][handleWebsocket] ------- read massage frame -------
[WS][0][handleWebsocket] fin: 1 rsv1: 0 rsv2: 0 rsv3 0  opCode: 2
[WS][0][handleWebsocket] mask: 0 payloadLen: 5
[readCb] n: 5 t: 7298
[WSc] get binary length: 5
MQTT subscribed
Publishing... {"state":{"reported":{"on": false}, "desired":{"on": false}}}
[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 116 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[WS][0][sendFrame] sending Frame Done (1902us).
Publishing... {"state":{"reported":{"on": false}, "desired":{"on": false}}}
[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 116 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[WS][0][sendFrame] sending Frame Done (1944us).
Publishing... {"state":{"reported":{"on": false}, "desired":{"on": false}}}
[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 116 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[WS][0][sendFrame] sending Frame Done (1946us).
Publishing... {"state":{"reported":{"on": false}, "desired":{"on": false}}}
[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 116 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[WS][0][sendFrame] sending Frame Done (1960us).
Publishing... {"state":{"reported":{"on": false}, "desired":{"on": false}}}
[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 116 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[WS][0][sendFrame] sending Frame Done (2048us).
Publishing... {"state":{"reported":{"on": false}, "desired":{"on": false}}}
[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 116 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[WS][0][sendFrame] sending Frame Done (1975us).
...
...
...
...
LmacRxBlk:1
LmacRxBlk:1
LmacRxBlk:1
LmacRxBlk:1
LmacRxBlk:1
Publishing... {"state":{"reported":{"on": false}, "desired":{"on": false}}}
[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 116 headerToPayload: 0

Soft WDT reset

ctx: cont 
sp: 3fff27a0 end: 3fff2c70 offset: 01b0

>>>stack>>>
3fff2950:  3fff1b64 00000309 00000309 4010020c  
3fff2960:  3fff5ba4 00000035 3fff51cc 4010068c  
3fff2970:  00000035 cafbd116 00000000 40209ea8  
3fff2980:  0000000a 00000009 3fff7870 4020424b  
3fff2990:  3fff5ba4 00000035 3fff51cc 40204728  
3fff29a0:  3fff77c0 3fff77d0 3fff79a0 00000000  
3fff29b0:  3fff5ba4 00000035 3fff51cc 402052b0  
3fff29c0:  00000000 3fff5aec 00000035 402367c8  
3fff29d0:  00020317 3fff1806 00000040 01000000  
3fff29e0:  00000006 00000017 00000010 3fff51ac  
3fff29f0:  00000000 3fff1838 40209f70 00000000  
3fff2a00:  3fff5aec 3fff2a60 00000006 4023684f  
3fff2a10:  00000006 40206a48 00000074 40202974  
3fff2a20:  00000000 00000b29 00000076 3fff1838  
3fff2a30:  00000000 3fff521c 3fff51ac 40204d2c  
3fff2a40:  00000001 00000074 00000074 40206c0a  
3fff2a50:  00000000 3fff521c 40209f70 3fff1c50  
3fff2a60:  0000f482 00000000 00000000 00000000  
3fff2a70:  3fff0000 3fff51ac 3fff1c50 4020a028  
3fff2a80:  00000006 03b96e08 00000000 00000002  
3fff2a90:  00000001 3fff8ee6 00000000 40204f7b  
3fff2aa0:  40104ec4 3fff1818 3fff1838 3fff521c  
3fff2ab0:  00000074 3fff1838 3fff1818 402077e0  
3fff2ac0:  00000001 00000000 00000002 4020947b  
3fff2ad0:  00000000 3fff1804 3fff1808 0000000a  
3fff2ae0:  00000000 3fff1804 00000003 3fff2c10  
3fff2af0:  00000074 3fff5214 00000074 40207800  
3fff2b00:  0000382b 00000000 00000000 402082d4  
3fff2b10:  00000072 3fff5214 00000000 40202d0d  
3fff2b20:  3fff1804 0001693d 3fff521c 00000074  
3fff2b30:  3fffdad0 3fff521c 00000000 00000000  
3fff2b40:  3fff2c10 3fff5214 3fff2ba0 402030a8  
3fff2b50:  3fff521d 00000000 00000000 40209294  
3fff2b60:  00000003 00000001 3fff2c10 00000001  
3fff2b70:  00000074 3fff5214 3fff2ba0 402031d0  
3fff2b80:  3ffe96cc 00000000 00000000 3fff2ba0  
3fff2b90:  0000003e 00000001 3fff561c 40201831  
3fff2ba0:  7473227b 22657461 72227b3a 726f7065  
3fff2bb0:  22646574 6f227b3a 203a226e 736c6166  
3fff2bc0:  202c7d65 73656422 64657269 227b3a22  
3fff2bd0:  3a226e6f 6c616620 7d7d6573 4020007d  
3fff2be0:  3fff2c10 0000000e 3ffe968a 3fff1c44  
3fff2bf0:  3fffdad0 0000000f 3fff1b88 40208171  
3fff2c00:  40104ec4 3ffe96cc 00000000 00000000  
3fff2c10:  0001693d 3fff19d8 3fff1c50 3fff19d8  
3fff2c20:  3fff521c 3fff1c44 40209f70 3fff1c50  
3fff2c30:  40201b7e 00001388 00001388 3fff1c44  
3fff2c40:  3fffdad0 3fff1938 00001388 402036cd  
3fff2c50:  feefeffe 00000000 3fff1c3d 40209fb4  
3fff2c60:  feefeffe feefeffe 3fff1c50 40100720  
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

Putting a private key on the device represents a HUGE security flaw

The ESP8266 is capable of using TLS 1.2 via the use of WiFiClientSecure, and then adding in IoT certificates properly via the use of espClient.setCertificate, espClient.setPrivateKey & espClient.setCACert.

While this project still works for people using older versions of the ESP8266, the readme should be amended to state that a proper connection using TLS 1.2 can now be accomplished. Examples of how this is done can be found here: https://github.com/copercini/esp8266-aws_iot

If internet becomes unavailable; ESP goes in wdt reset

Hello,
I checked out the code and works fine with AWS. However, I came across one issue.
After MQTT is subscribed and running, and then at any point after this if the ESP does not get access to internet (Wifi router is on), ESP goes in wdt reset mode. Maybe someone else also encountered this issue and has a fix for it?

pubsubclient sample cannot compile cannot declare variable 'awsWSclient' to be of abstract type 'AWSWebSocketClient'

Here is the errors after I compile. I'm using a NodeMCU 1.0 (ESP-12E Module) board.

aws-mqtt-websocket-example-pubsubclient:44: error: cannot declare variable 'awsWSclient' to be of abstract type 'AWSWebSocketClient'

AWSWebSocketClient awsWSclient(1000);

                ^

In file included from D:\Arduino\Wifi\aws-mqtt-websockets-master\examples\aws-mqtt-websocket-example-pubsubclient\aws-mqtt-websocket-example-pubsubclient.ino:21:0:

sketch\AWSWebSocketClient.h:25:7: note: because the following virtual functions are pure within 'AWSWebSocketClient':

class AWSWebSocketClient : public Client, private WebSocketsClient {

   ^

In file included from C:\Users\water\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0-beta1\libraries\ESP8266WiFi\src/WiFiClient.h:27:0,

             from C:\Users\water\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0-beta1\libraries\ESP8266WiFi\src/ESP8266WiFi.h:39,

             from D:\Arduino\Wifi\aws-mqtt-websockets-master\examples\aws-mqtt-websocket-example-pubsubclient\aws-mqtt-websocket-example-pubsubclient.ino:4:

C:\Users\water\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0-beta1\cores\esp8266/Client.h:29:21: note: virtual int Client::connect(const IPAddress&, uint16_t)

     virtual int connect(CONST IPAddress& ip, uint16_t port) =0;

                 ^

C:\Users\water\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0-beta1\cores\esp8266/Client.h:37:22: note: virtual bool Client::flush(unsigned int)

     virtual bool flush(unsigned int maxWaitMs = 0) = 0;

                  ^

C:\Users\water\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0-beta1\cores\esp8266/Client.h:38:22: note: virtual bool Client::stop(unsigned int)

     virtual bool stop(unsigned int maxWaitMs = 0) = 0;

                  ^

exit status 1
cannot declare variable 'awsWSclient' to be of abstract type 'AWSWebSocketClient'

Client disconnect - RX: HTTP/1.1 426 Upgrade Required

Hi,

since this morning I am unable to connecto the Websocket server. I looks like Amazon changed something server side (protocol requirements).

Any thoughts on this?

connected with ABC, channel 6
dhcp client start...
ip:10.11.10.201,mask:255.255.0.0,gw:10.11.0.1
ping 5, timeout 0, total payload 160 bytes, 5013 ms
Free heap size before AWS: 26312
pm open,type:2 0
[WS-Client] connect wss...
please start sntp first !
[WS-Client] connected to 123.iot.us-east-1.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] sending header... Done (160746us).
[WS-Client][handleHeader] RX: HTTP/1.1 101 Switching Protocols
[WS-Client][handleHeader] RX: content-length: 0
[WS-Client][handleHeader] RX: upgrade: websocket
[WS-Client][handleHeader] RX: connection: upgrade
[WS-Client][handleHeader] RX: sec-websocket-accept: Q0qdgdfdfg1X4EwVA/+NoP4=
[WS-Client][handleHeader] RX: sec-websocket-protocol: mqtt
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=x&X-Amz-Date=20160921T084332Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=54645645645645
[WS-Client][handleHeader] - cKey: sdfsfssdf==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader] - cCode: 101
[WS-Client][handleHeader] - cIsUpgrade: 0
[WS-Client][handleHeader] - cIsWebsocket: 1
[WS-Client][handleHeader] - cAccept: fsdfsf/+NoP4=
[WS-Client][handleHeader] - cProtocol: mqtt
[WS-Client][handleHeader] - cExtensions:
[WS-Client][handleHeader] - cVersion: 0
[WS-Client][handleHeader] no Websocket connection close.
[WS-Client] client disconnected.
[WS-Client] connect wss...
please start sntp first !
[WS-Client] connected to 123.iot.us-east-1.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] sending header... Done (138230us).
[WS-Client][handleHeader] RX: HTTP/1.1 426 Upgrade Required
[WS-Client][handleHeader] RX: content-type: application/json
[WS-Client][handleHeader] RX: content-length: 134
[WS-Client][handleHeader] RX: date: Wed, 21 Sep 2016 08:43:36 GMT
[WS-Client][handleHeader] RX: x-amzn-RequestId: 34140c5d-97b9-22fc-89e2-ba79daf799d0
[WS-Client][handleHeader] RX: connection: Keep-Alive
[WS-Client][handleHeader] RX: x-amzn-ErrorType: InternalFailureException:
[WS-Client][handleHeader] RX: sec-websocket-version: 13,8,7
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=sfsddsfsfsdf%sfsdf%c-east-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20160921T084332Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=sfsdfsdfdds
[WS-Client][handleHeader] - cKey: sfdsdfsdfd==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader] - cCode: 426
[WS-Client][handleHeader] - cIsUpgrade: 0
[WS-Client][handleHeader] - cIsWebsocket: 0
[WS-Client][handleHeader] - cAccept:
[WS-Client][handleHeader] - cProtocol:
[WS-Client][handleHeader] - cExtensions:
[WS-Client][handleHeader] - cVersion: 13
[WS-Client][handleHeader] no Websocket connection close.
[WS-Client] client disconnected.

"section type conflict" compile error

I tried to compile aws-mqtt-websocket-example-pubsubclient and got the error below - "error: mem_debug_file causes a section type conflict with __c"
The issue should be the same as - esp8266/Arduino#2078

I'd like to get your input on

  1. from your readme, can you share how you successfully compiled the binary?
  2. is the issue known to you? any thought fixing it?
    Otherwise, I will try to workaround it instead

C:\Users\xxx\Documents\ArduinoData\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1/tools/sdk/include" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1/tools/sdk/lwip2/include" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\xxx\AppData\Local\Temp\arduino_build_788939/core" -c -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -MMD -ffunction-sections -fdata-sections -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DDEBUG_ESP_PORT=Serial -DDEBUG_ESP_CORE -DDEBUG_ESP_WIFI -DDEBUG_ESP_HTTP_UPDATE -DDEBUG_ESP_UPDATER -DDEBUG_ESP_OTA -DDEBUG_ESP_OOM -include "umm_malloc/umm_malloc_cfg.h" -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\cores\esp8266" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\variants\nodemcu" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\libraries\ESP8266WiFi\src" "-IC:\Projects\esp8266\libraries\aws-sdk-arduino-master" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\libraries\Hash\src" "-IC:\Projects\esp8266\libraries\arduinoWebSockets-master\src" "-IC:\Projects\esp8266\libraries\pubsubclient-master\src" "-IC:\Projects\esp8266\libraries\aws-mqtt-websockets-master" "C:\Projects\esp8266\libraries\pubsubclient-master\src\PubSubClient.cpp" -o "C:\Users\xxx\AppData\Local\Temp\arduino_build_788939\libraries\pubsubclient-master\PubSubClient.cpp.o"
Compiling library "aws-mqtt-websockets-master"
"C:\Users\xxx\Documents\ArduinoData\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1/tools/sdk/include" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1/tools/sdk/lwip2/include" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\xxx\AppData\Local\Temp\arduino_build_788939/core" -c -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -MMD -ffunction-sections -fdata-sections -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DDEBUG_ESP_PORT=Serial -DDEBUG_ESP_CORE -DDEBUG_ESP_WIFI -DDEBUG_ESP_HTTP_UPDATE -DDEBUG_ESP_UPDATER -DDEBUG_ESP_OTA -DDEBUG_ESP_OOM -include "umm_malloc/umm_malloc_cfg.h" -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\cores\esp8266" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\variants\nodemcu" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\libraries\ESP8266WiFi\src" "-IC:\Projects\esp8266\libraries\aws-sdk-arduino-master" "-IC:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\libraries\Hash\src" "-IC:\Projects\esp8266\libraries\arduinoWebSockets-master\src" "-IC:\Projects\esp8266\libraries\pubsubclient-master\src" "-IC:\Projects\esp8266\libraries\aws-mqtt-websockets-master" "C:\Projects\esp8266\libraries\aws-mqtt-websockets-master\AWSWebSocketClient.cpp" -o "C:\Users\xxx\AppData\Local\Temp\arduino_build_788939\libraries\aws-mqtt-websockets-master\AWSWebSocketClient.cpp.o"
In file included from C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\cores\esp8266/Arduino.h:304:0,
from C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\libraries\ESP8266WiFi\src/WiFiClient.h:25,
from C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\libraries\ESP8266WiFi\src/ESP8266WiFi.h:39,
from C:\Projects\esp8266\libraries\arduinoWebSockets-master\src/WebSockets.h:133,
from C:\Projects\esp8266\libraries\arduinoWebSockets-master\src/WebSocketsClient.h:28,
from C:\Projects\esp8266\libraries\aws-mqtt-websockets-master\AWSWebSocketClient.h:7,
from C:\Projects\esp8266\libraries\aws-mqtt-websockets-master\AWSWebSocketClient.cpp:1:
C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\cores\esp8266/umm_malloc/umm_malloc_cfg.h:188:40: error: mem_debug_file causes a section type conflict with __c
#define malloc(s) ({ static const char mem_debug_file[] ICACHE_RODATA_ATTR STORE_ATTR = FILE; malloc_loc(s, mem_debug_file, LINE); })
^
C:\Projects\esp8266\libraries\aws-mqtt-websockets-master\CircularByteBuffer.h:42:18: note: in expansion of macro 'malloc'
data = (byte*) malloc (capacity);
^
In file included from C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\cores\esp8266/Arduino.h:258:0,
from C:\Projects\esp8266\libraries\aws-mqtt-websockets-master\AWSWebSocketClient.h:4,
from C:\Projects\esp8266\libraries\aws-mqtt-websockets-master\AWSWebSocketClient.cpp:1:
C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\cores\esp8266/pgmspace.h:16:51: note: '__c' was declared here
#define PSTR(s) (extension({static const char __c[] PROGMEM = (s); &__c[0];}))
^
C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\cores\esp8266/WString.h:38:76: note: in definition of macro 'FPSTR'
#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))
^
C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\cores\esp8266/WString.h:39:34: note: in expansion of macro 'PSTR'
#define F(string_literal) (FPSTR(PSTR(string_literal)))
^
C:\Projects\esp8266\libraries\aws-mqtt-websockets-master\AWSWebSocketClient.cpp:433:27: note: in expansion of macro 'F'
begin (host,port,path,F("mqtt"));
^
Using library ESP8266WiFi at version 1.0 in folder: C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\libraries\ESP8266WiFi
Using library aws-sdk-arduino-master in folder: C:\Projects\esp8266\libraries\aws-sdk-arduino-master (legacy)
Using library Hash at version 1.0 in folder: C:\Users\xxx\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.4.1\libraries\Hash
Using library arduinoWebSockets-master at version 2.1.0 in folder: C:\Projects\esp8266\libraries\arduinoWebSockets-master
Using library pubsubclient-master at version 2.6 in folder: C:\Projects\esp8266\libraries\pubsubclient-master
Using library aws-mqtt-websockets-master in folder: C:\Projects\esp8266\libraries\aws-mqtt-websockets-master (legacy)
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

not able to connect to AWS IOT

Hi! Awesome job on getting the ESP8266 talking with AWS IOT. I have set up a "thing" on my AWS IOT account. I used the credentials created for a single user with AWS IOT privileges, verified the end point path, region and the like via the details output from the AWS IOS console and populate the AWS IOT config variables. I'm using a NodeMCU 0.9(ESP-12 Module), 80MHz, 115200, 4M (3M SPIFFS) for the build option in the IDE. I'm able to get an internet connection via Wifi router but it fails when attempting to connect to AWS. Should I have some other configuration completed in the AWS IOT console? I basically have a single user with iot credentials and then used that to create a thing. Thanks for any help.

Serial console out put...
connected
error connection to the websocket server
error connection to the websocket server

Serial output from the more verbose memleak debug version...
error connection to the websocket server
38923 - conn: 5 - (27216)
error connection to the websocket server
46364 - conn: 6 - (27216)
error connection to the websocket server
53837 - conn: 7 - (27216)
error connection to the websocket server
61294 - conn: 8 - (27216)

undefined reference to 'gmtime_r' in Stream.h and AWSWebSocketClient.h

i was trying to run examples and when i tried to compile this error occurred. What could possible be the cause of this error and how to fix it?

Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Build options changed, rebuilding all
Archiving built core (caching) in: C:\Users\lpxed\AppData\Local\Temp\arduino_cache_110068\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____58eaac4747090ff4d9dbc37c18df4663.a
libraries\aws-mqtt-websockets-master\AWSWebSocketClient.cpp.o: In function `AWSWebSocketClient::ntpFixNumber(int)':

C:\Users\lpxed\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/Stream.h:93: undefined reference to `gmtime_r'

libraries\aws-mqtt-websockets-master\AWSWebSocketClient.cpp.o:(.text._ZN18AWSWebSocketClient17getCurrentTimeNTPEv+0x33): undefined reference to `gmtime_r'

libraries\aws-mqtt-websockets-master\AWSWebSocketClient.cpp.o: In function `AWSWebSocketClient::getCurrentTimeNTP()':

C:\Users\lpxed\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/Stream.h:93: undefined reference to `gmtime_r'

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Generic ESP8266 Module.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

MQTT publish big size payload

Hello,

I have big size payload to send through AWS MQTT. Paload size is more than 800 characters. For small size string it is working fine but not with big size.

Can you please share any way to free the Message objects or buf ?

Thanks

How to change the 'aws_topic'

Hello,
I want to create dynamic mqtt topic, such as:

String	TmpStr = "";
TmpStr = "$aws/things/TestIot/shadow/get/accepted";//example, this topic will input from other channel
aws_topic = TmpStr.c_str();
subscribe();

The Esp8266 can response 'MQTT subscribed' and seems okay. But it can not receive any message.

If I change the code as:

aws_topic = "$aws/things/TestIot/shadow/get/accepted";
subscribe();

The Esp8266 work well.

How to change the 'aws_topic'?

Callback function doesn't execute while sub on get/accepted shadow

i am working on esp8266 connected to aws iot ,My project is to control lamp through esp8266 so after reading what should i do for getting the response from get/accepted shadow
i have to send empty parenthesis on get shadow then receive from get/accepted shadow

the problem here that i don't receive any responses from get/accepted shadow
and callback function didnt called untill now
also i tried to increase the size of mqtt packet but nothing happened

Here what i should receive on get/accepted shadow

{
"state": {
"desired": {
"Switch": 1,
"power": "0"
},
"delta": {
"Switch": 1,
"power": "0"
}
},
"metadata": {
"desired": {
"Switch": {
"timestamp": 1563210303
},
"power": {
"timestamp": 1563210303
}
}
},
"version": 6,
"timestamp": 1563322772
}

Here is the code

`#include <Arduino.h>
#include <Stream.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

//AWS
#include "sha256.h"
#include "Utils.h"

//WEBSockets
#include <Hash.h>
#include <WebSocketsClient.h>

//MQTT PUBSUBCLIENT LIB
#include <PubSubClient.h>

//AWS MQTT Websocket
#include "Client.h"
#include "AWSWebSocketClient.h"
#include "CircularByteBuffer.h"

extern "C" {
#include "user_interface.h"
}

//AWS IOT config, change these:

char wifi_ssid[] = "Hopa";
char wifi_password[] = "HopaInternet00";
char aws_endpoint[] = "xxxxxxxxxxxxxxxxxxx";
char aws_key[] = "xxxxxxxxxxxxxxxxxxxxx";
char aws_secret[] = "xxxxxxxxxxxxxxx";
char aws_region[] = "xxxxxxxxxxxxxxxxx";
const char* aws_topic_sub = "$aws/things/esp/shadow/get/accepted";
const char* aws_topic_pub = "$aws/things/esp/shadow/get";
int port = 443;

//MQTT config
const int maxMQTTpackageSize = 1048;
const int maxMQTTMessageHandlers = 1;

ESP8266WiFiMulti WiFiMulti;

AWSWebSocketClient awsWSclient(1000);

PubSubClient client(awsWSclient);

//# of connections
long connection = 0;

//generate random mqtt clientID
char* generateClientID () {
char* cID = new char23;
for (int i=0; i<22; i+=1)
cID[i]=(char)random(1, 256);
return cID;
}

//count messages arrived
int arrivedcount = 0;

//callback to handle mqtt messages
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}

//connects to websocket layer and mqtt layer
bool connect () {

if (client.connected()) {    
    client.disconnect ();
}  
//delay is not necessary... it just help us to get a "trustful" heap space value
delay (1000);
Serial.print (millis ());
Serial.print (" - conn: ");
Serial.print (++connection);
Serial.print (" - (");
Serial.print (ESP.getFreeHeap ());
Serial.println (")");


//creating random client id
char* clientID = generateClientID ();

client.setServer(aws_endpoint, port);
if (client.connect(clientID)) {
  Serial.println("connected");     
  return true;
} else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  return false;
}

}

//subscribe to a mqtt topic
void subscribe () {
client.setCallback(callback);
client.subscribe(aws_topic_sub);
//subscript to a topic
Serial.println("MQTT subscribed");
}

//send a message to a mqtt topic
void sendmessage () {
//send a message
char buf[100];
strcpy(buf, "{ }");
int rc = client.publish(aws_topic_pub, buf);
}

void setup() {
wifi_set_sleep_type(NONE_SLEEP_T);
Serial.begin (115200);
delay (2000);
Serial.setDebugOutput(1);

//fill with ssid and wifi password
WiFiMulti.addAP(wifi_ssid, wifi_password);
Serial.println ("connecting to wifi");
while(WiFiMulti.run() != WL_CONNECTED) {
    delay(100);
    Serial.print (".");
}
Serial.println ("\nconnected");

//fill AWS parameters    
awsWSclient.setAWSRegion(aws_region);
awsWSclient.setAWSDomain(aws_endpoint);
awsWSclient.setAWSKeyID(aws_key);
awsWSclient.setAWSSecretKey(aws_secret);
awsWSclient.setUseSSL(true);

if (connect ()){
  
  subscribe ();
sendmessage ();
  
}

}

void loop() {

//keep the mqtt up and running
if (awsWSclient.connected ()) {
delay(100);
client.loop ();
delay(100);
subscribe ();
sendmessage ();

}
else {
//handle reconnection
if (connect ()){
subscribe ();

}

}

}`

Eratic connection

I manage to connect / publish / subscribe but the connection works pretty randomly and may takes many attempts. The connection is stable once established. Any idea what it could be ?

Here under 2 consecutive loops, one fails the second works....

[WS-Client] client disconnected.
[WS-Client] connect wss...
State: sending Client Hello (1)
State: receiving Server Hello (2)
State: receiving Certificate (11)
=== CERTIFICATE ISSUED TO ===
Common Name (CN): *.iot.us-west-2.amazonaws.com
Organization (O):
Basic Constraints: critical, CA:FALSE, pathlen:10000
Key Usage: critical, Digital Signature, Key Encipherment
Subject Alt Name: iot.us-west-2.amazonaws.com *.iot.us-west-2.amazonaws.com
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Amazon
Organization (O): Amazon
Organizational Unit (OU): Server CA 1B
Country (C): US
Not Before: Thu Aug 2 00:00:00 2018
Not After: Fri Aug 2 12:00:00 2019
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Amazon
Organization (O): Amazon
Organizational Unit (OU): Server CA 1B
Country (C): US
Basic Constraints: critical, CA:TRUE, pathlen:0
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Amazon Root CA 1
Organization (O): Amazon
Country (C): US
Not Before: Thu Oct 22 00:00:00 2015
Not After: Sun Oct 19 00:00:00 2025
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Amazon Root CA 1
Organization (O): Amazon
Country (C): US
Basic Constraints: critical, CA:TRUE, pathlen:10000
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Starfield Services Root Certificate Authority - G2
Organization (O): Starfield Technologies, Inc.
Location (L): Scottsdale
Country (C): US
State (ST): Arizona
Not Before: Mon May 25 12:00:00 2015
Not After: Thu Dec 31 01:00:00 2037
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Starfield Services Root Certificate Authority - G2
Organization (O): Starfield Technologies, Inc.
Location (L): Scottsdale
Country (C): US
State (ST): Arizona
Basic Constraints: critical, CA:TRUE, pathlen:10000
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN):
Organization (O): Starfield Technologies, Inc.
Organizational Unit (OU): Starfield Class 2 Certification Authority
Country (C): US
Not Before: Wed Sep 2 00:00:00 2009
Not After: Wed Jun 28 17:39:16 2034
RSA bitsize: 2048
Sig Type: SHA256
State: receiving Server Hello Done (14)
State: sending Client Key Exchange (16)
State: sending Finished (16)
State: receiving Finished (16)
[WS-Client] connected to MY_ENDPOINT-ats.iot.us-west-2.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] handshake GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MY_ACCES_KEY%2F19700101%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080004Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=77145f9661eb7e049b4b3d670d268f3eb2da39f0e38c42b72061de1a6eaed150 HTTP/1.1
Host: MY_ENDPOINT-ats.iot.us-west-2.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: BqqtCJcdb4cqFzjx3BWKjQ==
Sec-WebSocket-Protocol: mqtt
Origin: file://
User-Agent: arduino-WebSocket-Client

[write] n: zu t: 559
[WS-Client][sendHeader] sending header... Done (78040us).
[WS-Client][handleHeader] RX: HTTP/1.1 403 Forbidden
[WS-Client][handleHeader] RX: content-type: application/json
[WS-Client][handleHeader] RX: content-length: 163
[WS-Client][handleHeader] RX: date: Wed, 20 Feb 2019 02:33:14 GMT
[WS-Client][handleHeader] RX: x-amzn-RequestId: e5b733f6-071e-27d7-38c6-523dbe228518
[WS-Client][handleHeader] RX: connection: keep-alive
[WS-Client][handleHeader] RX: x-amzn-ErrorType: ForbiddenException:
[WS-Client][handleHeader] RX: access-control-allow-origin: *
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorMessage
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-RequestId
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorType
[WS-Client][handleHeader] RX: access-control-expose-headers: Date
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MY_ACCES_KEY%2F19700101%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080004Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=77145f9661eb7e049b4b3d670d268f3eb2da39f0e38c42b72061de1a6eaed150
[WS-Client][handleHeader] - cKey: BqqtCJcdb4cqFzjx3BWKjQ==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader] - cCode: 403
[WS-Client][handleHeader] - cIsUpgrade: 0
[WS-Client][handleHeader] - cIsWebsocket: 0
[WS-Client][handleHeader] - cAccept:
[WS-Client][handleHeader] - cProtocol: mqtt
[WS-Client][handleHeader] - cExtensions:
[WS-Client][handleHeader] - cVersion: 0
[WS-Client][handleHeader] - cSessionId:
[WS-Client][handleHeader] no Websocket connection close.
[write] n: zu t: 27
Alert: close notify
[WS-Client] client disconnected.
[WS-Client] client disconnected.
[WS-Client] connect wss...
State: sending Client Hello (1)
State: receiving Server Hello (2)
State: receiving Certificate (11)
=== CERTIFICATE ISSUED TO ===
Common Name (CN): *.iot.us-west-2.amazonaws.com
Organization (O):
Basic Constraints: critical, CA:FALSE, pathlen:10000
Key Usage: critical, Digital Signature, Key Encipherment
Subject Alt Name: iot.us-west-2.amazonaws.com *.iot.us-west-2.amazonaws.com
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Amazon
Organization (O): Amazon
Organizational Unit (OU): Server CA 1B
Country (C): US
Not Before: Thu Aug 2 00:00:00 2018
Not After: Fri Aug 2 12:00:00 2019
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Amazon
Organization (O): Amazon
Organizational Unit (OU): Server CA 1B
Country (C): US
Basic Constraints: critical, CA:TRUE, pathlen:0
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Amazon Root CA 1
Organization (O): Amazon
Country (C): US
Not Before: Thu Oct 22 00:00:00 2015
Not After: Sun Oct 19 00:00:00 2025
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Amazon Root CA 1
Organization (O): Amazon
Country (C): US
Basic Constraints: critical, CA:TRUE, pathlen:10000
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Starfield Services Root Certificate Authority - G2
Organization (O): Starfield Technologies, Inc.
Location (L): Scottsdale
Country (C): US
State (ST): Arizona
Not Before: Mon May 25 12:00:00 2015
Not After: Thu Dec 31 01:00:00 2037
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Starfield Services Root Certificate Authority - G2
Organization (O): Starfield Technologies, Inc.
Location (L): Scottsdale
Country (C): US
State (ST): Arizona
Basic Constraints: critical, CA:TRUE, pathlen:10000
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN):
Organization (O): Starfield Technologies, Inc.
Organizational Unit (OU): Starfield Class 2 Certification Authority
Country (C): US
Not Before: Wed Sep 2 00:00:00 2009
Not After: Wed Jun 28 17:39:16 2034
RSA bitsize: 2048
Sig Type: SHA256
State: receiving Server Hello Done (14)
State: sending Client Key Exchange (16)
State: sending Finished (16)
State: receiving Finished (16)
[WS-Client] connected to MY_ENDPOINT-ats.iot.us-west-2.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] handshake GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MY_ACCES_KEY%2F19700101%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080004Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=77145f9661eb7e049b4b3d670d268f3eb2da39f0e38c42b72061de1a6eaed150 HTTP/1.1
Host: MY_ENDPOINT-ats.iot.us-west-2.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: sA+TUDFa86ZvL5Ztmh4O/Q==
Sec-WebSocket-Protocol: mqtt
Origin: file://
User-Agent: arduino-WebSocket-Client

[write] n: zu t: 559
[WS-Client][sendHeader] sending header... Done (79310us).
[WS-Client][handleHeader] RX: HTTP/1.1 403 Forbidden
[WS-Client][handleHeader] RX: content-type: application/json
[WS-Client][handleHeader] RX: content-length: 163
[WS-Client][handleHeader] RX: date: Wed, 20 Feb 2019 02:33:17 GMT
[WS-Client][handleHeader] RX: x-amzn-RequestId: e1ed6f31-decb-fcfc-2dbe-bb7df7cfb315
[WS-Client][handleHeader] RX: connection: keep-alive
[WS-Client][handleHeader] RX: x-amzn-ErrorType: ForbiddenException:
[WS-Client][handleHeader] RX: access-control-allow-origin: *
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorMessage
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-RequestId
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorType
[WS-Client][handleHeader] RX: access-control-expose-headers: Date
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MY_ACCES_KEY%2F19700101%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080004Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=77145f9661eb7e049b4b3d670d268f3eb2da39f0e38c42b72061de1a6eaed150
[WS-Client][handleHeader] - cKey: sA+TUDFa86ZvL5Ztmh4O/Q==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader] - cCode: 403
[WS-Client][handleHeader] - cIsUpgrade: 0
[WS-Client][handleHeader] - cIsWebsocket: 0
[WS-Client][handleHeader] - cAccept:
[WS-Client][handleHeader] - cProtocol: mqtt
[WS-Client][handleHeader] - cExtensions:
[WS-Client][handleHeader] - cVersion: 0
[WS-Client][handleHeader] - cSessionId:
[WS-Client][handleHeader] no Websocket connection close.
[write] n: zu t: 27
Alert: close notify
[WS-Client] client disconnected.
[WS-Client] client disconnected.
[WS-Client] connect wss...
State: sending Client Hello (1)
State: receiving Server Hello (2)
State: receiving Certificate (11)
=== CERTIFICATE ISSUED TO ===
Common Name (CN): *.iot.us-west-2.amazonaws.com
Organization (O):
Basic Constraints: critical, CA:FALSE, pathlen:10000
Key Usage: critical, Digital Signature, Key Encipherment
Subject Alt Name: iot.us-west-2.amazonaws.com *.iot.us-west-2.amazonaws.com
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Amazon
Organization (O): Amazon
Organizational Unit (OU): Server CA 1B
Country (C): US
Not Before: Thu Aug 2 00:00:00 2018
Not After: Fri Aug 2 12:00:00 2019
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Amazon
Organization (O): Amazon
Organizational Unit (OU): Server CA 1B
Country (C): US
Basic Constraints: critical, CA:TRUE, pathlen:0
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Amazon Root CA 1
Organization (O): Amazon
Country (C): US
Not Before: Thu Oct 22 00:00:00 2015
Not After: Sun Oct 19 00:00:00 2025
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Amazon Root CA 1
Organization (O): Amazon
Country (C): US
Basic Constraints: critical, CA:TRUE, pathlen:10000
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Starfield Services Root Certificate Authority - G2
Organization (O): Starfield Technologies, Inc.
Location (L): Scottsdale
Country (C): US
State (ST): Arizona
Not Before: Mon May 25 12:00:00 2015
Not After: Thu Dec 31 01:00:00 2037
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Starfield Services Root Certificate Authority - G2
Organization (O): Starfield Technologies, Inc.
Location (L): Scottsdale
Country (C): US
State (ST): Arizona
Basic Constraints: critical, CA:TRUE, pathlen:10000
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN):
Organization (O): Starfield Technologies, Inc.
Organizational Unit (OU): Starfield Class 2 Certification Authority
Country (C): US
Not Before: Wed Sep 2 00:00:00 2009
Not After: Wed Jun 28 17:39:16 2034
RSA bitsize: 2048
Sig Type: SHA256
State: receiving Server Hello Done (14)
State: sending Client Key Exchange (16)
State: sending Finished (16)
State: receiving Finished (16)
[WS-Client] connected to MY_ENDPOINT-ats.iot.us-west-2.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] handshake GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MY_ACCES_KEY%2F19700101%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080004Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=77145f9661eb7e049b4b3d670d268f3eb2da39f0e38c42b72061de1a6eaed150 HTTP/1.1
Host: MY_ENDPOINT-ats.iot.us-west-2.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 6kN3CrJ2IdF3Jy9nx4tgrQ==
Sec-WebSocket-Protocol: mqtt
Origin: file://
User-Agent: arduino-WebSocket-Client

[write] n: zu t: 559
[WS-Client][sendHeader] sending header... Done (78657us).
[WS-Client][handleHeader] RX: HTTP/1.1 403 Forbidden
[WS-Client][handleHeader] RX: content-type: application/json
[WS-Client][handleHeader] RX: content-length: 163
[WS-Client][handleHeader] RX: date: Wed, 20 Feb 2019 02:33:19 GMT
[WS-Client][handleHeader] RX: x-amzn-RequestId: 612ceea9-8bb1-73d9-3cb1-f3b117766e94
[WS-Client][handleHeader] RX: connection: keep-alive
[WS-Client][handleHeader] RX: x-amzn-ErrorType: ForbiddenException:
[WS-Client][handleHeader] RX: access-control-allow-origin: *
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorMessage
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-RequestId
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorType
[WS-Client][handleHeader] RX: access-control-expose-headers: Date
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MY_ACCES_KEY%2F19700101%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080004Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=77145f9661eb7e049b4b3d670d268f3eb2da39f0e38c42b72061de1a6eaed150
[WS-Client][handleHeader] - cKey: 6kN3CrJ2IdF3Jy9nx4tgrQ==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader] - cCode: 403
[WS-Client][handleHeader] - cIsUpgrade: 0
[WS-Client][handleHeader] - cIsWebsocket: 0
[WS-Client][handleHeader] - cAccept:
[WS-Client][handleHeader] - cProtocol: mqtt
[WS-Client][handleHeader] - cExtensions:
[WS-Client][handleHeader] - cVersion: 0
[WS-Client][handleHeader] - cSessionId:
[WS-Client][handleHeader] no Websocket connection close.
[write] n: zu t: 27
Alert: close notify
[WS-Client] client disconnected.
[WS-Client] client disconnected.
failed, rc=-256389 - conn: 2 - (41176)
[WS-Client] client disconnected.
[WS-Client] connect wss...
State: sending Client Hello (1)
State: receiving Server Hello (2)
State: receiving Certificate (11)
=== CERTIFICATE ISSUED TO ===
Common Name (CN): *.iot.us-west-2.amazonaws.com
Organization (O):
Basic Constraints: critical, CA:FALSE, pathlen:10000
Key Usage: critical, Digital Signature, Key Encipherment
Subject Alt Name: iot.us-west-2.amazonaws.com *.iot.us-west-2.amazonaws.com
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Amazon
Organization (O): Amazon
Organizational Unit (OU): Server CA 1B
Country (C): US
Not Before: Thu Aug 2 00:00:00 2018
Not After: Fri Aug 2 12:00:00 2019
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Amazon
Organization (O): Amazon
Organizational Unit (OU): Server CA 1B
Country (C): US
Basic Constraints: critical, CA:TRUE, pathlen:0
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Amazon Root CA 1
Organization (O): Amazon
Country (C): US
Not Before: Thu Oct 22 00:00:00 2015
Not After: Sun Oct 19 00:00:00 2025
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Amazon Root CA 1
Organization (O): Amazon
Country (C): US
Basic Constraints: critical, CA:TRUE, pathlen:10000
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN): Starfield Services Root Certificate Authority - G2
Organization (O): Starfield Technologies, Inc.
Location (L): Scottsdale
Country (C): US
State (ST): Arizona
Not Before: Mon May 25 12:00:00 2015
Not After: Thu Dec 31 01:00:00 2037
RSA bitsize: 2048
Sig Type: SHA256
=== CERTIFICATE ISSUED TO ===
Common Name (CN): Starfield Services Root Certificate Authority - G2
Organization (O): Starfield Technologies, Inc.
Location (L): Scottsdale
Country (C): US
State (ST): Arizona
Basic Constraints: critical, CA:TRUE, pathlen:10000
Key Usage: critical, Digital Signature, Key Cert Sign, CRL Sign
=== CERTIFICATE ISSUED BY ===
Common Name (CN):
Organization (O): Starfield Technologies, Inc.
Organizational Unit (OU): Starfield Class 2 Certification Authority
Country (C): US
Not Before: Wed Sep 2 00:00:00 2009
Not After: Wed Jun 28 17:39:16 2034
RSA bitsize: 2048
Sig Type: SHA256
State: receiving Server Hello Done (14)
State: sending Client Key Exchange (16)
State: sending Finished (16)
State: receiving Finished (16)
[WS-Client] connected to MY_ENDPOINT-ats.iot.us-west-2.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] handshake GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MY_ACCES_KEY%2F20190220%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20190220T023320Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=ae191dc65e77d05ddbb6edff1c6e255bab2afb2d3436a1d7b23065c03331c81a HTTP/1.1
Host: MY_ENDPOINT-ats.iot.us-west-2.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 7ohN4jIx+1/rQmEro5dWlA==
Sec-WebSocket-Protocol: mqtt
Origin: file://
User-Agent: arduino-WebSocket-Client

[write] n: zu t: 559
[WS-Client][sendHeader] sending header... Done (78718us).
[WS-Client][handleHeader] RX: HTTP/1.1 101 Switching Protocols
[WS-Client][handleHeader] RX: content-length: 0
[WS-Client][handleHeader] RX: upgrade: websocket
[WS-Client][handleHeader] RX: connection: upgrade
[WS-Client][handleHeader] RX: sec-websocket-accept: DNS6xlnM82WiR4Wm0ikqp7GjSuI=
[WS-Client][handleHeader] RX: sec-websocket-protocol: mqtt
[WS-Client][handleHeader] RX: access-control-allow-origin: *
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorMessage
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-RequestId
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorType
[WS-Client][handleHeader] RX: access-control-expose-headers: Date
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=MY_ACCES_KEY%2F20190220%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20190220T023320Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=ae191dc65e77d05ddbb6edff1c6e255bab2afb2d3436a1d7b23065c03331c81a
[WS-Client][handleHeader] - cKey: 7ohN4jIx+1/rQmEro5dWlA==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader] - cCode: 101
[WS-Client][handleHeader] - cIsUpgrade: 1
[WS-Client][handleHeader] - cIsWebsocket: 1
[WS-Client][handleHeader] - cAccept: DNS6xlnM82WiR4Wm0ikqp7GjSuI=
[WS-Client][handleHeader] - cProtocol: mqtt
[WS-Client][handleHeader] - cExtensions:
[WS-Client][handleHeader] - cVersion: 0
[WS-Client][handleHeader] - cSessionId:
[WS-Client][handleHeader] Websocket connection init done.

Connection failed because of inproper initialization

There seems to be an initialization issue with the WSclient_t struct of the base class (WebSocketsClient)
I found using AWSWebSocketClient as global member (also static) worked with my sketch but
When allocating the AWSWebSocketClient on the heap it crahes.

The problem is that the WSclient_t struct of the base class is only initialized from the begin() function.
But when calling the AWSWebSocketClient::connect for the first time it calls stop() and leads to WebSocketsClient::disconnect() / WebSocketsClient::clientIsConnected. And here it crashes because the access of client->tcp which was is not initialized yet.

As a solution you could offer a initialization (e.g. begin) routine or do some initialization in the constructor.
Putting
begin("",0);
at the end of the AWSWebSocketClient::AWSWebSocketClient` solved for me the problem

403 Forbidden

Hi odelot,

Great Work. I tried to get the example script working. Unfortunately I keep getting 403 Forbidden Messages from the aws Server. I used aws-mqtt-websockets from the repository with the updated example from this post: #2 (comment)
Here is the Debug-Output. Do you have any idea what I could have done wrong ?

please start sntp first !
[WS-Client] connected to A2BF8DY97CWJ2U.iot.us-west-2.amazonaws.com:443.
[WS-Client][sendHeader] sending header...

-->GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AWSKEY%F 20160527%F us-west-2%F iotdevicegateway%F aws4_request&X-Amz-Date=20160527T075257Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=65544570a55cf2d17c676a04d4c3203c5096ad0232eef36eb773d1162c23e067 HTTP/1.1
Host: A2BF8DY97CWJ2U.iot.us-west-2.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Origin: file://
User-Agent: arduino-WebSocket-Client
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: JR5yCYxsfpFwLFbxlhTUEA==
Sec-WebSocket-Protocol: mqtt

[WS-Client][sendHeader] sending header... Done (284875us).
[WS-Client][handleHeader] RX: HTTP/1.1 403 Forbidden
[WS-Client][handleHeader] RX: content-type: application/json
[WS-Client][handleHeader] RX: content-length: 241
[WS-Client][handleHeader] RX: date: Fri, 27 May 2016 07:53:00 GMT
[WS-Client][handleHeader] RX: x-amzn-RequestId: 7b224257-875c-42e6-9c4c-46b471ea8570
[WS-Client][handleHeader] RX: connection: Keep-Alive
[WS-Client][handleHeader] RX: x-amzn-ErrorType: ForbiddenException:
[WS-Client][handleHeader] RX: access-control-allow-origin: *
[WS-Client][handleHeader] RX: access-control-allow-headers: Authorization
[WS-Client][handleHeader] RX: access-control-allow-headers: X-amz-security-token
[WS-Client][handleHeader] RX: access-control-allow-headers: Accept
[WS-Client][handleHeader] RX: access-control-allow-headers: X-amz-date
[WS-Client][handleHeader] RX: access-control-allow-headers: X-amz-user-agent
[WS-Client][handleHeader] RX: access-control-allow-headers: X-amz-content-sha256
[WS-Client][handleHeader] RX: access-control-allow-headers: Accept-Language
[WS-Client][handleHeader] RX: access-control-allow-headers: X-requested-with
[WS-Client][handleHeader] RX: access-control-allow-headers: Content-Language
[WS-Client][handleHeader] RX: access-control-allow-headers: Content-Type
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorMessage
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-RequestId
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorType
[WS-Client][handleHeader] RX: access-control-expose-headers: Date
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AWSKEY%2F20160527%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20160527T075257Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=65544570a55cf2d17c676a04d4c3203c5096ad0232eef36eb773d1162c23e067
[WS-Client][handleHeader] - cKey: JR5yCYxsfpFwLFbxlhTUEA==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader] - cCode: 403
[WS-Client][handleHeader] - cIsUpgrade: 0
[WS-Client][handleHeader] - cIsWebsocket: 1
[WS-Client][handleHeader] - cAccept:
[WS-Client][handleHeader] - cProtocol: mqtt
[WS-Client][handleHeader] - cExtensions:
[WS-Client][handleHeader] - cVersion: 0
[WS-Client][handleHeader] no Websocket connection close.
[WS-Client] client disconnected.
[AWSc] Disconnected!
[WS-Client] connect wss...

How to subscribe to multiple topic using paho MQTT in arduino

i am able to publish to multiple topic
how do i subscribe to multiple topic1 and topic 2
right now only topic1 i can subscribe

void subscribe(){

//subscript to a topic

client->subscribe(topic1,MQTT::QOS0,messageArrived1);

client->subscribe(topic2,MQTT::QOS0,messageArrived2);

}

void messageArrived1(MQTT::MessageData& md)
{
MQTT::Message &message = md.message;

char* msg = new charmessage.payloadlen+1;
memcpy (msg,message.payload,message.payloadlen);
json_msg = msg;
Serial.print(json_msg);
parse_json();
delete msg;

}
void messageArrived2(MQTT::MessageData& Md)
{
MQTT::Message &message = Md.message;

char* msg = new charmessage.payloadlen+1;
memcpy (msg,message.payload,message.payloadlen);
json_msg = msg;
Serial.print(json_msg);
parse_json();
delete msg;

}

Need subscribe example

I have trying to figure out how to get the desired shadow from AWS. Publishing the state is no issue.

I think I found the solution here: https://github.com/heskew/aws-sdk-arduino/blob/iot-get-shadow-and-cleanup/src/common/AmazonIOTClient.cpp but I'm failing to put it together. I have attempted to reach out to the author without success.

If we can get the subscribe function in the example (https://github.com/odelot/aws-mqtt-websockets/blob/master/examples/aws-mqtt-websocket-example/aws-mqtt-websocket-example.ino) to return the value from AWS, we have a full solution.

I have reached out to you via twitter to offer compensation for your efforts as well.

ESP32 supported?

Hi,
I enjoyed using this library on ESP8266 for a while now. Worked like charm.
Now i tried to make it work on an ESP32, unfortunately there is always an exception when trying to connect to AWS.
Could you pinpoint where the problem is?

6450 - conn: 1 - (223004)
Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x400de9e0  PS      : 0x00060e30  A0      : 0x800dfab8  A1      : 0x3ffb1890  
A2      : 0x3ffccd18  A3      : 0x3ffccd38  A4      : 0x000000fe  A5      : 0x00000000  
A6      : 0x00ff0000  A7      : 0x0000003e  A8      : 0x800df9d9  A9      : 0x3ffb18a0  
A10     : 0xfefefefe  A11     : 0x3f403cc4  A12     : 0x00000002  A13     : 0x0000ff00  
A14     : 0x00ff0000  A15     : 0xff000000  SAR     : 0x0000000a  EXCCAUSE: 0x0000001c  
EXCVADDR: 0xfefefefe  LBEG    : 0x4000c46c  LEND    : 0x4000c477  LCOUNT  : 0x00000000  

Backtrace: 0x400de9e0:0x3ffb1890 0x400dfab5:0x3ffb18b0 0x400e0c2e:0x3ffb18d0 0x400d5814:0x3ffb1920 0x400d59de:0x3ffb19a0 0x400d4239:0x3ffb19d0 0x4014efde:0x3ffb1fa0

0x400de9e0: WebSocketsClient::clientDisconnect(WSclient_t*) at WString.h line 47
0x400de9e0: WebSocketsClient::clientDisconnect(WSclient_t*) at WString.h line 47
0x400dfab5: AWSWebSocketClient::stop() at AWSWebSocketClient.cpp line 526
0x400e0c2e: AWSWebSocketClient::connect(char const*, unsigned short) at AWSWebSocketClient.cpp line 526
0x400d5814: IPStack::connect(char*, int) at awsIot.cpp line 153
:  (inlined by) AwsIotClient::connect() at awsIot.cpp line 58
0x400d59de: AwsIotClient::init(FP ) at awsIot.cpp line 153
0x400d4239: setup() at CoffeemakerPS.ino line 130 (discriminator 5)
0x4014efde: loopTask(void*) at main.cpp line 15

Kind regards
David

Not seeing aws subscribed messages

I have all the code configured correctly. I see 'MQTT subscribed' and sometimes see the 'Message arrived ["state":{"reported":{"on": false}, "desired":{"on": false}}}' In my Serial Print. I can't see the message though in the AWS subscription though

mqtt-websockets for mosquitto

Hi,

Any chance of porting the library so it can support the mosquitto broker?

Havent try to use it as it is with the mosquitto broker but as i understand the technology is similar.

Thanks,

Zen

Aws-mqtt-websockets device stopped working

Hello, something very strange happened to me, for months I was running an iot device based on ESP8266 that was connected (by aws-mqtt-websockets) to AWS to read instructions from the shadow of a thing, but since yesterday it does not work, I thought it was the hardware but everything is fine, checking the programming I realize that I can no longer establish the connection to the server websocket, I checked the credentials (IAM) and I see that they have 183 days of creation, so I tried new credentials but the problem was not solved. Any ideas or suggestions?

Frequent websocket disconnects from AWS for no apparent reason

Hi, Im using this Library and am experiencing frequent (every 4-5 Seconds) disconnects of the websocket connection. Is this normal? according to AWS you should be able to maintain a connection for 24 hours nowadays. Has anyone else experienced this behavior?

Does not connect with current arduinoWebSockets version

Hi,
I had the connection error issue with 403 Forbidden message. It turned out there was an error in the header string caused by the latest commits of Links2004's arduinoWebSockets library. By checking out an older version of that dependency (b3efb31) I managed to solve the problem. Maybe we can fix this somehow.
Best,

Cannot subscribe to 2 topics. Lots of reconnects.

Hi,
I am unable to subscribe to more than 2 topics. Also, there are lots of reconnections, even if I keep publishing.

The code that I changed are

void loop() {
  //keep the mqtt up and running
  if (awsWSclient.connected ()) {
    delay(2000);
    sendmessage();
    client->yield();
  } else {
    //handle reconnection
    if (connect ()) {
      subscribe ();
      sendmessage ();
    }
  }

}

and

void subMessage1(MQTT::MessageData& md) {
  Serial.print("Topic ");
  Serial.println(aws_sub1);
  messageArrived(md);
}
void subMessage2(MQTT::MessageData& md) {
  Serial.print("Topic ");
  Serial.println(aws_sub2);
  messageArrived(md);
}

and

//subscribe to a mqtt topic
void subscribe () {
  //subscript to a topic
  int rc1 = client->subscribe(aws_sub1, MQTT::QOS0, subMessage1);
  if (rc1 != 0) {
    Serial.print("rc from MQTT subscribe is ");
    Serial.println(rc1);
    return;
  }
  Serial.println("MQTT subscribed");

  int rc2 = client->subscribe(aws_sub2, MQTT::QOS0, subMessage2);
  if (rc2 != 0) {
    Serial.print("rc from MQTT subscribe is ");
    Serial.println(rc2);
    return;
  }
  Serial.println("MQTT subscribed");
}

Full code is as follows:

#include <Arduino.h>
#include <Stream.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

//AWS
#include "sha256.h"
#include "Utils.h"

//WEBSockets
#include <Hash.h>
#include <WebSocketsClient.h>

//MQTT PAHO
#include <SPI.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>



//AWS MQTT Websocket
#include "Client.h"
#include "AWSWebSocketClient.h"
#include "CircularByteBuffer.h"

//AWS IOT config, change these:
char wifi_ssid[]       = "Amped_TAPR2_2.4";
char wifi_password[]   = "6aeb76df";
char aws_endpoint[]    = "aly36d4whljst.iot.us-west-2.amazonaws.com";
char aws_key[]         = "AKIAJII65UM7AOKSSBTQ";
char aws_secret[]      = "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";
char aws_region[]      = "us-west-2";
const char* aws_pub  = "$aws/things/ESPNODE/shadow/update";
const char* aws_sub1  = "espnode/lcd1";
const char* aws_sub2  = "espnode/lcd2";
int port = 443;

//MQTT config
const int maxMQTTpackageSize = 512;
const int maxMQTTMessageHandlers = 1;

ESP8266WiFiMulti WiFiMulti;

AWSWebSocketClient awsWSclient(1000);

IPStack ipstack(awsWSclient);
MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> *client = NULL;

//# of connections
long connection = 0;

//generate random mqtt clientID
char* generateClientID () {
  char* cID = new char[23]();
  for (int i = 0; i < 22; i += 1)
    cID[i] = (char)random(1, 256);
  return cID;
}

//count messages arrived
int arrivedcount = 0;


void subMessage1(MQTT::MessageData& md) {
  Serial.print("Topic ");
  Serial.println(aws_sub1);
  messageArrived(md);
}
void subMessage2(MQTT::MessageData& md) {
  Serial.print("Topic ");
  Serial.println(aws_sub2);
  messageArrived(md);
}

//callback to handle mqtt messages
void messageArrived(MQTT::MessageData& md)
{
  MQTT::Message &message = md.message;

  Serial.print("Message ");
  Serial.print(++arrivedcount);
  Serial.print(" arrived: qos ");
  Serial.print(message.qos);
  Serial.print(", retained ");
  Serial.print(message.retained);
  Serial.print(", dup ");
  Serial.print(message.dup);
  Serial.print(", packetid ");
  Serial.println(message.id);
  Serial.print("Payload ");
  char* msg = new char[message.payloadlen + 1]();
  memcpy (msg, message.payload, message.payloadlen);
  Serial.println(msg);
  delete msg;
}

//connects to websocket layer and mqtt layer
bool connect () {

  if (client == NULL) {
    client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
  } else {

    if (client->isConnected ()) {
      client->disconnect ();
    }
    delete client;
    client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
  }


  //delay is not necessary... it just help us to get a "trustful" heap space value
  delay (1000);
  Serial.print (millis ());
  Serial.print (" - conn: ");
  Serial.print (++connection);
  Serial.print (" - (");
  Serial.print (ESP.getFreeHeap ());
  Serial.println (")");

  int rc = ipstack.connect(aws_endpoint, port);
  if (rc != 1)
  {
    Serial.println("error connection to the websocket server");
    return false;
  } else {
    Serial.println("websocket layer connected");
  }


  Serial.println("MQTT connecting");
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
  data.MQTTVersion = 3;
  char* clientID = generateClientID ();
  data.clientID.cstring = clientID;
  rc = client->connect(data);
  delete[] clientID;
  if (rc != 0)
  {
    Serial.print("error connection to MQTT server");
    Serial.println(rc);
    return false;
  }
  Serial.println("MQTT connected");
  return true;
}

//subscribe to a mqtt topic
void subscribe () {
  //subscript to a topic
  int rc1 = client->subscribe(aws_sub1, MQTT::QOS0, subMessage1);
  if (rc1 != 0) {
    Serial.print("rc from MQTT subscribe is ");
    Serial.println(rc1);
    return;
  }
  Serial.println("MQTT subscribed");

  int rc2 = client->subscribe(aws_sub2, MQTT::QOS0, subMessage2);
  if (rc2 != 0) {
    Serial.print("rc from MQTT subscribe is ");
    Serial.println(rc2);
    return;
  }
  Serial.println("MQTT subscribed");
}

//send a message to a mqtt topic
void sendmessage () {
  //send a message
  MQTT::Message message;
  char buf[100];
  strcpy(buf, "{\"state\":{\"reported\":{\"on\": false}, \"desired\":{\"on\": false}}}");
  message.qos = MQTT::QOS0;
  message.retained = false;
  message.dup = false;
  message.payload = (void*)buf;
  message.payloadlen = strlen(buf) + 1;
  int rc = client->publish(aws_pub, message);
}


void setup() {
  Serial.begin (115200);
  delay (2000);
  Serial.setDebugOutput(1);

  //fill with ssid and wifi password
  WiFiMulti.addAP(wifi_ssid, wifi_password);
  Serial.println ("connecting to wifi");
  while (WiFiMulti.run() != WL_CONNECTED) {
    delay(100);
    Serial.print (".");
  }
  Serial.println ("\nconnected");
  configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
  //fill AWS parameters
  awsWSclient.setAWSRegion(aws_region);
  awsWSclient.setAWSDomain(aws_endpoint);
  awsWSclient.setAWSKeyID(aws_key);
  awsWSclient.setAWSSecretKey(aws_secret);
  awsWSclient.setUseSSL(true);

  if (connect ()) {
    subscribe ();
    sendmessage ();
  }

}

void loop() {
  //keep the mqtt up and running
  if (awsWSclient.connected ()) {
    delay(2000);
    sendmessage();
    client->yield();
  } else {
    //handle reconnection
    if (connect ()) {
      subscribe ();
      sendmessage ();
    }
  }

}

freezes esp8266 after ~40 reconnection

probably a memory leak.

I hope to be in my library. The other option is inside the connection/desconnection procedure from paho mqtt and arduino websockets (out of my control)

Multiple Mqtt Subscription problem

Hello All,
I could subscribe to aws iot mqtt endpoint with a client connect, but could recieve mqtt messages for first topic but not subsequent topics. Please help me with solution for this problem.

Failed to connect with AWS

Hi, I double check the endpoint, port, key, secret.
Grant IoTFull control for users.

I received this error which looks like it could not connect to the Server.
pm open,type:0 0
failed, rc=-280152 - conn: 2 - (33272)

Please help what else could I check to know what is my problems.
Thank you very much.

messageArrived handler - how to get and parse the topic

How do you get the topicName from the messageArrived handler out of the MessageData argument?

I want to be able to know the particular topic that invoked the messageArrived callback.

NOTE: My subscribe function is loading several subscriptions during set-up so that I can get multiple topics calling the same messageArrived callback handler:

char *subscribeTopic[5] = {
"$aws/things/" THING_NAME "/shadow/update/accepted",
"$aws/things/" THING_NAME "/shadow/update/rejected",
"$aws/things/" THING_NAME "/shadow/update/delta",
"$aws/things/" THING_NAME "/shadow/get/accepted",
"$aws/things/" THING_NAME "/shadow/get/rejected"
};

//subscribe to a mqtt topic(s)
void subscribe () {

  for (int i=0; i<5; i++) {
    int rc = client->subscribe(subscribeTopic[i], MQTT::QOS0, messageArrived);
    if (rc != 0) {
      Serial.print("rc from MQTT subscribe is ");
      Serial.println(rc);
      break;
    }
    Serial.println("MQTT Topic subscribed");
  }

}

When I try to see the topicName inside the messageArrived handler, I am getting NULL values:

For example, this just prints a blank line as if the topicName wasn't passed back in the MessageData argument.
Serial.println(md.topicName.cstring);

aws-iot with esp8266 error

please help me on connecting with aws iot services with esp8266 12e. i am using example aws-mqtt-websocket example not able to connect with dashboard of aws iot the code is as follow and the error i get is (please start sntp first ! error connection to the websocket server)

`#include <Arduino.h>
#include <Stream.h>

#include <ESP8266WiFi.h>

//AWS
#include "sha256.h"
#include "Utils.h"
#include "AWSClient2.h"

//WEBSockets
#include <Hash.h>
#include <WebSocketsClient.h>

//MQTT PAHO
#include <SPI.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>

//AWS MQTT Websocket
#include "Client.h"
#include "AWSWebSocketClient.h"
#include "CircularByteBuffer.h"

//AWS IOT config, change these:

const char* ssid = "NPSE";
const char* password = "P/W070415";
char aws_endpoint[] = "aph0r6gk1etz5.iot.us-east-1.amazonaws.com";
char aws_key[] = "AKIAJDJA6HPCGZXG7N6Q";
char aws_secret[] = "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";
char aws_region[] = "us-east-1";
const char* aws_topic = "$aws/things/tutorial/shadow/update";
int port = 443;

//MQTT config
const int maxMQTTpackageSize = 512;
const int maxMQTTMessageHandlers = 1;

WiFiClientSecure espclient;

AWSWebSocketClient awsWSclient(1000);

IPStack ipstack(awsWSclient);

MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> *client = NULL;

//# of connections
long connection = 0;

//generate random mqtt clientID
char* generateClientID () {
char* cID = new char23;
for (int i=0; i<22; i+=1)
cID[i]=(char)random(1, 256);
return cID;
}

//count messages arrived
int arrivedcount = 0;

//callback to handle mqtt messages
void messageArrived(MQTT::MessageData& md)
{
MQTT::Message &message = md.message;

Serial.print("Message ");
Serial.print(++arrivedcount);
Serial.print(" arrived: qos ");
Serial.print(message.qos);
Serial.print(", retained ");
Serial.print(message.retained);
Serial.print(", dup ");
Serial.print(message.dup);
Serial.print(", packetid ");
Serial.println(message.id);
Serial.print("Payload ");
char* msg = new char[message.payloadlen+1]();
memcpy (msg,message.payload,message.payloadlen);
Serial.println(msg);
delete msg;

}

//connects to websocket layer and mqtt layer
bool connect () {

  if (client == NULL) {
    client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
  } else {

    if (client->isConnected ()) {    
      client->disconnect ();
    }  
    delete client;
    client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
  }


  //delay is not necessary... it just help us to get a "trustful" heap space value
  delay (1000);
  Serial.print (millis ());
  Serial.print (" - conn: ");
  Serial.print (++connection);
  Serial.print (" - (");
  Serial.print (ESP.getFreeHeap ());
  Serial.println (")");




 int rc = ipstack.connect(aws_endpoint, port);
 Serial.print(rc);

  if (rc != 1)
  {
    Serial.println("error connection to the websocket server");
    return false;
  } else {
    Serial.println("websocket layer connected");
  }


  Serial.println("MQTT connecting");
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
  data.MQTTVersion = 3;
  char* clientID = generateClientID ();
  data.clientID.cstring = clientID;
  rc = client->connect(data);
  delete[] clientID;
  if (rc != 0)
  {
    Serial.print("error connection to MQTT server");
    Serial.println(rc);
    return false;
  }
  Serial.println("MQTT connected");
  return true;

}

//subscribe to a mqtt topic
void subscribe () {
//subscript to a topic
int rc = client->subscribe(aws_topic, MQTT::QOS0, messageArrived);
Serial.println(rc);
if (rc != 0) {
Serial.print("rc from MQTT subscribe is ");
Serial.println(rc);
return;
}
Serial.println("MQTT subscribed");
}

//send a message to a mqtt topic
void sendmessage () {
//send a message
MQTT::Message message;
char buf[100];
strcpy(buf, "{"state":{"reported":{"on": false}, "desired":{"on": false}}}");
message.qos = MQTT::QOS0;
message.retained = false;
message.dup = false;
message.payload = (void*)buf;
message.payloadlen = strlen(buf)+1;
int rc = client->publish(aws_topic, message);
}

void setup_wifi() {

delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

}

void setup() {
Serial.begin (115200);
setup_wifi();

  Serial.setDebugOutput(1); 
 //fill AWS parameters    
  awsWSclient.setAWSRegion(aws_region);
  awsWSclient.setAWSDomain(aws_endpoint);
  awsWSclient.setAWSKeyID(aws_key);
  awsWSclient.setAWSSecretKey(aws_secret);
  awsWSclient.setUseSSL(true);

  if (connect ()){
    subscribe ();
    sendmessage ();
  }

}

void loop() {
//keep the mqtt up and running
if (awsWSclient.connected ()) {
client->yield();
} else {
//handle reconnection
if (connect ()){
subscribe ();
}
}

}`
error

Compiles by the console prints gibberish

I see non ascii characters when I connect to the mcu (via screen) after running this. I have installed all dependencies and the program compiles perfectly.

I am new to this library. Any ideas?

Connected to wss but MQTT connect fail

I can connect to wss, but when mqtt is connecting, I receive msg "WS-Client: connection lost".
What is my problem?

connected with Tenda_351528, channel 7<\n>
dhcp client start...<\n>
ip:192.168.2.106,mask:255.255.255.0,gw:192.168.2.1<\n>
<\n>
connected<\r><\n>
10746 - conn: 1 - (34336)<\r><\n>
Sat Sep 03 16:40:02 2016<\n>
<\n>
[WS-Client] connect wss...<\n>
[WS-Client] connected to a2o4q1d0iu8ppm.iot.ap-southeast-1.amazonaws.com:443.<\n>
[WS-Client][sendHeader] sending header...<\n>
[WS-Client][sendHeader] sending header... Done (115986us).<\n>
[WS-Client][handleHeader] RX: HTTP/1.1 101 Switching Protocols<\n>
[WS-Client][handleHeader] RX: content-length: 0<\n>
[WS-Client][handleHeader] RX: upgrade: websocket<\n>
[WS-Client][handleHeader] RX: connection: Upgrade<\n>
[WS-Client][handleHeader] RX: sec-websocket-accept: 6rJ86EqKcY0vFEPwKlNgjfzTDXM=<\n>
[WS-Client][handleHeader] RX: sec-websocket-protocol: mqtt<\n>
[WS-Client][handleHeader] RX: access-control-allow-origin: *<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: Authorization<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: X-amz-security-token<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: Accept<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: X-amz-date<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: X-amz-user-agent<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: X-amz-content-sha256<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: Accept-Language<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: X-requested-with<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: Content-Language<\n>
[WS-Client][handleHeader] RX: access-control-allow-headers: Content-Type<\n>
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorMessage<\n>
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-RequestId<\n>
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorType<\n>
[WS-Client][handleHeader] RX: access-control-expose-headers: Date<\n>
[WS-Client][handleHeader] Header read fin.<\n>
[WS-Client][handleHeader] Client settings:<\n>
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIA4OLXG2IIQVMKHQ%2F20160903%2Fap-southeast-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20160903T094001Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=49a71885182198397765030d4f85eaf64389527a0f87579337f1d972faeb815a<\n>
[WS-Client][handleHeader] - cKey: BCXisznV8O6L30IzWI5Y3Q==<\n>
[WS-Client][handleHeader] Server header:<\n>
[WS-Client][handleHeader] - cCode: 101<\n>
[WS-Client][handleHeader] - cIsUpgrade: 1<\n>
[WS-Client][handleHeader] - cIsWebsocket: 1<\n>
[WS-Client][handleHeader] - cAccept: 6rJ86EqKcY0vFEPwKlNgjfzTDXM=<\n>
[WS-Client][handleHeader] - cProtocol: mqtt<\n>
[WS-Client][handleHeader] - cExtensions: <\n>
[WS-Client][handleHeader] - cVersion: 0<\n>
[WS-Client][handleHeader] Websocket connection init done.<\n>
[WS][0][headerDone] Header Handling Done (0us).<\n>
websocket layer connected<\r><\n>
MQTT connecting<\r><\n>
[MQTT client]creat connect msg done<\r><\n>
[WS][0][sendFrame] ------- send massage frame -------<\n>
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 38 headerToPayload: 0<\n>
[WS][0][sendFrame] pack to one TCP package...<\n>
[WS][0][sendFrame] sending Frame Done (101571us).<\n>
[MQTT client]send packet done<\r><\n>
[WS][0][handleWebsocketWaitFor] size: 2 cWsRXsize: 0<\n>
[readCb] n: 2 t: 14735<\n>
[WS][0][handleWebsocketWaitFor][readCb] size: 2 ok: 1<\n>
[WS-Client] connection lost.<\n>
[WS-Client] client disconnected.<\n>
[WS-Client] connect wss...<\n>
[WS-Client] connected to a2o4q1d0iu8ppm.iot.ap-southeast-1.amazonaws.com:443.<\n>
[WS-Client][sendHeader] sending header...<\n>
[WS-Client][sendHeader] sending header... Done (114428us).<\n>
pm open,type:2 0<\n>

Websocket connection times out

Hey! I'm trying your example, and running into an issue with the websocket connection, I added some extra serial.println()'s for overview:

Connecting to wifi
Connected
Socket connected
........................................................................................................................................................................................................MQTT connecting

Soft WDT reset
[snip]

As there are exactly 200 dots, I think the workaround is not working, I'll see if I can find out why :)

MQTT fails on long messages

I think I've found an issue. When I publish a message with a quote it in ", the message is never received on the iot end. When I publish a message without json, it does work:

The topic I subscribed to is $aws/things/xyz/shadow/update.

With regular text:

connecting to wifi
Connected
socket connected
MQTT connecting
MQTT connected
MQTT subscribed
Message 1 arrived: qos 1, retained 0, dup 0, packetid 2
Payload 
Message 2 arrived: qos 1, retained 0, dup 0, packetid 4
Payload foobar
Message 3 arrived: qos 1, retained 0, dup 0, packetid 5
Payload {}
Message 4 arrived: qos 1, retained 0, dup 0, packetid 6
Payload foo

With quotes:

connecting to wifi
Connected
socket connected
MQTT connecting
MQTT connected
MQTT subscribed

No response ;)

Fatal exception 29 when the internet suddenly goes down

Hello. First of all thank you for this useful library.
I'm testing for internet disconnection situation or situation that AP disappear.
It works fine for sudden absent of AP. (it recovers the connection automatically when AP is back)
But in case of internet disconnection it has a problem.

This is the log after internet disconnection.

[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 2 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[write] n: 8 t: 71466
:wr
:ww
:wr
:ww
:wr
:ww
:wr
:ww
:wr
Fatal exception 29(StoreProhibitedCause):
epc1=0x4000e1b2, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000

Exception (29):
epc1=0x4000e1b2 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

ctx: sys
sp: 3ffffda0 end: 3fffffb0 offset: 01a0

>>>stack>>>
3fffff40: 00000000 00000000 00000300 4010071d
3fffff50: 3fffdc00 00000000 3fff0dc0 40107638
3fffff60: 4010579e 01b41273 3fff1d20 402187b2
3fffff70: 4022a3fc 3fff1cf8 40218c72 00000002
3fffff80: 4022a422 3fffdab0 40219e6f 3fffdab0
3fffff90: 00000000 3fffdab0 3fff26ac 40210cb3
3fffffa0: 40000f49 40000f49 3fffdab0 40000f49
<<<stack<<<

ets Jan 8 2013,rst cause:1, boot mode:(3,0)
(log end)

[stack decode result]
Decoding 12 results
0x4010071d: calloc at C:\Users\handgear\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266\umm_malloc/umm_malloc.c line 1684
0x40107638: pvPortZalloc at C:\Users\handgear\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/heap.c line 33
0x4010579e: wdt_feed at ?? line ?
0x402187b2: pm_set_sleep_time at ?? line ?
0x4022a3fc: ets_timer_handler_isr at ?? line ?
0x40218c72: pm_get_sleep_type at ?? line ?
0x4022a422: ets_timer_handler_isr at ?? line ?
0x40219e6f: pm_post at ?? line ?
0x40210cb3: loop_task at C:\Users\handgear\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/core_esp8266_main.cpp line 56

i guess arduinoWebSockets could be the problem though
don't know why it dosn't exit from here ->
https://github.com/Links2004/arduinoWebSockets/blob/642750e232e3f0dbb23a10c0f12772df0e98b087/src/WebSockets.cpp#L618

Or shoud i ask to Links2004/arduinoWebSockets ?

Fatal exception 3(LoadStoreErrorCause) with NodeMCU

I got the following error trying to send a MQTT Message with NodeMCU to AWS IoT:
Fatal exception 3(LoadStoreErrorCause):
epc1=0x4020d7b1, epc2=0x00000000, epc3=0x00000000, excvaddr=0x40000000, depc=0x00
Panic /Users/arodes/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_main.cpp:134 loop_task

I want to send MQTT message with several MAC address like this:
//send a message
char buf[100];
strcpy(buf, "{"MAC":["08:d5:9d:63:3b:fe","44:f4:36:e0:30:a8","48:ba:4e:16:c0:09","78:4f:43:5e:de:ee","48:ba:4e:16:c0:08","1c:b0:44:38:19:4f","84:f3:eb:b4:50:23","08:d5:9d:63:3b:fc","24:5e:be:1f:0f:fb","b4:8b:19:c7:37:8a","68:d9:3c:86:8f:fa","08:d5:9d:63:3b:fd","70:c9:4e:00:01:0b"],"RSSI":[]}");
int rc = client.publish(aws_topic, buf);

Any idea??

Can't get disconnected info when internet disconnection

Hello,
Is there a way to get disconnect info when internet is off-line?
I'm trying to get connected status in loop by MQTT::Client->isConnected() and AWSWebSocketClient->connected().

In normal case it send & receive heartbeat(?) once a minute.

[WS][0][sendFrame]` ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 2 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[write] n: 8 t: 186387
[WS][0][sendFrame] sending Frame Done (9153us).

[WS][0][handleWebsocketWaitFor] size: 2 cWsRXsize: 0
[readCb] n: 2 t: 186421
[WS][0][handleWebsocketWaitFor][readCb] size: 2 ok: 1
[WS][0][handleWebsocket] ------- read massage frame -------
[WS][0][handleWebsocket] fin: 1 rsv1: 0 rsv2: 0 rsv3 0  opCode: 2
[WS][0][handleWebsocket] mask: 0 payloadLen: 2
[readCb] n: 2 t: 186436

When the internet is off-line, after about 1min, it send below and never send it again.
(situation pretend sudden disconnection after normal state)

[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 2 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[write] n: 8 t: 246673
[WS][0][sendFrame] sending Frame Done (9062us).

In this situation(off-line), MQTT::Client->isConnected() and AWSWebSocketClient->connected() are both true during loop.
It actually detects the disconnection after the internet recovered.

log after internet recovered:

[WS-Client] connection lost.
[WS-Client] client disconnected.
[WS-Client] connect wss...
[WS-Client] connected to qwertyqwerty.iot.ap-northeast-2.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] handshake GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=qwertyqwerty%2Fqwertyqwerty%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20180108T061032Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=qwertyqwerty HTTP/1.1
Host: qwertyqwerty.iot.ap-northeast-2.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: qwertyqwerty==
Origin: file://
User-Agent: arduino-WebSocket-Client

[write] n: 535 t: 456279
[WS-Client][sendHeader] sending header... Done (58594us).

in this point MQTT::Client->isConnected() == true, AWSWebSocketClient->connected() == false in loop

458176 - conn: 2 - (13376)
[WS][0][handleWebsocket] clientDisconnect code: 1000
[WS-Client] client disconnected.
[WS-Client] connect wss...
[WS-Client] connected to qwertyqwerty.ap-northeast-2.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] handshake GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=qwertyqwerty%2Fap-northeast-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20180108T061800Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=qwertyqwerty HTTP/1.1
Host: qwertyqwerty.iot.ap-northeast-2.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: qwertyqwerty==
Sec-WebSocket-Protocol: mqtt
Origin: file://
User-Agent: arduino-WebSocket-Client

and after this, it init webSocket and connect MQTT

Is there a way to get disconnect info when internet is off-line?


I tried with latest eclipse/paho.mqtt.embedded-c (release vertion 1.1.0)
wonder this was my case(eclipse/paho.mqtt.embedded-c@5509124)

interestingly with this MQTTClient.h, MQTT::Client->isConnected() is false after MQTT connection.
So it reconnect session after every 1min.

WDT Reset on Pubsubclient Connect

Hi All,

I am trying to connect to AWS IoT / use MQTT running one of the examples from this project on a NodeMCU. While the sketch runs, an error occurs and the serial monitor shows a WDT Soft Reset.

From using the ESPExceptionDecoder, there appears to be an issue with AWSWebSocketClient. I get the following trace from the Decoder:

0x40207c8d: AWSWebSocketClient::available() at /Users/ben/Documents/Arduino/libraries/AWSWebSocketClient/AWSWebSocketClient.cpp line 475
0x40207820: PubSubClient::connect(char const*, char const*, char const*, char const*, unsigned char, unsigned char, char const*) at /Users/ben/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp line 180
0x402078a4: PubSubClient::connect(char const*) at /Users/ben/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp line 106
0x402023ae: generateClientID() at /Users/ben/Documents/Arduino/odelot_pubsubclient_test070818/odelot_pubsubclient_test070818.ino line 57
0x40202480: connect() at /Users/ben/Documents/Arduino/odelot_pubsubclient_test070818/odelot_pubsubclient_test070818.ino line 97
0x402025fc: setup() at /Users/ben/Documents/Arduino/odelot_pubsubclient_test070818/odelot_pubsubclient_test070818.ino line 147
0x40209d20: loop_wrapper() at /Users/ben/Library/Arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/core_esp8266_main.cpp line 118

The error occurred on line this line from my sketch:
client.connect(clientID)

And the line that caused the error in AWSWebSocketClient.cpp is the call to "getsize" in the available() method:

//return with there is bytes to consume from the circular buffer (used by mqtt layer)
int AWSWebSocketClient::available(){
  //force websocket to handle it messages
  if (_connected == false)
	  return false;
  return bb.getSize ();
}

The code for my sketch follows:

#include <Arduino.h>
#include <Stream.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

//AWS
#include "sha256.h"
#include "Utils.h"

//WEBSockets
#include <Hash.h>
#include <WebSocketsClient.h>

//MQTT PUBSUBCLIENT LIB 
#include <PubSubClient.h>

//AWS MQTT Websocket
#include "Client.h"
#include "AWSWebSocketClient.h"
#include "CircularByteBuffer.h"

extern "C" {
  #include "user_interface.h"
}

//AWS IOT config, change these:
//Redacted for GitHub post
char wifi_ssid[]       = "";
char wifi_password[]   = "";
char aws_endpoint[]    = "";
char aws_key[]         = "";
char aws_secret[]      = "";
char aws_region[]      = "";
const char* aws_topic  = "";
int port = 443;



//MQTT config
const int maxMQTTpackageSize = 512;
const int maxMQTTMessageHandlers = 1;

ESP8266WiFiMulti WiFiMulti;
AWSWebSocketClient awsWSclient(100);

PubSubClient client(awsWSclient);

//# of connections
long connection = 0;

//generate random mqtt clientID
char* generateClientID () {
  char* cID = new char[23]();
  for (int i=0; i<22; i+=1)
    cID[i]=(char)random(1, 256);
  return cID;
}

//count messages arrived
int arrivedcount = 0;

//callback to handle mqtt messages
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

//connects to websocket layer and mqtt layer
bool connect () {



    if (client.connected()) {    
        client.disconnect ();
    }  
    //delay is not necessary... it just help us to get a "trustful" heap space value
    delay (1000);
    Serial.print (millis ());
    Serial.print (" - conn: ");
    Serial.print (++connection);
    Serial.print (" - (");
    Serial.print (ESP.getFreeHeap ());
    Serial.println (")");

    
    //creating random client id
    char* clientID = generateClientID ();
    client.setServer(aws_endpoint, port);
    if (client.connect(clientID)) {
      Serial.println("connected");     
      return true;
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      return false;
    }
    Serial.println("Afterclientconnectedcheck");
}

//subscribe to a mqtt topic
void subscribe () {
    client.setCallback(callback);
    client.subscribe(aws_topic);
   //subscript to a topic
    Serial.println("MQTT subscribed");
}

//send a message to a mqtt topic
void sendmessage () {
    //send a message   
    char buf[100];
    strcpy(buf, "{\"state\":{\"reported\":{\"on\": false}, \"desired\":{\"on\": false}}}");   
    int rc = client.publish(aws_topic, buf); 
}


void setup() {
    wifi_set_sleep_type(NONE_SLEEP_T);
    Serial.begin (115200);
//    delay (2000);
    Serial.setDebugOutput(1);

    //fill with ssid and wifi password
    WiFiMulti.addAP(wifi_ssid, wifi_password);
    Serial.println ("connecting to wifi");
    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
        Serial.print (".");
    }
    Serial.println ("\nconnected");
//Ben Winston 07.09.18 DELAY BEFORE AWS client invocation
  delay(100);
  Serial.print("Initializing AWS\n");

    //fill AWS parameters    
    awsWSclient.setAWSRegion(aws_region);
    awsWSclient.setAWSDomain(aws_endpoint);
    awsWSclient.setAWSKeyID(aws_key);
    awsWSclient.setAWSSecretKey(aws_secret);
    awsWSclient.setUseSSL(true);
  Serial.print("\nAWS Set up--------------");
    if (connect ()){
      subscribe ();
      sendmessage ();
    }

}

void loop() {
  //keep the mqtt up and running
  if (awsWSclient.connected ()) {    
    Serial.println("invoking client loop");
      client.loop ();
  } else {
    //handle reconnection
    if (connect ()){
      subscribe ();      
    }
  }
}


Any suggestions are appreciated.

Error in compiling examples

When compiling the examples, I get error about HASH_HEX_LEN2 has already defined in AWSClient2.h

I have latest aws-sdk-arduino and Arduino IDE 1.6.12.

Not able to compile

libraries/aws-mqtt-websockets-master/AWSWebSocketClient.cpp.o: In function AWSWebSocketClient::ntpFixNumber(int)': /Users/sunil/Documents/Arduino/libraries/aws-mqtt-websockets-master/AWSWebSocketClient.cpp:526: undefined reference to gmtime_r'
libraries/aws-mqtt-websockets-master/AWSWebSocketClient.cpp.o:(.text._ZN18AWSWebSocketClient17getCurrentTimeNTPEv+0x33): undefined reference to gmtime_r' libraries/aws-mqtt-websockets-master/AWSWebSocketClient.cpp.o: In function AWSWebSocketClient::getCurrentTimeNTP()':
/Users/sunil/Documents/Arduino/libraries/aws-mqtt-websockets-master/AWSWebSocketClient.cpp:526: undefined reference to `gmtime_r'
collect2: error: ld returned 1 exit status
exit status 1

Incompatibility with TimeLib 1.5

The new version uses time.h but it can't compile if the application uses Timelib. I made a version for use with Timelib. Now it compile and the date and time are exactly same as in your version but it cannot connect to AWS.

The previous version works like a charm for about 1 year. is it possible to download previous version?

error: conflicting return type specified for 'virtual void Sha256Class::write(uint8_t)'

screen shot 2017-02-28 at 6 27 39 pm

I'm using Generic ESP8266 module and trying to establish a secure SSL connection.
I get the following error after installing all the libraries:

In file included from /Users/huzaifah/Downloads/aws-mqtt-websockets-master/examples/aws-mqtt-websocket-example/aws-mqtt-websocket-example.ino:8:0: /Users/huzaifah/Documents/Arduino/libraries/Others/sha256.h:26:18: error: conflicting return type specified for 'virtual void Sha256Class::write(uint8_t)' virtual void write(uint8_t); ^ In file included from /Users/huzaifah/Library/Arduino15/packages/esp8266/hardware/esp8266/2.3.0/cores/esp8266/Stream.h:26:0, from /Users/huzaifah/Library/Arduino15/packages/esp8266/hardware/esp8266/2.3.0/cores/esp8266/HardwareSerial.h:31, from /Users/huzaifah/Library/Arduino15/packages/esp8266/hardware/esp8266/2.3.0/cores/esp8266/Arduino.h:245, from /Users/huzaifah/Downloads/aws-mqtt-websockets-master/examples/aws-mqtt-websocket-example/aws-mqtt-websocket-example.ino:1: /Users/huzaifah/Library/Arduino15/packages/esp8266/hardware/esp8266/2.3.0/cores/esp8266/Print.h:55:24: error: overriding 'virtual size_t Print::write(uint8_t)' virtual size_t write(uint8_t) = 0; ^ aws-mqtt-websocket-example:48: error: 'MQTT' does not name a type MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> *client = NULL; ^ aws-mqtt-websocket-example:65: error: variable or field 'messageArrived' declared void void messageArrived(MQTT::MessageData& md) ^ aws-mqtt-websocket-example:65: error: 'MQTT' has not been declared aws-mqtt-websocket-example:65: error: 'md' was not declared in this scope void messageArrived(MQTT::MessageData& md) ^ aws-mqtt-websocket-example:65: error: variable or field 'messageArrived' declared void void messageArrived(MQTT::MessageData& md) ^ aws-mqtt-websocket-example:65: error: 'MQTT' has not been declared aws-mqtt-websocket-example:65: error: 'md' was not declared in this scope void messageArrived(MQTT::MessageData& md) ^ /Users/huzaifah/Downloads/aws-mqtt-websockets-master/examples/aws-mqtt-websocket-example/aws-mqtt-websocket-example.ino: In function 'bool connect()': aws-mqtt-websocket-example:89: error: 'client' was not declared in this scope if (client == NULL) { ^ aws-mqtt-websocket-example:90: error: expected type-specifier before 'MQTT' client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack); ^ aws-mqtt-websocket-example:90: error: expected ';' before 'MQTT' aws-mqtt-websocket-example:96: error: type '<type error>' argument given to 'delete', expected pointer delete client; ^ aws-mqtt-websocket-example:97: error: expected type-specifier before 'MQTT' client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack); ^ aws-mqtt-websocket-example:97: error: expected ';' before 'MQTT' aws-mqtt-websocket-example:128: error: 'client' was not declared in this scope rc = client->connect(data); ^ /Users/huzaifah/Downloads/aws-mqtt-websockets-master/examples/aws-mqtt-websocket-example/aws-mqtt-websocket-example.ino: In function 'void subscribe()': aws-mqtt-websocket-example:143: error: 'client' was not declared in this scope int rc = client->subscribe(aws_topic, MQTT::QOS0, messageArrived); ^ aws-mqtt-websocket-example:143: error: 'MQTT' has not been declared int rc = client->subscribe(aws_topic, MQTT::QOS0, messageArrived); ^ aws-mqtt-websocket-example:143: error: 'messageArrived' was not declared in this scope int rc = client->subscribe(aws_topic, MQTT::QOS0, messageArrived); ^ /Users/huzaifah/Downloads/aws-mqtt-websockets-master/examples/aws-mqtt-websocket-example/aws-mqtt-websocket-example.ino: In function 'void sendmessage()': aws-mqtt-websocket-example:155: error: 'MQTT' has not been declared MQTT::Message message; ^ aws-mqtt-websocket-example:155: error: expected ';' before 'message' MQTT::Message message; ^ aws-mqtt-websocket-example:158: error: 'message' was not declared in this scope message.qos = MQTT::QOS0; ^ aws-mqtt-websocket-example:158: error: 'MQTT' has not been declared message.qos = MQTT::QOS0; ^ aws-mqtt-websocket-example:163: error: 'client' was not declared in this scope int rc = client->publish(aws_topic, message); ^ /Users/huzaifah/Downloads/aws-mqtt-websockets-master/examples/aws-mqtt-websocket-example/aws-mqtt-websocket-example.ino: In function 'void loop()': aws-mqtt-websocket-example:198: error: 'client' was not declared in this scope client->yield(); ^ exit status 1 'MQTT' does not name a type

Kindly help me to analyze the situation and find a solution for the same.

Error 400 on connection upgrade

Since I've not been able to find sources on how to proceed, here's my current issue in hopes of resolve.
Upon connecting to AWS IoT I receive a "400: Bad Request" from the IoT server. This happens as a response to the connection upgrade header sent out by the example. I have attempted to solve this by adjusting the AWS IoT policies, but had no success; editing the (public) key only resolved in a 403, which to me indicates that the verification is not the issue. It seems from the console output that it is related to the following lines in the response:

[WS-Client][handleHeader] RX: x-amzn-ErrorType: InvalidRequestException:
[WS-Client][handleHeader] RX: access-control-allow-origin: *

Any advice on how to process would be much appreciated!

The debug console output is as follows:

connecting to wifi

connected to wifi
Mon Jan 30 16:55:45 2017

25597 - conn: 1 - (27744)
[WS-Client] connect wss...
[WS-Client] connected to a229lcxkod94gz.iot.eu-central-1.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] handshake GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgVTqFkxdtijfCqb6cbLl
xzJucnT0cBv7q%2Fw7mQ3SySunjlKL2bAT5CzLMFhkxRcsJo29OwW9OXFsAeo1PHqz
n3QrY6Lg395PuWrUqu8VB6kglaxrx%2FKFnHUh0kGBe4K3XCOog06JMJu%2FJtE0SInZ
YlsWmqTIYcjf9CFbTZu2J6FYa99CKbhqeBwtnNUWW4s%2FZmAFu8o%2FZLZnh3+zTZGT
OLrJRypgLzRQrodBG+vzrKGkymnvUBItyV3UDOnEN6Nxz2U9vD7QajQCN02KAq60
zjjmEqzscZxGuHydBJy85Cd0tocP3mzreSWdgZ1FEaSXATabspnfFr1z6nRVZxLt
wQIDAQAB
-----END PUBLIC KEY-----%2F20170130%2Feu-central-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20170130T135547Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=39e2a13082057a7762a97a81905552679700b0bdbf13dbb1b58272543fce71c5 HTTP/1.1
Host: a229lcxkod94gz.iot.eu-central-1.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: XSN17QH9Jg0EH8cps+F9HQ==
Sec-WebSocket-Protocol: mqtt
Origin: file://
User-Agent: arduino-WebSocket-Client

[WS-Client][sendHeader] sending header... Done (145065us).
[WS-Client][handleHeader] RX: HTTP/1.1 400 Bad Request
[WS-Client][handleHeader] RX: content-type: application/json
[WS-Client][handleHeader] RX: content-length: 102
[WS-Client][handleHeader] RX: date: Mon, 30 Jan 2017 13:55:49 GMT
[WS-Client][handleHeader] RX: x-amzn-RequestId: f9b962c1-52f2-965d-9672-d3f7215840cc
[WS-Client][handleHeader] RX: connection: Keep-Alive
[WS-Client][handleHeader] RX: x-amzn-ErrorType: InvalidRequestException:
[WS-Client][handleHeader] RX: access-control-allow-origin: *
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader]  - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgVTqFkxdtijfCqb6cbLl
xzJucnT0cBv7q%2Fw7mQ3SySunjlKL2bAT5CzLMFhkxRcsJo29OwW9OXFsAeo1PHqz
n3QrY6Lg395PuWrUqu8VB6kglaxrx%2FKFnHUh0kGBe4K3XCOog06JMJu%2FJtE0SInZ
YlsWmqTIYcjf9CFbTZu2J6FYa99CKbhqeBwtnNUWW4s%2FZmAFu8o%2FZLZnh3+zTZGT
OLrJRypgLzRQrodBG+vzrKGkymnvUBItyV3UDOnEN6Nxz2U9vD7QajQCN02KAq60
zjjmEqzscZxGuHydBJy85Cd0tocP3mzreSWdgZ1FEaSXATabspnfFr1z6nRVZxLt
wQIDAQAB
-----END PUBLIC KEY-----%2F20170130%2Feu-central-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20170130T135547Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=39e2a13082057a7762a97a81905552679700b0bdbf13dbb1b58272543fce71c5
[WS-Client][handleHeader]  - cKey: XSN17QH9Jg0EH8cps+F9HQ==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader]  - cCode: 400
[WS-Client][handleHeader]  - cIsUpgrade: 0
[WS-Client][handleHeader]  - cIsWebsocket: 1
[WS-Client][handleHeader]  - cAccept: 
[WS-Client][handleHeader]  - cProtocol: mqtt
[WS-Client][handleHeader]  - cExtensions: 
[WS-Client][handleHeader]  - cVersion: 0
[WS-Client][handleHeader]  - cSessionId: 
[WS-Client][handleHeader] no Websocket connection close.
[WS-Client] client disconnected.
[AWSc] Disconnected!

These messages repeat in the console indefinitely.

My sketch is based upon the example that comes with this library. My only alterations are the debugging instructions seen here, some Serial.prints and an altered MQTT message.

I am currently using the following software versions and libraries:
Arduino IDE: 1.6.11
esp8266 by ESPCommunity: 2.3.0
And the most recent versions of the dependencies as listed in the readme.md of this project.

As for hardware, I'm using an Adafruit Feather Huzzah, which is based upon an ESP8266-12S.

Below is the sketch with the WiFi and Amazon keys redacted:

#include <Arduino.h>
#include <Stream.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

//AWS
#include "sha256.h"
#include "Utils.h"
#include "AWSClient2.h"

//WEBSockets
#include <Hash.h>
#include <WebSocketsClient.h>

//MQTT PAHO
#include <SPI.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>



//AWS MQTT Websocket
#include "Client.h"
#include "AWSWebSocketClient.h"
#include "CircularByteBuffer.h"

//AWS IOT config, change these:
char wifi_ssid[]       = "**";
char wifi_password[]   = "**";
char aws_endpoint[]    = "a229lcxkod94gz.iot.eu-central-1.amazonaws.com";
char aws_key[]         = 
"-----BEGIN PUBLIC KEY-----\n"
"-----END PUBLIC KEY-----";

char aws_secret[]      = 
"-----BEGIN RSA PRIVATE KEY-----\n"
"-----END RSA PRIVATE KEY-----";
char aws_region[]      = "eu-central-1";
const char* aws_topic  = "$aws/things/RESTtest/shadow/update";
int port = 443;

//MQTT config
const int maxMQTTpackageSize = 512;
const int maxMQTTMessageHandlers = 1;

ESP8266WiFiMulti WiFiMulti;

AWSWebSocketClient awsWSclient(1000);

IPStack ipstack(awsWSclient);
MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> *client = NULL;

//# of connections
long connection = 0;

//generate random mqtt clientID
char* generateClientID () {
  char* cID = new char[23]();
  for (int i=0; i<22; i+=1)
    cID[i]=(char)random(1, 256);
  return cID;
}

//count messages arrived
int arrivedcount = 0;

//callback to handle mqtt messages
void messageArrived(MQTT::MessageData& md)
{
  MQTT::Message &message = md.message;

  Serial.print("Message ");
  Serial.print(++arrivedcount);
  Serial.print(" arrived: qos ");
  Serial.print(message.qos);
  Serial.print(", retained ");
  Serial.print(message.retained);
  Serial.print(", dup ");
  Serial.print(message.dup);
  Serial.print(", packetid ");
  Serial.println(message.id);
  Serial.print("Payload ");
  char* msg = new char[message.payloadlen+1]();
  memcpy (msg,message.payload,message.payloadlen);
  Serial.println(msg);
  delete msg;
}

//connects to websocket layer and mqtt layer
bool connect () {

    if (client == NULL) {
      client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
    } else {

      if (client->isConnected ()) {    
        client->disconnect ();
      }  
      delete client;
      client = new MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers>(ipstack);
    }


    //delay is not necessary... it just help us to get a "trustful" heap space value
    delay (1000);
    Serial.print (millis ());
    Serial.print (" - conn: ");
    Serial.print (++connection);
    Serial.print (" - (");
    Serial.print (ESP.getFreeHeap ());
    Serial.println (")");




   int rc = ipstack.connect(aws_endpoint, port);
    if (rc != 1)
    {
      Serial.println("error connection to the websocket server");
      return false;
    } else {
      Serial.println("websocket layer connected");
    }


    Serial.println("MQTT connecting");
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.MQTTVersion = 3;
    char* clientID = generateClientID ();
    data.clientID.cstring = clientID;
    rc = client->connect(data);
    delete[] clientID;
    if (rc != 0)
    {
      Serial.print("error connection to MQTT server");
      Serial.print("rc = ");
      Serial.println(rc);
      return false;
    }
    Serial.println("MQTT connected");
    return true;
}

//subscribe to a mqtt topic
void subscribe () {
   //subscript to a topic
    int rc = client->subscribe(aws_topic, MQTT::QOS0, messageArrived);
    if (rc != 0) {
      Serial.print("rc from MQTT subscribe is ");
      Serial.println(rc);
      return;
    }
    Serial.println("MQTT subscribed");
}

//send a message to a mqtt topic
void sendmessage () {
    //send a message
    MQTT::Message message;
    char buf[100];
    strcpy(buf, "{\"desired\":{\"value\": \"HelloWorld\",\"esp_uptime\": 5},\"reported\": {\"value\": \"HelloWorld\",\"esp_uptime\": 5}}");
    
    message.qos = MQTT::QOS0;
    message.retained = false;
    message.dup = false;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf)+1;
    int rc = client->publish(aws_topic, message); 
}


void setup() {
    Serial.begin (115200);
    delay (2000);
    Serial.setDebugOutput(1);

    //fill with ssid and wifi password
    WiFiMulti.addAP(wifi_ssid, wifi_password);
    Serial.println ("connecting to wifi");
    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
        Serial.print (".");
    }
    Serial.println ("\nconnected to wifi");

    // config the time to prevent "please start sntp first!" message/error
    configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
    
    //fill AWS parameters    
    awsWSclient.setAWSRegion(aws_region);
    awsWSclient.setAWSDomain(aws_endpoint);
    awsWSclient.setAWSKeyID(aws_key);
    awsWSclient.setAWSSecretKey(aws_secret);
    awsWSclient.setUseSSL(true);

    if (connect ()){
      Serial.println(F("Sending first message over MQTT"));
      subscribe ();
      sendmessage ();
    }else{
      Serial.println(F("Could not connect to MQTT"));
    }

    // Show that the device is on
    pinMode(0, OUTPUT);
    digitalWrite(0, HIGH);
}

void loop() {
  //keep the mqtt up and running
  if (awsWSclient.connected ()) {    
      Serial.println(F("Connected to MQTT"));
      client->yield();
  } else {
    //handle reconnection
    if (connect ()){
      Serial.println(F("Connected, subscribing.."));
      subscribe ();      
    }else{
      Serial.println(F("Could not reconnect"));
    }
  }

}

"please start sntp first !" message while connecting to AWS

Hi,

I am trying to get my NodeMCU to publish to AWS IoT. While trying to connect, I get the message:

please start sntp first !

Multiple times before it finally prints:

error connection to the web socket server

I am successfully connected to my wifi network. Below is the (semi) full log.

um 0x2
m 0x2d
vc9f0c112
�connecting to wifi
state: 5 -> 0 (0)
rm 0
f r0, .....................scandone
.f r0, scan done
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 6
int

connected with A Network, channel 7
dhcp client start...
ip:192.168.1.30,mask:255.255.255.0,gw:192.168.1.1

connected
31604 - conn: 1 - (34784)
please start sntp first !
please start sntp first !
please start sntp first !
please start sntp first !
error connection to the web socket server
...

Thank you for any help. I appreciate it.

Receiving exception (3) in console on example

Hi. I love the look of this library. When I run the example I get Exception (3):
epc1=0x4010011d epc2=0x00000000 epc3=0x00000000 excvaddr=0x4002ea20 depc=0x00000000
followed by a stack dump and wdt reset

AWS shows a new connection coming through so it is connecting as I can see it. Before the crash, I see this in the console:

WiFi connected
IP address:
192.168.x.xxx
xxxxxxxxx.iot.eu-west-2.amazonaws.com
443
POST $aws/things/xxxxx/shadow/update HTTP/1.1
Content-Type: application/json
Connection: close
Content-Length: 41
Host: xxxxxxxxxxxxxxx.iot.eu-west-2.amazonaws.com
x-amz-content-sha256: 7c22939fcab76690cc822fb0628c4a0c03ab562ec24a0b8f9f0486914a543dd5
x-amz-date: 20180103T182433Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIAJNCMRQ6E4C7FEPAA/20180103/eu-west-2/iotdata/aws4_request,SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date,Signature=d755361de2df60e71265688cb40970a83d9ddfaf6b3a32d4fec8069554447cf4

{"state":{"reported": {"foobar": "bar"}}}

Esp8266 - Long time to establish connection to AWS and messages each second.

Hi guys, firstly, congratulation for this excelent work of integration with aws iot.
I'm not a expert about this, I'm woking with esp8266-01 and esp8266-12E.
My first issue is related to the initial connection with aws. Both my ESPs take about 5 minutes to connect with aws in port 443. After this, it's great the sending and receiving messasges. My doubt is related to this time of connection, why this happens? This time is closed or can I change it? After a hardware reset, some times esp8266 take some seconds to reconnect, but sometimes it takes about 4/5 minutes like before.

My second issue is when my esp is connected. Setting the parameter "debug Level" in my IDE arduino to "core", I notice my ESP sends/receive msgs to AWS each 15 seconds. I don't understanding well this. I'm using lib pubsubclient for mqtt (https://github.com/knolleary/pubsubclient.git). I saw in the code "PubSubClient.cpp" at function "boolean PubSubClient::loop()" that the author use this defines: MQTT_MAX_PACKET_SIZE and
MQTT_KEEPALIVE, but I'm not sure if just changing them "PubSubClient.h" in solve my problem. Can I change this parameter as I want?

ps: Sorry for my english, I need to improve them.

The message I receive while ESP try connecting to aws:

[WS-Client] connection to a33yv9okseqbmj.iot.us-east-1.amazonaws.com:443 Faild
[WS-Client] client disconnected.
[WS-Client] client disconnected.
[WS-Client] connect wss...
[WS-Client] connected to a33yv9okseqbmj.iot.us-east-1.amazonaws.com:443.
[WS-Client][sendHeader] sending header...
[WS-Client][sendHeader] handshake GET /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIZKJYVJSYIF7DOBQ%2F19700101%2Fus-east-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080059Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=95f0b4d95b125fc6c16c0443c8f263af67a8f3fefb59d1366f0cb00643efd8ab HTTP/1.1
Host: a33yv9okseqbmj.iot.us-east-1.amazonaws.com:443
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: yuPjAE9716yxqFeG0pUDdw==
Sec-WebSocket-Protocol: mqtt
Origin: file://
User-Agent: arduino-WebSocket-Client
[WS-Client][sendHeader] sending header... Done (701616us).
[WS-Client][handleHeader] RX: HTTP/1.1 403 Forbidden
[WS-Client][handleHeader] RX: content-type: application/json
[WS-Client][handleHeader] RX: content-length: 163
[WS-Client][handleHeader] RX: date: Thu, 24 May 2018 18:11:31 GMT
[WS-Client][handleHeader] RX: x-amzn-RequestId: c6309e93-8b63-6bf9-7c2d-45c5d97843ab
[WS-Client][handleHeader] RX: connection: keep-alive
[WS-Client][handleHeader] RX: x-amzn-ErrorType: ForbiddenException:
[WS-Client][handleHeader] RX: access-control-allow-origin: *
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorMessage
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-RequestId
[WS-Client][handleHeader] RX: access-control-expose-headers: x-amzn-ErrorType
[WS-Client][handleHeader] RX: access-control-expose-headers: Date
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client settings:
[WS-Client][handleHeader] - cURL: /mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIZKJYVJSYIF7DOBQ%2F19700101%2Fus-east-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=19700101T080059Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=95f0b4d95b125fc6c16c0443c8f263af67a8f3fefb59d1366f0cb00643efd8ab
[WS-Client][handleHeader] - cKey: yuPjAE9716yxqFeG0pUDdw==
[WS-Client][handleHeader] Server header:
[WS-Client][handleHeader] - cCode: 403
[WS-Client][handleHeader] - cIsUpgrade: 0
[WS-Client][handleHeader] - cIsWebsocket: 0
[WS-Client][handleHeader] - cAccept:
[WS-Client][handleHeader] - cProtocol: mqtt
[WS-Client][handleHeader] - cExtensions:
[WS-Client][handleHeader] - cVersion: 0
[WS-Client][handleHeader] - cSessionId:
[WS-Client][handleHeader] no Websocket connection close.

The message ESP receive each 15 secondes while it's connected :

[WS][0][sendFrame] ------- send message frame -------
[WS][0][sendFrame] fin: 1 opCode: 2 mask: 1 length: 2 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
[WS][0][sendFrame] sending Frame Done (48676us).
[WS][0][handleWebsocketWaitFor] size: 2 cWsRXsize: 0
[readCb] n: zu t: 2
[WS][0][handleWebsocketWaitFor][readCb] size: 2 ok: 1
[WS][0][handleWebsocket] ------- read massage frame -------
[WS][0][handleWebsocket] fin: 1 rsv1: 0 rsv2: 0 rsv3 0 opCode: 2
[WS][0][handleWebsocket] mask: 0 payloadLen: 2

A whole lot of problems

Hey. I have a problem on using this code in Arduino. I get these messages:
Arduino:1.8.4 (Windows 10), Kort:"Adafruit HUZZAH ESP8266, 80 MHz, 4M (1M SPIFFS), v2 Prebuilt (MSS=536), Disabled, None, 115200"

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp: In member function 'char* AWSWebSocketClient::generateAWSPath(uint16_t)':

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:277:2: error: 'SHA256' was not declared in this scope

SHA256* sha256 = new SHA256();

^

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:277:10: error: 'sha256' was not declared in this scope

SHA256* sha256 = new SHA256();

      ^

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:277:23: error: expected type-specifier before 'SHA256'

SHA256* sha256 = new SHA256();

                   ^

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:277:23: error: expected ';' before 'SHA256'

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:279:9: error: type '' argument given to 'delete', expected pointer

delete sha256;

     ^

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:287:15: error: expected type-specifier before 'SHA256'

sha256 = new SHA256();

           ^

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:287:15: error: expected ';' before 'SHA256'

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:289:9: error: type '' argument given to 'delete', expected pointer

delete sha256;

     ^

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:303:64: error: 'hmacSha256' was not declared in this scope

 char* k1 = hmacSha256(key, keyLen, awsDate, strlen(awsDate)); 

                                                            ^

C:\Program Files (x86)\Arduino\libraries\aws-mqtt-websockets\AWSWebSocketClient.cpp:305:31: error: 'SHA256_DEC_HASH_LEN' was not declared in this scope

 char* k2 = hmacSha256(k1, SHA256_DEC_HASH_LEN, awsRegion,

                           ^

exit status 1
Error compiling for board Adafruit HUZZAH ESP8266.

This happens when I try to verify or load it up to my Adafuit. Do you know why this is happening?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.