# Reference: https://wokwi.com/projects/394206176807480321
# https://wokwi.com/projects/393972531340227585
# ntfy Publishing https://docs.ntfy.sh/publish/
from machine import Pin,unique_id
import network
import time
import usocket as socket
import ussl as ssl
import ubinascii
import urandom as random
import os
import dht
# AP
WIFI_SSID1 = '1234' # "Your network name";
WIFI_PASS1 = '5678' # "Your network password";
WIFI_SSID2 = "2345" # Your WiFi SSID
WIFI_PASS2 = "6789" # Your WiFi Password
WIFI_SSID3 = "3456" # Your WiFi SSID
WIFI_PASS3 = "7890" # Your WiFi Password
# WIFI_SSID = "Wokwi-GUEST"
# WIFI_PASS = ""
# ntfy.sh url
HOST = "ntfy.sh" # 伺服器網址,不可動
API_URL = "/ <Enter your topics>" # 連線對象URL
PORT = 443 # https
button_down = False
def randint(min, max):
span = max - min + 1
div = 0x3FFFFFFF // span
offset = random.getrandbits(30) // div
val = min + offset
return val
def connect_wifi():
print("Scanning for WiFi networks, please wait...")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
num = 0
for (ssid, bssid, channel, RSSI, authmode, hidden) in wifi.scan():
if WIFI_SSID1 in ssid:
WIFI_SSID = WIFI_SSID1 # Your WiFi SSID
WIFI_PASS = WIFI_PASS1 # Your WiFi Password
num=1
break
elif WIFI_SSID2 in ssid:
WIFI_SSID = WIFI_SSID2 # Your WiFi SSID
WIFI_PASS = WIFI_PASS2 # Your WiFi Password
num=2
break
elif WIFI_SSID3 in ssid:
WIFI_SSID = WIFI_SSID3 # Your WiFi SSID
WIFI_PASS = WIFI_PASS3 # Your WiFi Password
num=3
break
elif "Wokwi-GUEST" in ssid:
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
num=4
break
if (num == 0):
print("Couldn't get a wifi connection")
while True:
pass
# authmodes = ['Open', 'WEP', 'WPA-PSK' 'WPA2-PSK4', 'WPA/WPA2-PSK']
print("* {:s}".format(ssid))
# print(" - Auth: {} {}".format(authmodes[authmode], '(hidden)' if hidden else ''))
print(" - Channel: {}".format(channel))
print(" - RSSI: {}".format(RSSI))
print(" - BSSID: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*bssid))
if not wifi.isconnected():
print('connecting to network...')
wifi.connect(WIFI_SSID, WIFI_PASS)
while not wifi.isconnected():
time.sleep(1)
print('network config:', wifi.ifconfig())
return
# Function to handle button press interrupt (optional)
def button_press(pin):
global button_down
led2_pin.value(not led2_pin.value())
button_down = True
def sendMessage(param_data):
# 定義發送至伺服器的訊息內容
message_str = "POST " + API_URL + " HTTP/1.1\r\n" \
+ "Host: " + HOST + "\r\n" \
+ "Title: Unauthorized access detected\r\n" \
+ "Tags: warning\r\n" \
+ "Content-Length: " + str(len(param_data)) + "\r\n" \
+ "Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
+ param_data + "\r\n"
addr = socket.getaddrinfo(HOST, PORT)[0][-1] # 取得連線到伺服器的相關訊息
print(addr) # 顯示取得的address訊息內容
try:
Socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create STREAM TCP socket
print("connecting to server")
Socket1.connect(addr) # 與伺服器進行連線
print("server is connected")
time.sleep_ms(1000)
ssl_sock = ssl.wrap_socket(Socket1) # SSL wrap
ssl_sock.write(message_str) # send data
print("send done")
time.sleep_ms(1000)
Socket1.close() # 關閉與伺服器的連線,避免佔用端口。
except:
print("except")
time.sleep_ms(1000)
# Start Function
if __name__ == '__main__':
print(os.uname())
print("Hello, " + os.uname().sysname + "!")
# ESP32 unique ID
CLIENT_ID = ubinascii.hexlify(unique_id())
print("Unique ID: ", end="")
print(CLIENT_ID)
# Define GPIO pins for LED and push button
led1_pin = Pin(4, Pin.OUT)
led2_pin = Pin(2, Pin.OUT) # Initialize LED on GPIO2
led1_pin.value(False)
led2_pin.value(False)
button_pin = Pin(35, Pin.IN, Pin.PULL_UP) # Internal pull-up resistor
# Attach interrupt to the push button pin
button_pin.irq(trigger=Pin.IRQ_FALLING, handler=button_press)
dht_sensor = dht.DHT22(Pin(15))
connect_wifi() # Connecting to WiFi Router
payload = """This message is sent by "{:s}".""".format(os.uname().sysname)
print(payload) # 顯示此訊息內容進行debug
sendMessage(payload) # 執行此函數
while True:
led1_pin.value(not led1_pin.value())
if button_down == True:
led2_pin.value(True)
dht_sensor.measure()
temp = dht_sensor.temperature()
humi = dht_sensor.humidity()
# temp=randint(1,50)
# humi=randint(1,100)
Temp="Temp: %2d\u00b0C" % (temp) # Degree Celsius => \u2103
Humi="Humi: %2d%%" % (humi)
payload = "{:s}, {:s}..".format(Temp,Humi)
print(payload) # 顯示此訊息內容進行debug
connect_wifi() # Connecting to WiFi Router
sendMessage(payload) # 執行此函數
led2_pin.value(False)
button_down = False
# Do other tasks while waiting for button press
time.sleep_ms(100)