Hi, I am trying to send some data in a form of json as post request to my flask backend.
I keep getting erors. my flask backend is ruuning on local host so i got the url intact and my nicla vision board is connected to wifi.
below is the code and errro I am facing.
import sensor, image, time, os, tf, math, uos, gc, json
import network, urequests
import pyb
# Wi-Fi connection details
SSID = "***"
PASSWORD = "***"
# Initialize the NIC (network interface controller)
nic = network.WLAN(network.STA_IF)
nic.active(True)
# Attempt Wi-Fi connection
nic.connect(SSID, PASSWORD)
timeout = 600 # 2 seconds (20 * 100ms)
while not nic.isconnected() and timeout > 0:
print("Connecting to Wi-Fi...")
time.sleep(0.1)
timeout -= 1
if nic.isconnected():
print("Connected to Wi-Fi")
print(nic.ifconfig()) # Print the IP address, subnet mask, gateway, and DNS
else:
print("Failed to connect to Wi-Fi within 2 seconds.")
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_windowing((240, 240))
sensor.skip_frames(time=2000)
net = None
labels = None
min_confidence = 0.5
ledRed = pyb.LED(1)
ledGreen = pyb.LED(2)
try:
net = tf.load("trained.tflite", load_to_fb=uos.stat('trained.tflite')[6] > (gc.mem_free() - (64*1024)))
except Exception as e:
raise Exception('Failed to load "trained.tflite", did you copy the .tflite and labels.txt file onto the mass-storage device? (' + str(e) + ')')
try:
labels = [line.rstrip('\n') for line in open("labels.txt")]
except Exception as e:
raise Exception('Failed to load "labels.txt", did you copy the .tflite and labels.txt file onto the mass-storage device? (' + str(e) + ')')
colors = [
(255, 0, 0),
(0, 255, 0),
(255, 255, 0),
(0, 0, 255),
(255, 0, 255),
(0, 255, 255),
(255, 255, 255),
]
last_five_predictions = []
def send_data_with_retry(data, retry_count=3, delay_seconds=1):
while retry_count > 0:
try:
response = urequests.post('http://127.0.0.1:5000/data', json=data)
if response.status_code == 200:
print("Data sent to backend successfully")
return True
else:
print(f"Failed to send data. Response code: {response.status_code}")
except Exception as e:
print(f"Failed to send data: {e}")
time.sleep(delay_seconds)
retry_count -= 1
print("Failed to send data after retries")
return False
clock = time.clock()
while True:
clock.tick()
img = sensor.snapshot()
current_prediction = None
for i, detection_list in enumerate(net.detect(img, thresholds=[(math.ceil(min_confidence * 255), 255)])):
if i == 0:
continue
if len(detection_list) == 0:
continue
print(labels[i])
current_prediction = labels[i]
for d in detection_list:
[x, y, w, h] = d.rect()
img.draw_rectangle(x, y, w, h, color=colors[i], thickness=2)
if current_prediction:
last_five_predictions.append(current_prediction)
if len(last_five_predictions) > 10:
last_five_predictions.pop(0)
if all(pred == "Closed_Eye" for pred in last_five_predictions):
ledRed.on()
ledGreen.off()
print("drowsy")
data = {
"card_id": "5678",
"confidence": "0.98",
"location": "Location B",
"time_moved": str(time.localtime()),
"drowsiness_state": "Drowsy",
"contact": "Contact B"
}
print(data)
send_data_with_retry(data)
else:
ledGreen.on()
ledRed.off()
print("non_drowsy")
OUTPUT
Connected to Wi-Fi
(‘', '', '', '*’)
Closed_Eye
drowsy
{‘drowsiness_state’: ‘Drowsy’, ‘card_id’: ‘5678’, ‘location’: ‘Location B’, ‘confidence’: ‘0.98’, ‘time_moved’: ‘(2000, 1, 1, 0, 1, 22, 0, 1)’, ‘contact’: ‘Contact B’}
Failed to send data: [Errno 103] ECONNABORTED
Failed to send data: [Errno 103] ECONNABORTED
Failed to send data: [Errno 103] ECONNABORTED
Failed to send data after retries