import utime
import machine
import ujson as json
import network
import urequests
import time
# Function to log data to a JSON file
def log_data(data):
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# r = urequests.get('https://api.ipify.org')
r = urequests.get('http://127.0.0.1:5000/api/data/get')
print(r.text)
# with open("data.json", "a") as f:
# print(data)
# json.dump(data, f)
# f.write("\n")
print('run...')
# Main loop
while True:
try:
# Replace this with your own data collection code
data_to_log = {"value1": 1, "value2": 2, "value3": 3} # Replace with your JSON data
# Get the current timestamp
timestamp = utime.localtime()
timestamp_str = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
timestamp[0], timestamp[1], timestamp[2], timestamp[3], timestamp[4], timestamp[5]
)
# Add timestamp to the data
data_to_log["timestamp"] = timestamp_str
# Log the data
log_data(data_to_log)
# Sleep for 10 minutes (600 seconds)
utime.sleep(6)
print('logged...')
except Exception as e:
print("Error:", e)
# Sleep for 10 seconds if there is an error
utime.sleep(10)