1 | #include <ESP8266WiFi.h>
|
2 | #include <PubSubClient.h>
|
3 |
|
4 |
|
5 | #define wifi_ssid "My_SSID"
|
6 | #define wifi_password "My_PW"
|
7 |
|
8 | #define mqtt_server "m20.cloudmqtt.com"
|
9 | #define mqtt_user "user"
|
10 | #define mqtt_password "password" //
|
11 |
|
12 |
|
13 |
|
14 | #define humidity_topic "tr_test"
|
15 | #define cloudmqttport 17208
|
16 | WiFiClient espClient;
|
17 |
|
18 | PubSubClient client(mqtt_server, cloudmqttport,callback,espClient);
|
19 |
|
20 |
|
21 | void setup() {
|
22 | Serial.begin(115200);
|
23 | setup_wifi();
|
24 | // client.setServer(mqtt_server, 17208); // dieser Port ist wichtig
|
25 | //client.setCallback(callback);
|
26 | //client.subscribe(humidity_topic);
|
27 |
|
28 | }
|
29 |
|
30 | void setup_wifi() {
|
31 | delay(10);
|
32 | // We start by connecting to a WiFi network
|
33 | Serial.println();
|
34 | Serial.print("Connecting to ");
|
35 | Serial.println(wifi_ssid);
|
36 |
|
37 | WiFi.begin(wifi_ssid, wifi_password);
|
38 |
|
39 | while (WiFi.status() != WL_CONNECTED) {
|
40 | delay(500);
|
41 | Serial.print(".");
|
42 | }
|
43 |
|
44 | Serial.println("");
|
45 | Serial.println("WiFi connected");
|
46 | Serial.println("IP address: ");
|
47 | Serial.println(WiFi.localIP());
|
48 | }
|
49 |
|
50 | void reconnect() {
|
51 | // Loop until we're reconnected
|
52 | while (!client.connected()) {
|
53 | Serial.print("Attempting MQTT connection...");
|
54 | // Attempt to connect
|
55 | if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
|
56 | Serial.println("connected");
|
57 | } else {
|
58 | Serial.print("failed, rc=");
|
59 | Serial.print(client.state());
|
60 | Serial.println(" try again in 5 seconds");
|
61 | // Wait 5 seconds before retrying
|
62 | delay(5000);
|
63 | }
|
64 | }
|
65 | }
|
66 |
|
67 |
|
68 | long lastMsg = 0;
|
69 | float temp = 0.0;
|
70 | float hum = 0.0;
|
71 | float diff = 1.0;
|
72 |
|
73 | void loop() {
|
74 | if (!client.connected()) {
|
75 | reconnect();
|
76 | }
|
77 |
|
78 | client.loop();
|
79 |
|
80 | long now = millis();
|
81 | if (now - lastMsg > 5000) {
|
82 | lastMsg = now;
|
83 |
|
84 | float newHum = random(0,100);
|
85 |
|
86 | if (newHum != hum) {
|
87 | hum = newHum;
|
88 | //Serial.print("New humidity:");
|
89 | //Serial.println(String(hum).c_str());
|
90 | client.publish(humidity_topic, String(hum).c_str(), true);
|
91 | }
|
92 | }
|
93 | }
|
94 |
|
95 | void callback(char* topic, byte* payload, unsigned int length) {
|
96 | Serial.print("Message arrived [");
|
97 | Serial.print(topic);
|
98 | Serial.print("] ");
|
99 | for (int i = 0; i < length; i++) {
|
100 | Serial.print((char)payload[i]);
|
101 | }
|
102 | Serial.println();
|
103 | }
|