-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
148 lines (129 loc) · 4.39 KB
/
main.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
import network
import usocket as socket
import machine
import time
import onewire
import ds18x20
import secrets
# Set up network
wifi_ssid = secrets.SSID
wifi_password = secrets.PASSWORD
# Connect to WiFi
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(wifi_ssid, wifi_password)
# Disable WiFi power saver mode
wifi.config(pm=0xa11140)
# Wait until connected to WiFi
while not wifi.isconnected():
pass
# Print IP address
ip_address = wifi.ifconfig()[0]
print("Pico W IP address:", ip_address)
# Set up GPIO for heater
heater_pin = machine.Pin(22, machine.Pin.OUT)
heater_pin.value(0) # Initially turn off heater
# Set up DS18x20 temperature sensor
ds_pin = machine.Pin(26) # DS18x20 data pin
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
roms = ds_sensor.scan()
# Default setpoint value
setpoint = 30.0
# HTML form
html = """<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Reservoir Temperature Control</title></head>
<body>
<h2>Reservoir Temperature Control</h2>
<form id="setpointForm" action="/" method="get">
<label for="setpoint">Setpoint:</label><br>
<input type="number" id="setpoint" name="setpoint" min="0" max="100" step="0.1" value="{0:.1f}"><br><br>
<input type="submit" value="Submit">
</form>
<div id="temperature">Temperature: {0:.1f}</div>
<div id="setpointDisplay">Setpoint: {0:.1f}</div>
<script>
function updateTemperature() {{
fetch("/temperature")
.then(response => response.text())
.then(data => {{
document.getElementById("temperature").innerHTML = "Temperature: " + data + "°C";
}})
.catch(error => console.error('Error fetching temperature:', error));
}}
document.getElementById("setpointForm").addEventListener("submit", function(event) {{
event.preventDefault();
var newSetpoint = document.getElementById("setpoint").value;
fetch("/?setpoint=" + newSetpoint)
.then(response => {{
if (response.ok) {{
console.log("Setpoint updated successfully.");
// Update temperature display
updateTemperature();
// Update setpoint display
document.getElementById("setpointDisplay").innerHTML = "Setpoint: " + newSetpoint + "°C";
}} else {{
throw new Error("Failed to update setpoint.");
}}
}})
.catch(error => console.error('Error updating setpoint:', error));
}});
// Initial update of temperature and setpoint
updateTemperature();
document.getElementById("setpointDisplay").innerHTML = "Setpoint: {0:.1f}" + "°C";
setInterval(updateTemperature, 5000); // Update temperature every 5 seconds
</script>
</body>
</html>
""".format(setpoint)
# Function to parse HTTP request
def parse_request(request):
request_str = request.decode('utf-8')
if "GET /?setpoint=" in request_str:
start = request_str.find("setpoint=") + len("setpoint=")
end = request_str.find(" HTTP")
setpoint_str = request_str[start:end]
return setpoint_str.strip()
return None
# Function to handle HTTP requests
def handle_request(client_socket):
global setpoint
request = client_socket.recv(1024)
setpoint_str = parse_request(request)
if setpoint_str:
print("Setpoint:", setpoint_str)
try:
setpoint = float(setpoint_str)
except ValueError:
pass
if request.startswith(b"GET /temperature"):
# Read temperature from DS18x20 sensor
ds_sensor.convert_temp()
time.sleep(1)
temperature = ds_sensor.read_temp(roms[0])
if temperature is None:
temperature = "Error"
else:
temperature = "{:.1f}".format(temperature) # Format temperature to one decimal place
ftemperature = float(temperature)
if ftemperature < setpoint:
heater_pin.value(1)
else:
heater_pin.value(0)
client_socket.send(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n" + bytes(temperature, 'utf-8'))
client_socket.close()
return
# Send HTML response
client_socket.send(b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n")
client_socket.send(html)
client_socket.close()
# Set up socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', 80))
s.listen(5)
print("Server running on port 80...")
# Main loop to handle incoming connections
while True:
client, addr = s.accept()
print("Client connected from:", addr)
handle_request(client)