forked from AbdulrahmanAlhamed/8Channel-Relay-PiPicoW
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.py
More file actions
267 lines (218 loc) · 8.4 KB
/
Copy pathcode.py
File metadata and controls
267 lines (218 loc) · 8.4 KB
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
"""
Smart IoT Controller with auto-fallback
- Tries to use MQTT if available
- Falls back to HTTP-only mode if MQTT not available
"""
import os
import time
import wifi
import socketpool
import board
import microcontroller
import digitalio
import rtc
import struct
from adafruit_httpserver.server import HTTPServer
from adafruit_httpserver.request import HTTPRequest
from adafruit_httpserver.response import HTTPResponse
from adafruit_httpserver.methods import HTTPMethod
from adafruit_httpserver.mime_type import MIMEType
# Try to import MQTT support
try:
import adafruit_minimqtt.adafruit_minimqtt as MQTT
MQTT_AVAILABLE = True
print("✓ MQTT library found")
except ImportError:
MQTT_AVAILABLE = False
print("⚠ MQTT library not found - running in HTTP-only mode")
# Relay setup
Relay8 = digitalio.DigitalInOut(board.GP14)
Relay8.direction = digitalio.Direction.OUTPUT
relay_state = False # Track relay state
# --- NTP Time Sync ---
def sync_time_with_ntp(pool, host="time.navy.mi.th"):
port = 123
buf = 1024
address = (host, port)
print(f"🕒 Attempting to sync time with NTP server: {host}")
# Create NTP Packet
msg = bytearray(48)
msg[0] = 0b00100011 # LI, VN, Mode
try:
# Create a UDP socket
client = pool.socket(socketpool.AF_INET, socketpool.SOCK_DGRAM)
client.settimeout(5)
# Send request
client.sendto(msg, address)
# Wait for response
data, address = client.recvfrom(buf)
client.close()
# NTP Protocol: time is in bytes 40-43
t = struct.unpack("!I", data[40:44])[0]
# NTP epoch is 1900, Unix/PC epoch is 1970.
# Difference is 2208988800 seconds.
t -= 2208988800
# Add Thailand timezone offset (UTC+7 = 7 hours = 25200 seconds)
t += 25200
# Set the RTC
rtc.RTC().datetime = time.localtime(t)
current_time = time.localtime()
print("✅ Time synced successfully!")
print(f"📅 Current device time: {current_time.tm_mday}/{current_time.tm_mon}/{current_time.tm_year} {current_time.tm_hour:02}:{current_time.tm_min:02}:{current_time.tm_sec:02}")
return True
except OSError as e:
print(f"❌ NTP connection error: {e}")
return False
except Exception as e:
print(f"❌ An error occurred during NTP sync: {e}")
return False
# connect to network
print()
print("Connecting to WiFi")
# connect to your SSID
wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))
print("Connected to WiFi")
pool = socketpool.SocketPool(wifi.radio)
# Sync time after connecting to WiFi
sync_time_with_ntp(pool)
server = HTTPServer(pool, "/static")
def Relay_ON():
global relay_state
print("🔴 Relay: ON")
Relay8.value = True
relay_state = True
publish_status('on')
def Relay_OFF():
global relay_state
print("⚫ Relay: OFF")
Relay8.value = False
relay_state = False
publish_status('off')
def publish_status(state):
"""Publish relay status to MQTT (if available)"""
if mqtt_client and MQTT_ENABLED:
try:
payload = f'{{"state": "{state}", "timestamp": "{time.monotonic()}", "source": "pico"}}'
mqtt_client.publish(TOPICS['STATUS'], payload)
print(f"✅ MQTT status published: {state} → {TOPICS['STATUS']}")
except Exception as e:
print(f"⚠ MQTT publish error: {e}")
else:
print(f"⚠️ MQTT not available for status publish")
def mqtt_message_received(client, topic, message):
"""Callback when MQTT message is received"""
print(f"📨 MQTT Message received: {topic} = {message}")
if topic == TOPICS['CONTROL']:
try:
# ป้องกัน loop: ข้าม message ที่มาจาก backend เอง
if '"source"' in message and ('"backend"' in message or '"mqtt-control"' in message):
print("⏭️ Skipping message from backend (loop prevention)")
return
print(f"📦 Processing command...")
if '"on"' in message or "'on'" in message:
print("🎯 Command: ON")
Relay_ON()
elif '"off"' in message or "'off'" in message:
print("🎯 Command: OFF")
Relay_OFF()
else:
print(f"⚠️ Unknown command in message")
except Exception as e:
print(f"⚠ Error processing MQTT: {e}")
# MQTT Configuration
MQTT_BROKER = os.getenv('MQTT_BROKER', 'broker.hivemq.com')
MQTT_PORT = int(os.getenv('MQTT_PORT', '1883'))
MQTT_USERNAME = os.getenv('MQTT_USERNAME', '')
MQTT_PASSWORD = os.getenv('MQTT_PASSWORD', '')
MQTT_ENABLED = os.getenv('MQTT_ENABLED', 'false').lower() == 'true'
TOPICS = {
'CONTROL': 'home-iot/relay/control',
'STATUS': 'home-iot/relay/status',
'DEVICE': 'home-iot/device/status'
}
mqtt_client = None
# Setup MQTT if enabled and available
if MQTT_ENABLED and MQTT_AVAILABLE:
try:
mqtt_client = MQTT.MQTT(
broker=MQTT_BROKER,
port=MQTT_PORT,
socket_pool=pool,
ssl_context=None
)
if MQTT_USERNAME and MQTT_PASSWORD:
mqtt_client.username = MQTT_USERNAME
mqtt_client.password = MQTT_PASSWORD
mqtt_client.on_message = mqtt_message_received
print(f"Connecting to MQTT broker: {MQTT_BROKER}")
mqtt_client.connect()
mqtt_client.subscribe(TOPICS['CONTROL'])
mqtt_client.publish(TOPICS['DEVICE'], '{"online": true}', retain=True)
print(f"✓ MQTT enabled - subscribed to: {TOPICS['CONTROL']}")
except Exception as e:
print(f"⚠ MQTT setup failed: {e}")
print("→ Falling back to HTTP-only mode")
mqtt_client = None
MQTT_ENABLED = False
else:
print("→ Running in HTTP-only mode")
# API endpoint to get relay status (JSON)
@server.route("/api/relay", method=HTTPMethod.GET)
def get_relay_status(request: HTTPRequest):
with HTTPResponse(request, content_type=MIMEType.TYPE_JSON) as response:
response.send('{"state": "' + ('on' if relay_state else 'off') + '", "success": true}')
# API endpoint to control relay (JSON)
@server.route("/api/relay", method=HTTPMethod.POST)
def control_relay(request: HTTPRequest):
raw_text = request.raw_request.decode("utf8")
# Simple JSON parsing (CircuitPython doesn't have json module built-in)
if '"state"' in raw_text or "'state'" in raw_text:
if '"on"' in raw_text or "'on'" in raw_text:
Relay_ON()
state = "on"
elif '"off"' in raw_text or "'off'" in raw_text:
Relay_OFF()
state = "off"
else:
with HTTPResponse(request, content_type=MIMEType.TYPE_JSON) as response:
response.send('{"error": "Invalid state", "success": false}')
return
with HTTPResponse(request, content_type=MIMEType.TYPE_JSON) as response:
response.send('{"state": "' + state + '", "success": true}')
else:
with HTTPResponse(request, content_type=MIMEType.TYPE_JSON) as response:
response.send('{"error": "Missing state parameter", "success": false}')
print("Starting server..")
# startup the server
try:
server.start(str(wifi.radio.ipv4_address))
print("Listening on http://%s" % wifi.radio.ipv4_address)
# if the server fails to begin, restart the pico w
except OSError:
time.sleep(5)
print("Restarting..")
microcontroller.reset()
# Main loop
last_mqtt_check = time.monotonic()
MQTT_CHECK_INTERVAL = 1.0 # Check MQTT every 1 second
while True:
try:
# Poll HTTP server
server.poll()
# Poll MQTT client if enabled
if mqtt_client and MQTT_ENABLED:
current_time = time.monotonic()
if current_time - last_mqtt_check >= MQTT_CHECK_INTERVAL:
try:
mqtt_client.loop()
last_mqtt_check = current_time
except Exception as e:
print(f"⚠ MQTT loop error: {e}")
# Try to reconnect
try:
mqtt_client.reconnect()
except Exception:
pass
except Exception as e:
print(f"Main loop error: {e}")
continue