-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt_esp8266-fan1-controller-OTA.ino
228 lines (216 loc) · 6.73 KB
/
mqtt_esp8266-fan1-controller-OTA.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
ESP8266 MQTT OTA Updateable Sunsynk5.5 DC Side Top Fan1 Controller
Works with most 4pin fans that can measure rpms and have builtin pwm controller
*/
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ArduinoOTA.h>
#include <ESP8266HTTPUpdateServer.h>
#include <PubSubClient.h>
#include <Wire.h>
// Define message buffer and publish string
char message_buff[16];
char message_buffe[16];
String pubString;
String pubStringe;
int iTotalDelay;
const char* versionNumber = "Online-Ver1030";
// ------------------------------------------------------------
// Start Editing here
const char* ssid = "YOURWIFINAME";
const char* password = "YOURWIFIPASSWORD";
const char* mqtt_username = "YOURMQTTUSERNAME";
const char* mqtt_password = "YOURMQTTPASSWORD";
const char* mqtt_server = "YOURMQTTSERVERADDRESS";
const char* host = "esp8266-webupdateFan1";
const char* noderedtopic = "YOURFANSPEEDTOPICFROMMQTT"; // Subscribe to Fan Speed MQTT Topic sent to mqtt From Nodered
/*
* FAN SPEED SHOULD IDEALLY HAVE 5 VALUES for 1% - 100%
* THESE VALUES CAN BE DIFFERENT DEPENDING ON YOUR FAN PWM REQUIREMENTS
* USING NODERED TO GET THE SUNSYNK TEMPS AND CONVERT TO PWM VALUES AS SUGGESTED BELOW
* 1 FOR LOWEST/SLOWEST SPEED
* 20 25% SPEED
* 55 50% SPEED
* 105 75% SPEED
* 250 100% SPEED
*/
#define FAN_PIN 14 //pwm fan control signal
#define SIGNAL_PIN 13 // Read Fan RPMs
// Stop Editing here
// Making changes below this line could cause unexpected results
// -------------------------------------------------------------
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;
#define DELAY_TIME 10000 // time between measurements [ms]
#define MIN_FAN_SPEED_PERCENT 20 // minimum fan speed [%]
#define MIN_TEMP 20 // turn fan off below [deg C]
#define MAX_TEMP 250 // turn fan to full speed above [deg C]
int vTaskDelay;
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
volatile bool TopicArrived = false;
const int mqttpayloadSize = 100;
char mqttpayload [mqttpayloadSize] = {'\0'};
String mqtttopic;
void callback(char* topic, byte* payload, unsigned int length)
{
if ( !TopicArrived )
{
memset( mqttpayload, '\0', mqttpayloadSize ); // clear payload char buffer
mqtttopic = ""; //clear topic string buffer
mqtttopic = topic; //store new topic
memcpy( mqttpayload, payload, length );
TopicArrived = true;
}
}
// Wifi Client
WiFiClient wifiClient;
//
// This function yields back to the watchdog to avoid random ESP8266 resets
//
void myDelay(int ms)
{
int i;
for(i=1; i!=ms; i++)
{
delay(1);
if(i%100 == 0)
{
ESP.wdtFeed();
yield();
}
}
iTotalDelay+=ms;
}
//
// Starts WIFI connection
//
void startWIFI()
{
// If we are not connected
if (WiFi.status() != WL_CONNECTED)
{
int iTries;
iTries=0;
Serial.println(" ");
Serial.println("Starting WIFI connection");
WiFi.mode(WIFI_STA);
WiFi.disconnect();
WiFi.begin(ssid, password);
// If not WiFi connected, retry every 2 seconds for 15 minutes
while (WiFi.status() != WL_CONNECTED)
{
iTries++;
Serial.print(".");
delay(2000);
// If can't get to Wifi for 15 minutes, reboot ESP Default 450
if (iTries > 50)
{
Serial.println("TOO MANY WIFI ATTEMPTS, REBOOTING!");
ESP.reset();
}
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
// Let network have a chance to start up
myDelay(1500);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect to mqtt
if (client.connect("esp8266Fan1ClientOTA1", mqtt_username, mqtt_password)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("Fan1ControllerOTA", versionNumber);
// ... and resubscribe
client.subscribe(noderedtopic); //Get Fan Speed From NodeRed
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
mqtttopic.reserve(100);
// setup_wifi();
startWIFI();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
pinMode(FAN_PIN, OUTPUT);
pinMode(SIGNAL_PIN, INPUT);
// start OTA
MDNS.begin(host);
httpUpdater.setup(&httpServer);
httpServer.begin();
MDNS.addService("http", "tcp", 80);
Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
// end OTA
}
int getFanSpeedRpm() {
int highTime = pulseIn(SIGNAL_PIN, HIGH);
int lowTime = pulseIn(SIGNAL_PIN, LOW);
int period = highTime + lowTime;
if (period == 0) {
return 0;
}
float freq = 1000000.0 / (float)period;
return (freq * 60.0) / 2.0; // two cycles per revolution
}
void setFanSpeedPercent(int p) {
int value = p; // (p / 100.0) * 255;
analogWrite(FAN_PIN, value);
Serial.println(value);
String pubStringe = String(value);
pubStringe.toCharArray(message_buffe, pubStringe.length()+1);
client.publish("Fan1ControlerPWMPinValue", message_buffe);
}
void loop(void) {
httpServer.handleClient();
MDNS.update();
if (!client.connected()) {
reconnect();
}
client.loop();
if ( TopicArrived )
{
//parse topic
Serial.print("Fan 2 Speed: ");
Serial.println( mqttpayload );
TopicArrived = false;
float mqttpayloadresult = atof(mqttpayload); // float f = atof(carray);
float temp = mqttpayloadresult;
Serial.print("Temperature derived PWM value is ");
Serial.print(temp);
Serial.println(" - RPMs Signal");
int fanSpeedPercent, actualFanSpeedRpm;
fanSpeedPercent = temp;
Serial.print("Setting fan1 speed to ");
Serial.print(fanSpeedPercent);
Serial.println(" %");
setFanSpeedPercent(fanSpeedPercent);
actualFanSpeedRpm = getFanSpeedRpm();
Serial.print("Fan1 speed is ");
Serial.print(actualFanSpeedRpm);
String pubString = String(actualFanSpeedRpm);
pubString.toCharArray(message_buff, pubString.length()+1);
client.publish("FanControllerRPMs", message_buff );
Serial.println(" RPM");
Serial.println();
}
}