#Project get

#imports
from machine import Pin, Timer
import network
import time
import math
import urequests
import json

#wifi
ssid = "Wokwi-GUEST"
counter = 0
#limitations
ANGLE = 50
ACCEL = 0.25
#LED
led = Pin(12, Pin.OUT)

#Connect to wifi
print("Connecting to wifi:")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
wifi.connect(ssid,"")
while (not wifi.isconnected() and counter < 10):
    print(".",end="")
    time.sleep(1)
    counter = counter + 1
if(wifi.isconnected()):
    print(' Connected to WiFi')
else:
    print(' Not connected!') #If no wifi end
    #sys.exit()

#Check for crash
while True:

    #Get newest data
    request = urequests.get('https://api.thingspeak.com/channels/2496395/feeds.json?results=2')
    request_data = json.loads(request.text)
    request.close()

    #Get result 1 data
    ax1 = float(request_data["feeds"][0]["field1"])
    az1 = float(request_data["feeds"][0]["field2"])
    ay1 = float(request_data["feeds"][0]["field3"])
    gx1 = float(request_data["feeds"][0]["field4"])
    gz1 = float(request_data["feeds"][0]["field5"])
    gy1 = float(request_data["feeds"][0]["field6"])
    timestamp1 = request_data["feeds"][0]["created_at"]

    #get result 2 data
    ax2 = float(request_data["feeds"][1]["field1"]) 
    az2 = float(request_data["feeds"][1]["field2"])
    ay2 = float(request_data["feeds"][1]["field3"]) 
    gx2 = float(request_data["feeds"][1]["field4"]) 
    gz2 = float(request_data["feeds"][1]["field5"])
    gy2 = float(request_data["feeds"][1]["field6"])
    timestamp2 = request_data["feeds"][1]["created_at"]

    #The following calculations may be wrong and are just examples:

    #Calculate based on seconds in day
    hour1, min1, sec1 = map(int,(timestamp1.split('T')[1].split('Z')[0]).split(':'))
    tot1 = (hour1 * 3600) + (min1 * 60) + sec1
    hour2, min2, sec2 = map(int,(timestamp2.split('T')[1].split('Z')[0]).split(':'))
    tot2 = (hour2 * 3600) + (min2 * 60) + sec2
    tot = tot2 - tot1
    
    #yro range: -250 to 250 degress
    g2 = [gx2,gy2,gz2]
    g1 = [gx1,gy1,gz1]
    g = [g2s - g1s for g1s, g2s in zip(g1,g2)] #gyro 2 - gyro 1
    gz = math.sqrt(g[0]**2 + g[1]**2 + g[2]**2) #Total gyro
    gzz = gz / tot #rate of change

    #accel range: -2 to 2 g's
    a2 = [ax2,ay2,az2]
    a1 = [ax1,ay1,az1]
    a = [a2s - a1s for a1s, a2s in zip (a1,a2)] #accel 2 - accel 1
    az = math.sqrt(a[0]**2 + a[1]**2 + a[2]**2) #total accel
    azz = az / tot #rate of change

    #Print Total Rate Of Change
    print()
    print("Start:",tot1,"End:",tot2)
    print("g-TROC: {:.2f}".format(gzz), "/", ANGLE)
    print("a-TROC: {:.2f}".format(azz), "/", ACCEL)

    #Check if crash
    if gzz > ANGLE and azz > ACCEL:
        print("Crash!")
        led.on()
        uhoh = 1
    else:
        print("No crash.")
        led.off()
        uhoh = 0

    #Send
    message = {'field1':uhoh}
    request = urequests.post('https://api.thingspeak.com/update?api_key=FOL1ZTYPZYG3NDI9', json = message)
    request.close()
    #time.sleep(1)