# Reference: https://qiita.com/kotaproj/items/3b974425dfa2579afdbc
# https://docs.blynk.io/en/blynk.cloud/device-https-api/update-datastream-value
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
# 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 = ""
# Fill-in information from Blynk Device Info here
BLYNK_TEMPLATE_ID = "TMPL6Bxg96QSE"
BLYNK_TEMPLATE_NAME = "ESP32LED"
BLYNK_AUTH_TOKEN = "XoNXUD1WSva6Jmuj9HPyeBr5Sx8ogbWj"
HOST = "blynk.cloud" # 伺服器網址,不可動
PORT = 443 # https
button_down = False
button_up = False
GPIO_PIN = 2 # 使用D4腳位
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(url):
# 定義發送至伺服器的訊息內容
message_str = "GET " + url + " HTTP/1.1\r\n" \
+ "Host: " + HOST + "\r\n" \
+ "Content-Type: application/x-www-form-urlencoded\r\n\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)
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)
connect_wifi()
while True:
led1_pin.value(not led1_pin.value())
if button_down == True:
temp=randint(1,50)
humi=randint(1,100)
# /external/api/update?token={token}&pin=V1&value=lon&value=lat
API_URL = "/external/api/update?token=" + BLYNK_AUTH_TOKEN + "&V6=" + str(temp)
print(API_URL) # 顯示此訊息內容進行debug
sendMessage(API_URL) # 執行此函數
button_down = False
# Do other tasks while waiting for button press
time.sleep_ms(100)