-
Notifications
You must be signed in to change notification settings - Fork 0
/
moisture_sensor.py
841 lines (701 loc) · 26.8 KB
/
moisture_sensor.py
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
import machine
from machine import Pin, ADC, PWM
import network
import usocket
import time
from umqtt.simple import MQTTClient
import ujson
import gc
import ubinascii
import sys
import dht
import ntptime
import ds18x20
import onewire
print("Free memory before connecting to WiFi:", gc.mem_free())
global WIFI_SSID, WIFI_PASSWORD, MQTT_BROKER, MQTT_USERNAME, MQTT_PASSWORD, SLEEP_DURATION
# WiFi and MQTT Configuration
CONFIG_FILE = 'config.json'
MQTT_PORT = 1883
MQTT_CLIENT_ID = "esp32c3_moisture_sensor"
MQTT_TOPIC = "tele/sensor/moisture_sensor/state"
MQTT_LIGHT_TOPIC = "tele/sensor/light_sensor/state"
MQTT_AIR_TEMP_TOPIC = "tele/sensor/air_temp_sensor/state"
MQTT_HUMIDITY_TOPIC = "tele/sensor/humidity_sensor/state"
MQTT_BATTERY_TOPIC = "tele/sensor/battery_sensor/state"
# Analog pin assignment
MOISTURE_SENSOR_PIN = 3
LIGHT_SENSOR_PIN = 2
#Power Pins
MOISTURE_PWR_PIN = 8
#LIGHT_PWR_PIN = 9
#LED pins
LED_PWR_PIN = 7
LED_BLUE_PIN = 10
LED_GREEN_PIN = 6
LED_PWR = machine.Pin(LED_PWR_PIN, machine.Pin.OUT)
LED_GREEN = PWM(Pin(LED_GREEN_PIN), freq=1000)
LED_BLUE = PWM(Pin(LED_BLUE_PIN), freq=1000)
SOIL_TEMP_PWR_PIN = 20
SOIL_TEMP_DATA_PIN = 5
min_update = 6
# Sleep duration in seconds (1 hour)
#SLEEP_DURATION = 3600
def connect_to_wifi(WIFI_SSID,WIFI_PASSWORD):
global Connecting
print(WIFI_SSID)
print(WIFI_PASSWORD)
wlan = network.WLAN(network.STA_IF)
wlan.active(False)
time.sleep(1)
wlan.active(True)
#LED_PWR = machine.Pin(LED_PWR_PIN, machine.Pin.OUT)
#LED_GREEN = PWM(Pin(LED_GREEN_PIN), freq=1000)
LED_GREEN.duty(1023)
LED_PWR.value(1)
#LED_BLUE = PWM(Pin(LED_BLUE_PIN), freq=1000)
button_pin = machine.Pin(9, machine.Pin.IN)
count = 0
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
button_press = button_pin.value()
count = count + 1
print("Connecting to WiFi...")
fade_in(LED_BLUE)
fade_out(LED_BLUE)
if button_press == 0 or (count > 30 and not wlan.isconnected()):
enter_configuration_mode()
wifi_solid()
print("Connected to WiFi:", wlan.ifconfig())
def fade_in(led):
for duty_cycle in range(0, 1023, 25): # Increase duty cycle in steps of 32
led.duty(duty_cycle)
time.sleep(0.025)
def fade_out(led):
for duty_cycle in range(1023, 0, -25): # Decrease duty cycle in steps of 32
led.duty(duty_cycle)
time.sleep(0.025)
def disconnect_from_wifi():
wlan = network.WLAN(network.STA_IF)
if wlan.isconnected():
print("Disconnecting from WiFi...")
wlan.disconnect()
time.sleep(1)
print("Disconnected from WiFi")
def connect_to_mqtt(MQTT_BROKER,MQTT_USERNAME,MQTT_PASSWORD):
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USERNAME, password=MQTT_PASSWORD)
time.sleep(2) # Add a short delay before connecting to MQTT
client.connect()
return client
def read_moisture():
#ADC.width(ADC.WIDTH_9BIT)
adc = ADC(Pin(MOISTURE_SENSOR_PIN))
adc.init(atten=ADC.ATTN_11DB)
moisture_value = adc.read()
return moisture_value
def read_light():
#ADC.width(ADC.WIDTH_9BIT)
adc = ADC(Pin(LIGHT_SENSOR_PIN))
adc.init(atten=ADC.ATTN_11DB)
light_value = adc.read()
return light_value
def publish_moisture(client, moisture_value):
payload = {
"moisture" : moisture_value
}
# Publish the message multiple times with short intervals
for _ in range(2):
client.publish(MQTT_TOPIC, ujson.dumps(payload).encode('utf-8'), retain=True)
time.sleep(2.5) # Adjust the delay as needed
return payload
def publish_light(client, light_value):
payload = {
"light" : light_value
}
# Publish the message multiple times with short intervals
for _ in range(2):
client.publish(MQTT_LIGHT_TOPIC, ujson.dumps(payload).encode('utf-8'), retain=True)
time.sleep(2.5) # Adjust the delay as needed
return payload
def publish_air_temp(client, air_temp):
payload = {
"temperature" : air_temp
}
# Publish the message multiple times with short intervals
for _ in range(2):
client.publish(MQTT_AIR_TEMP_TOPIC, ujson.dumps(payload).encode('utf-8'), retain=True)
time.sleep(2.5) # Adjust the delay as needed
return payload
def publish_humidity(client, humidity):
payload = {
"humidity" : humidity
}
# Publish the message multiple times with short intervals
for _ in range(2):
client.publish(MQTT_HUMIDITY_TOPIC, ujson.dumps(payload).encode('utf-8'), retain=True)
time.sleep(2.5) # Adjust the delay as needed
return payload
def publish_battery(client, battery):
payload = {
"battery" : battery
}
# Publish the message multiple times with short intervals
for _ in range(2):
client.publish(MQTT_BATTERY_TOPIC, ujson.dumps(payload).encode('utf-8'), retain=True)
time.sleep(2.5) # Adjust the delay as needed
return payload
def wait_for_ack(client, expected_ack):
# Wait for a response (acknowledgment) from the MQTT server
timeout = 10 # Adjust the timeout as needed
start_time = time.time()
while time.time() - start_time < timeout:
msg = client.check_msg()
if msg:
# Check if the received message is the expected acknowledgment
if msg[1] == expected_ack:
return True
return False
def deep_sleep(duration):
print("Going into deep sleep for {} seconds...".format(duration))
machine.deepsleep(duration * 1000)
def publish_discovery(client):
topic = "homeassistant/sensor/moisture_sensor/config"
payload = {
"name": "Moisture Sensor",
"state_topic": "tele/sensor/moisture_sensor/state",
"device_class": "moisture",
"unit_of_measurement": "%",
"unique_id" : "54839_moisture",
"value_template":"{{ value_json.moisture}}",
"device": {
"identifiers": [
"Garden-Sensor"
],
"manufacturer" : "Intellidwell",
"name" : "Garden Sensor",
"model" : "garden-sensor-v1"
},
"platform": "mqtt"
}
client.publish(topic, ujson.dumps(payload).encode('utf-8'), retain=True)
def publish_light_discovery(client):
topic = "homeassistant/sensor/light_sensor/config"
payload = {
"name": "Light Sensor",
"state_topic": "tele/sensor/light_sensor/state",
"icon":"mdi:sun-wireless",
"unit_of_measurement": "%",
"unique_id" : "54839_light",
"value_template":"{{ value_json.light}}",
"device": {
"identifiers": [
"Garden-Sensor"
],
"manufacturer" : "Intellidwell",
"name" : "Garden Sensor",
"model" : "garden-sensor-v1"
},
"platform": "mqtt"
}
client.publish(topic, ujson.dumps(payload).encode('utf-8'), retain=True)
def publish_air_temp_discovery(client):
topic = "homeassistant/sensor/air_temp_sensor/config"
payload = {
"name": "Air Temperature Sensor",
"state_topic": "tele/sensor/air_temp_sensor/state",
"device_class": "temperature",
"unit_of_measurement": "°F",
"unique_id" : "54839_air_temp",
"value_template":"{{ value_json.temperature}}",
"device": {
"identifiers": [
"Garden-Sensor"
],
"manufacturer" : "Intellidwell",
"name" : "Garden Sensor",
"model" : "garden-sensor-v1"
},
"platform": "mqtt"
}
client.publish(topic, ujson.dumps(payload).encode('utf-8'), retain=True)
def publish_humidity_discovery(client):
topic = "homeassistant/sensor/humidity_sensor/config"
payload = {
"name": "Humidity Sensor",
"state_topic": "tele/sensor/humidity_sensor/state",
"device_class": "humidity",
"unit_of_measurement": "%",
"unique_id" : "54839_humidity",
"value_template":"{{ value_json.humidity}}",
"device": {
"identifiers": [
"Garden-Sensor"
],
"manufacturer" : "Intellidwell",
"name" : "Garden Sensor",
"model" : "garden-sensor-v1"
},
"platform": "mqtt"
}
client.publish(topic, ujson.dumps(payload).encode('utf-8'), retain=True)
def publish_battery_discovery(client):
topic = "homeassistant/sensor/battery_sensor/config"
payload = {
"name": "Battery Sensor",
"state_topic": "tele/sensor/battery_sensor/state",
"device_class": "battery",
"unit_of_measurement": "%",
"unique_id" : "54839_battery",
"value_template":"{{ value_json.battery}}",
"device": {
"identifiers": [
"Garden-Sensor"
],
"manufacturer" : "Intellidwell",
"name" : "Garden Sensor",
"model" : "garden-sensor-v1"
},
"platform": "mqtt"
}
client.publish(topic, ujson.dumps(payload).encode('utf-8'), retain=True)
def get_bootcount_prev():
try:
with open('boot_count_update.txt', 'r') as f:
count = int(f.read())
except OSError:
count = 0
return count
def save_boot_count(bootcount):
count = bootcount
with open('boot_count_update.txt', 'w') as f:
f.write(str(count))
def get_boot_count():
try:
with open('boot_count.txt', 'r') as f:
count = int(f.read())
except OSError:
count = 0
return count
def increment_boot_count():
count = get_boot_count() + 1
with open('boot_count.txt', 'w') as f:
f.write(str(count))
def reset_boot_count():
with open('boot_count.txt', 'w') as f:
f.write('0')
def get_prev():
try:
with open('moisture_prev.txt', 'r') as f:
moisture_prev = float(f.read())
except OSError:
moisture_prev = 0
return moisture_prev
def write_prev(moisture_prev):
with open('moisture_prev.txt', 'w') as f:
f.write(str(moisture_prev))
def get_prev_light():
try:
with open('light_prev.txt', 'r') as f:
light_prev = float(f.read())
except OSError:
light_prev = 0
return light_prev
def write_prev_light(light_prev):
with open('light_prev.txt', 'w') as f:
f.write(str(light_prev))
def get_prev_air_temp():
try:
with open('air_temp_prev.txt', 'r') as f:
air_temp_prev = float(f.read())
except OSError:
air_temp_prev = 0
return air_temp_prev
def write_prev_air_temp(air_temp_prev):
with open('air_temp_prev.txt', 'w') as f:
f.write(str(air_temp_prev))
def get_prev_humidity():
try:
with open('humidity_prev.txt', 'r') as f:
humidity_prev = float(f.read())
except OSError:
humidity_prev = 0
return humidity_prev
def write_prev_humidity(humidity_prev):
with open('humidity_prev.txt', 'w') as f:
f.write(str(humidity_prev))
def get_prev_battery():
try:
with open('battery_prev.txt', 'r') as f:
battery_prev = float(f.read())
except OSError:
battery_prev = 0
return battery_prev
def write_prev_battery(battery_prev):
with open('battery_prev.txt', 'w') as f:
f.write(str(battery_prev))
# AP configuration
def enter_configuration_mode():
# Disconnect from WiFi
disconnect_from_wifi()
# Create an Access Point for configuration
ap_ssid = "Intellidwell_Garden_Sensor"
#ap_ssid = "Mosby2"
ap_password = "MyGarden12345"
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=ap_ssid, password=ap_password)
print("Configuration mode activated. Connect to AP:", ap_ssid, "with password:", ap_password)
print("Visit http://192.168.4.1 in your web browser to configure.")
# Serve the configuration page
serve_configuration_page()
def serve_configuration_page():
# HTML code for the configuration page
html_content = """<!DOCTYPE html>
<html>
<head>
<title>ESP32C3 Configuration</title>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<body>
<h2>ESP32C3 Configuration</h2>
<form action="/configure" method="post">
<label for="wifi_ssid">WiFi SSID:</label>
<input type="text" id="wifi_ssid" name="wifi_ssid" required><br>
<label for="wifi_password">WiFi Password:</label>
<input type="password" id="wifi_password" name="wifi_password" required><br>
<label for="mqtt_broker">MQTT Broker:</label>
<input type="text" id="mqtt_broker" name="mqtt_broker" required><br>
<label for="mqtt_username">MQTT Username:</label>
<input type="text" id="mqtt_username" name="mqtt_username" required><br>
<label for="mqtt_password">MQTT Password:</label>
<input type="password" id="mqtt_password" name="mqtt_password" required><br>
<label for="interval">Sleep Interval (seconds):</label>
<input type="number" id="interval" name="interval" required><br>
<label for="min_update">Minimum Update Interval (cycles):</label>
<input type="number" id="min_update" name="min_update" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
"""
# Set up a simple web server using usocket
addr = usocket.getaddrinfo('0.0.0.0', 80)[0][-1]
server_socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
server_socket.bind(addr)
server_socket.listen(5)
print("Listening on", addr)
#LED_PWR = machine.Pin(LED_PWR_PIN, machine.Pin.OUT)
#LED_BLUE = machine.Pin(LED_BLUE_PIN, machine.Pin.OUT)
LED_BLUE.duty(0)
LED_PWR.value(1)
while True:
client_socket, addr = server_socket.accept()
print("Client connected from", addr)
req = client_socket.recv(4096)
if req:
if req.find(b'POST /configure') != -1:
# Handle form submission
handle_configuration_submission(req, client_socket)
else:
# Serve the HTML page
response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}".format(
len(html_content), html_content)
client_socket.sendall(response)
client_socket.close()
def replace_all(text, dic):
for i,j in dic.items():
text = text.replace(i,j)
return text
def handle_configuration_submission(req, client_socket):
print("Received data (before decoding):", req)
form_data = req.decode('utf-8').split('\r\n')[-1]
form_data_dict = {}
for pair in form_data.split("&"):
key, value = pair.split("=")
form_data_dict[key] = value
# Use the entered values for configuration
WIFI_SSID = form_data_dict.get("wifi_ssid", "")
WIFI_PASSWORD = form_data_dict.get("wifi_password", "")
MQTT_BROKER = form_data_dict.get("mqtt_broker", "")
MQTT_USERNAME = form_data_dict.get("mqtt_username", "")
MQTT_PASSWORD = form_data_dict.get("mqtt_password", "")
SLEEP_DURATION = int(form_data_dict.get("interval", 0))
min_update = int(form_data_dict.get("min_update",0))
# Decode the MQTT password using the decode_url function
# MQTT_PASSWORD = decode_url(form_data_dict.get("mqtt_password", ""))
# Update your existing configuration variables with the entered
characters = {
'%21': '!', # !
'%27': "'", # '
'%28': '(', # (
'%29': ')', # )
'%3A': ':', # :
'%3B': ';', # ;
'%40': '@', # @
'%26': '&', # &
'%3D': '=', # =
'%2B': '+', # +
'%24': '$', # $
}
WIFI_PASSWORD = replace_all(WIFI_PASSWORD, characters)
MQTT_PASSWORD = replace_all(MQTT_PASSWORD, characters)
print("Configuration submitted successfully!")
print("WiFi SSID:", WIFI_SSID)
print("WiFi Password:", WIFI_PASSWORD)
print("MQTT Broker:", MQTT_BROKER)
print("MQTT Username:", MQTT_USERNAME)
print("MQTT Password:", MQTT_PASSWORD)
print("Sleep Interval:", SLEEP_DURATION)
print("Minimum Update Interval:", min_update)
save_config_to_file(WIFI_SSID,WIFI_PASSWORD,MQTT_BROKER,MQTT_USERNAME,MQTT_PASSWORD,SLEEP_DURATION,min_update)
# Respond with a simple acknowledgment page
acknowledgment = "Configuration submitted successfully!<br>Rebooting..."
response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}".format(
len(acknowledgment), acknowledgment)
client_socket.sendall(response)
# Delay to allow the acknowledgment to be sent before rebooting
time.sleep(2)
ap = network.WLAN(network.AP_IF)
ap.active(False)
led_off()
# Reboot the ESP32C3 to apply the new configuration
machine.reset()
def save_config_to_file(WIFI_SSID,WIFI_PASSWORD,MQTT_BROKER,MQTT_USERNAME,MQTT_PASSWORD,SLEEP_DURATION,min_update):
config_data = {
"WIFI_SSID": WIFI_SSID,
"WIFI_PASSWORD": WIFI_PASSWORD,
"MQTT_BROKER": MQTT_BROKER,
"MQTT_USERNAME": MQTT_USERNAME,
"MQTT_PASSWORD": MQTT_PASSWORD,
"SLEEP_DURATION": SLEEP_DURATION,
"min_update": min_update,
}
with open(CONFIG_FILE, 'w') as f:
ujson.dump(config_data, f)
def load_config_from_file():
try:
with open(CONFIG_FILE, 'r') as f:
config_data = ujson.load(f)
return config_data
except (OSError, ValueError):
return None
def wifi_solid():
LED_BLUE.duty(1023)
LED_GREEN.duty(0)
LED_PWR.value(1)
def led_off():
LED_BLUE.duty(1023)
LED_GREEN.duty(1023)
LED_PWR.value(0)
def get_soil_temp():
#adc = ADC(Pin(SOIL_TEMP_DATA_PIN))
#adc.init(atten=ADC.ATTN_11DB)
#soil_temp_value = adc.read()
ds_pin = machine.Pin(SOIL_TEMP_DATA_PIN)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
#ds_sensor.convert_temp()
time.sleep_ms(750)
roms = ds_sensor.scan()
for rom in roms:
temp_value = ds_sensor.read_temp(rom)
soil_temp_value = (temp_value * (9/5) + 32)
return soil_temp_value
def battery():
# Define the minimum and maximum voltage of the battery
min_voltage = 1.5 # Minimum voltage of the battery (0%)
max_voltage = 2.1 # Maximum voltage of the battery (100%)
# Define ADC reference voltage and maximum ADC value
#adc_ref_voltage = 3.3 # ADC reference voltage
adc_ref_voltage = 2.86
max_adc_value = 4095 # Maximum ADC value (12-bit ADC)
#uart = machine.UART(0, baudrate=115200)
adc = ADC(Pin(2)) # Define ADC pin (A0 in Arduino)
adc.atten(ADC.ATTN_11DB) # Set attenuation to 11dB
adc_value = adc.read()
battery_voltage = adc_value * adc_ref_voltage / max_adc_value
percentage = ((battery_voltage - min_voltage) / (max_voltage - min_voltage)) * 100
#Vbatt = 0
#for i in range(16):
# Vbatt += adc.read() # Read ADC value
#Vbatt = adc.read()
#Vbattf = 2 * Vbatt / 16 / 1000.0 # Convert to voltage (mV to V)
#uart.write("%.3f\r\n" % Vbattf) # Send voltage value over UART
time.sleep(1)
percentage = min(max(percentage, 0), 100)
return percentage
#return adc_value
def main():
button_pin = machine.Pin(9, machine.Pin.IN)
config_data = load_config_from_file()
LED_PWR.value(0)
LED_BLUE.duty(1023)
LED_GREEN.duty(1023)
# LED_PWR = machine.Pin(LED_PWR_PIN, machine.Pin.OUT)
# LED_GREEN = PWM(Pin(LED_GREEN_PIN), freq=1000)
WIFI_SSID = config_data.get("WIFI_SSID", "")
WIFI_PASSWORD = config_data.get("WIFI_PASSWORD", "")
MQTT_BROKER = config_data.get("MQTT_BROKER", "")
MQTT_USERNAME = config_data.get("MQTT_USERNAME", "")
MQTT_PASSWORD = config_data.get("MQTT_PASSWORD", "")
SLEEP_DURATION = config_data.get("SLEEP_DURATION", 0)
print(WIFI_SSID)
print(MQTT_BROKER)
#reset_boot_count()
# Retrieve and print the boot count
boot_count = get_boot_count()
print("Boot Count:", boot_count)
print('Powering on sensors...')
MOISTURE_PWR = machine.Pin(MOISTURE_PWR_PIN, machine.Pin.OUT)
SOIL_TEMP_PWR = machine.Pin(SOIL_TEMP_PWR_PIN, machine.Pin.OUT)
SOIL_TEMP_PWR.value(1)
MOISTURE_PWR.value(1)
# LIGHT_PWR = machine.Pin(LIGHT_PWR_PIN, machine.Pin.OUT)
#LIGHT_PWR.value(1)
time.sleep(10)
button_press = button_pin.value()
if button_press == 0:
enter_configuration_mode()
if boot_count < 1:
connect_to_wifi()
client = connect_to_mqtt()
publish_discovery(client)
initial_moisture = read_moisture()
normalized_value = 1 - (initial_moisture / 4095)
moisture_percentage_previous = round(normalized_value *100, 2)
write_prev(moisture_percentage_previous)
while True:
moisture_percentage_previous = get_prev()
print("Initial Moisture Value:", moisture_percentage_previous, " %")
current_moisture = read_moisture()
normalized_value = 1 - (current_moisture / 4095)
# Moisture Calibration
if normalized_value > 0.35:
normalized_value = 1
else:
normalized_value = normalized_value*2.86
moisture_percentage_current = round(normalized_value *100, 2)
print("Current Moisture Value:", moisture_percentage_current, " %")
# Light
# light_percentage_previous = get_prev_light()
# print("Initial Light Percentage:", light_percentage_previous, " %")
# current_light = read_light()
# normalized_light_value = current_light / 4095
# light_percentage_current = round(normalized_light_value *100, 2)
# print("Current Light Percentage:", light_percentage_current, " %")
#Air Temp
air_temp_previous = get_prev_air_temp()
print("Initial Air Temperature: ", air_temp_previous, " °F")
dht22sensor = dht.DHT22(Pin(4))
dht22sensor.measure()
air_temp_current = (dht22sensor.temperature() * (9/5) + 32)
print("Current Air Temperature:", air_temp_current, " %")
#Air Humidity
humidity_previous = get_prev_humidity()
print("Initial Humidity: ", humidity_previous, " %")
#dht22sensor.measure()
humidity_current = dht22sensor.humidity()
print("Current Humidity:", humidity_current, " %")
bootcount_prev = get_bootcount_prev()
tracker = boot_count - bootcount_prev
#Soil Temperature
#light_percentage_previous = get_prev_light()
#print("Initial Light Percentage:", light_percentage_previous, " %")
#current_soil_temp = get_soil_temp()
#normalized_light_value = current_light / 4095
#light_percentage_current = round(normalized_light_value *100, 2)
#print("Current Light Percentage:", light_percentage_current, " %")
#print("Current Soil Temperature:", current_soil_temp, " °F")
#Battery
battery_previous = get_prev_battery()
print("Initial Battery Percentage: ", battery_previous, " %")
battery_current = battery()
print("Current Battery Percentage is: ", battery_current," %")
if tracker >= min_update or abs(moisture_percentage_current - moisture_percentage_previous) >= (3):
print("Updating Server...")
connect_to_wifi(WIFI_SSID,WIFI_PASSWORD)
print(time.localtime())
#ntptime.settime()
#print(time.localtime())
client = connect_to_mqtt(MQTT_BROKER,MQTT_USERNAME,MQTT_PASSWORD)
#MQTT Moisture Messages
publish_discovery(client)
count = 0
print('Publishing moisture sensor discovery message to MQTT server...')
while True:
count = count + 1
fade_in(LED_GREEN)
fade_out(LED_GREEN)
if count > 2:
break
print('Publishing moisture sensor value to MQTT server...')
payload = publish_moisture(client, moisture_percentage_current)
#MQTT Light Messages
# publish_light_discovery(client)
# count = 0
# while True:
# print('Publishing light sensor discovery message to MQTT server...')
# count = count + 1
# LED_PWR.value(0)
# time.sleep(0.5)
# LED_PWR.value(1)
# time.sleep(0.5)
# if count > 3:
# break
# print('Publishing light sensor value to MQTT server...')
# payload = publish_light(client, light_percentage_current)
#MQTT Air_Temp Messages
publish_air_temp_discovery(client)
count = 0
print('Publishing Air Temperature discovery message to MQTT server...')
while True:
count = count + 1
fade_in(LED_GREEN)
fade_out(LED_GREEN)
if count > 2:
break
print('Publishing air temperature sensor value to MQTT server...')
payload = publish_air_temp(client, air_temp_current)
#MQTT Air_Hum Messages
publish_humidity_discovery(client)
count = 0
print('Publishing humidity sensor discovery message to MQTT server...')
while True:
count = count + 1
fade_in(LED_GREEN)
fade_out(LED_GREEN)
if count > 2:
break
print('Publishing humidity sensor value to MQTT server...')
payload = publish_humidity(client, humidity_current)
#MQTT Battery Messages
publish_battery_discovery(client)
count = 0
print('Publishing battery sensor discovery message to MQTT server...')
while True:
count = count + 1
fade_in(LED_GREEN)
fade_out(LED_GREEN)
if count > 2:
break
print('Publishing battery percentage to MQTT server...')
payload = publish_battery(client, battery_current)
#Write sensor values to memory
write_prev(moisture_percentage_current)
#write_prev_light(light_percentage_current)
write_prev_air_temp(air_temp_current)
write_prev_humidity(humidity_current)
write_prev_battery(battery_current)
save_boot_count(boot_count)
client.disconnect()
disconnect_from_wifi()
SOIL_TEMP_PWR.value(0)
MOISTURE_PWR.value(0)
#LIGHT_PWR.value(0)
led_off()
print('Powering off sensors...')
#client.disconnect()
#disconnect_from_wifi()
increment_boot_count()
deep_sleep(SLEEP_DURATION)
if __name__ == "__main__":
main()