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
RECONNECT_INTERVAL = 20000 # millisecond
# 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 = ""
HOST = "script.google.com" # 伺服器網址,不可動
# Google Apps Script Web App
GSCRIPT_ID = "AKfycbxMjwPXNzdXrWv_sHVLu1oURQuoPP9DQRWAPdYRxRiV7aZFmOG5wuQT_VODvmT7nfUf"
# Create a URI for the request
API_URL = "/macros/s/" + GSCRIPT_ID + "/exec" # 連線對象URL
PORT = 443 # https
CITY = "\"taipei,tw\""
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
def sendMessage(param_data):
# 定義發送至伺服器的訊息內容
message_str = "POST " + API_URL + " HTTP/1.1\r\n" \
+ "Host: " + HOST + "\r\n" \
+ "Content-Length: " + str(len(param_data)) + "\r\n" \
+ "Content-Type: application/json\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)
# Function to handle button press interrupt (optional)
def button_press(pin):
global button_down
led2_pin.value(not led2_pin.value())
button_down = True
# 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))
lastTime = time.ticks_ms()
while True:
led1_pin.value(not led1_pin.value())
currTime = time.ticks_ms()
if (currTime - lastTime > RECONNECT_INTERVAL):
lastTime = currTime
led2_pin.value(True)
# dht_sensor.measure()
# temp = dht_sensor.temperature()
# humi = dht_sensor.humidity()
temp=randint(1,50)
humi=randint(1,100)
payload = "{\"city\": " + CITY + ", \"temperature\": " + str(temp) + ", \"humidity\": " + str(humi) + "}"
print(payload) # 顯示此訊息內容進行debug
connect_wifi() # Connecting to WiFi Router
sendMessage(payload) # 執行此函數
led2_pin.value(False)