Skip to content

Commit bb0447a

Browse files
committed
Add WiFi101 AWS IoT example
1 parent 21c0242 commit bb0447a

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// This example uses an Arduino/Genuino Zero together with
2+
// a WiFi101 Shield or a MKR1000 to connect to shiftr.io.
3+
//
4+
// IMPORTANT: This example uses the new WiFi101 library.
5+
//
6+
// IMPORTANT: You need to install/update the SSL certificates first:
7+
// https://github.com/arduino-libraries/WiFi101-FirmwareUpdater#to-update-ssl-certificates
8+
//
9+
// You can check on your device after a successful
10+
// connection here: https://shiftr.io/try.
11+
//
12+
// by Gilberto Conti
13+
// https://github.com/256dpi/arduino-mqtt
14+
15+
#include <WiFi101.h>
16+
#include <MQTTClient.h>
17+
#include <ArduinoBearSSL.h>
18+
19+
const char ssid[] = "ssid";
20+
const char pass[] = "pass";
21+
22+
const char server[] = "xxxxxxxxxxxxxx.iot.xx-xxxx-x.amazonaws.com";
23+
24+
// Get the cert data by:
25+
// 1) Creating a CSR using the ArduinoBearSSL -> Tools -> ECC508CSR example for key slot 0
26+
// 2) Creating a new thing and uploading the CSR for it
27+
// 3) Downloading the public key for the thing in AWS IoT
28+
// 4) Convert the base64 encoded cert to binary
29+
const byte cert[] = {
30+
// ...
31+
};
32+
33+
WiFiClient wifiClient;
34+
BearSSLClient net(wifiClient, 0, cert, sizeof(cert));
35+
MQTTClient client;
36+
37+
unsigned long lastMillis = 0;
38+
39+
unsigned long getTime() {
40+
return WiFi.getTime();
41+
}
42+
43+
void setup() {
44+
Serial.begin(115200);
45+
46+
ArduinoBearSSL.onGetTime(getTime);
47+
48+
WiFi.begin(ssid, pass);
49+
50+
// Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
51+
// You need to set the IP address directly.
52+
//
53+
// MQTT brokers usually use port 8883 for secure connections.
54+
client.begin(server, 8883, net);
55+
client.onMessage(messageReceived);
56+
57+
connect();
58+
}
59+
60+
void connect() {
61+
Serial.print("checking wifi...");
62+
while (WiFi.status() != WL_CONNECTED) {
63+
Serial.print(".");
64+
delay(1000);
65+
}
66+
67+
Serial.print("\nconnecting...");
68+
while (!client.connect("arduino")) {
69+
Serial.print(".");
70+
delay(1000);
71+
}
72+
73+
Serial.println("\nconnected!");
74+
75+
client.subscribe("/hello");
76+
// client.unsubscribe("/hello");
77+
}
78+
79+
void loop() {
80+
client.loop();
81+
82+
if (!client.connected()) {
83+
connect();
84+
}
85+
86+
// publish a message roughly every second.
87+
if (millis() - lastMillis > 1000) {
88+
lastMillis = millis();
89+
client.publish("/hello", "world");
90+
}
91+
}
92+
93+
void messageReceived(String &topic, String &payload) {
94+
Serial.println("incoming: " + topic + " - " + payload);
95+
}

0 commit comments

Comments
 (0)