#Project send

#imports
from machine import Pin, I2C, sleep, PWM, Timer
from umqtt.simple import MQTTClient
import time
import network
import math
import urequests
import json

#Note accel() class has been copied from wokwi documentation
class accel():
    def __init__(self, i2c, addr=0x68):
        self.iic = i2c
        self.addr = addr
        self.iic.start()
        self.iic.writeto(self.addr, bytearray([107, 0]))
        self.iic.stop()

    def get_raw_values(self):
        self.iic.start()
        a = self.iic.readfrom_mem(self.addr, 0x3B, 14)
        self.iic.stop()
        return a

    def bytes_toint(self, firstbyte, secondbyte):
        if not firstbyte & 0x80:
            return firstbyte << 8 | secondbyte
        return - (((firstbyte ^ 255) << 8) | (secondbyte ^ 255) + 1)

    def get_values(self):
        raw_ints = self.get_raw_values()
        vals = {}
        vals["AcX"] = self.bytes_toint(raw_ints[0], raw_ints[1]) / 16384
        vals["AcY"] = self.bytes_toint(raw_ints[2], raw_ints[3]) / 16384
        vals["AcZ"] = self.bytes_toint(raw_ints[4], raw_ints[5]) / 16384
        vals["Tmp"] = self.bytes_toint(raw_ints[6], raw_ints[7]) / 340.00 + 36.53
        vals["GyX"] = self.bytes_toint(raw_ints[8], raw_ints[9]) / 131
        vals["GyY"] = self.bytes_toint(raw_ints[10], raw_ints[11]) / 131 
        vals["GyZ"] = self.bytes_toint(raw_ints[12], raw_ints[13]) / 131
        return vals

#mqtt and wifi
cid = "GTQxGzU4GAI8BAAuLwETFiw"
user = "GTQxGzU4GAI8BAAuLwETFiw"
pwrd = "POsfsdeTE94Jzkm5S5Y5F/Zt"
srvr = "mqtt3.thingspeak.com"
pub = "channels/2496395/publish"
ssid = "Wokwi-GUEST"
counter = 0
#Get device set up
i2c = I2C(scl=Pin(27), sda=Pin(26))
mpu = accel(i2c)

#Connect to wifi
print("Connecting to wifi/mqtt:")
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()

#Connect to mqtt
client = MQTTClient(client_id=cid,server=srvr,user=user,password=pwrd)
client.connect()
for x in range(counter): #False sense of loading
    print(".",end="")
    time.sleep(1)
print(" Connected to MQTT\n")
time.sleep(1)

#Loop for device values
while True:
    #If crashed get notification
    request = urequests.get('https://api.thingspeak.com/channels/2508701/feeds.json?results=1')
    request_data = json.loads(request.text)
    request.close()
    crash = int(request_data["feeds"][0]["field1"])
    if crash == 1:
        print("Emergency services have been alerted and are on there way!")

    #Get values
    temp = mpu.get_values()
    acx = temp["AcX"]
    acy = temp["AcY"] 
    acz = temp["AcZ"] 
    tmp = temp["Tmp"] #Not needed
    gyx = temp["GyX"]
    gyy = temp["GyY"]
    gyz = temp["GyZ"]

    #Print data
    print("acx: {:.2f}".format(acx))
    print("acy: {:.2f}".format(acy))
    print("acz: {:.2f}".format(acz))
    print("tmp: {:.1f}".format(tmp)) #Not needed
    print("gyx: {:.0f}".format(gyx))
    print("gyy: {:.0f}".format(gyy))
    print("gyz: {:.0f}".format(gyz))

    #Send data
    message = "field1=" + str(acx) + "&field2=" + str(acz) + "&field3=" + str(acy) + "&field4=" + str(gyx) + "&field5=" + str(gyz) + "&field6=" + str(gyy)
    client.publish(pub, message.encode("utf-8"))
    print("Sent data!")
    print()

    #wait and reconnect
    #time.sleep(1)
    client.connect()