# -*- coding: utf-8 -*-
#!pip install pycryptodome

# Python Cryptography Toolkit for AES encryption
import sys
from cryptage import *

import serial
import time
import os
import requests

#connexion série à un périphérique externe via le port en paramètre à un vitesse de 115200 bauds
ser = serial.Serial('/dev/ttyACM0', 115200)

file2 = open("./lastbt.txt","w+")

def clean_frame(frame):
    frame = frame.decode("utf-8") # enlever le b'
    frame = frame.replace("\r\n", "") # enlever le '\r\n'
    return frame

def recup_data(trame):
    trame1 = trame[45:47]
    trame1 += trame[42:44] # extraire les 4 derniers octets de la trame
    #print(trame1)
    data = int(trame1, 16) # convertir la trame en décimal et diviser par 100 pour obtenir la température en degrés Celsius
    return data

def recup_info(trame):
    trame1 = trame[9:11]
    trame1 += trame[6:8] # extraire les 4 derniers octets de la trame
    #print("info1 :", trame1)
    info = int(trame1, 16)
    #print("info2 :", info)
    return info
  
def paytotrame(trame,payload):
  clean_payload = payload.replace(" ","")
  #returnhex(trame)
  trame_dec=trame[0:62]+clean_payload+trame[94:106]
  # print("trame :",trame)
  # print("payload :",clean_payload)
  # print("trame_dec :",trame_dec)
  return trame_dec

def sendTrame(trame):
  ser.write(trame.encode())#'utf-8'))
  
def exporttrame(trame):
  file1 = open("./trame.txt","w+")
  file1.write(trame)
  file1.close()
  
def exportbt(trame):
  file2 = open("./lastbt.txt","w+")
  file2.write(trame)
  file2.close()
  
def readbt():
  file2 = open("./lastbt.txt","r")
  bt = file2.readlines()
  file2.close()
  return bt
  
while True:
  data = ser.readline()
  #print ("Trame Brut :",data)
  
  #print("longueur :",len(data))
  
  trame = clean_frame(data)
  if len(trame) == 106:
    payload = decrypt(trame)
    print ('Payload = ', payload)
    
    packet_info = recup_info(payload)
    if packet_info == 1026:
      temp = recup_data(payload)
      temperature = temp/100 
      print("La temperature est de ", temperature,"°C")
      #temp = {temp} # données à envoyer au serveur
      #response = requests.post(url, json=temp) # Envoi de la demande POST avec les données en format JSON
      #print(response.text) # Affiche la réponse du serveur
      url = 'https://eloitourangin.fr/SAE/post.php?speed='+str(temp)
      print(url)
      requests.post(url)
      
    if packet_info == 1029:
      hum = recup_data(payload)
      humidity = hum/100
      print("L'Humidité est de ", humidity,"%")
    elif packet_info == 18:
      print("Bouton !!!!  ", recup_data(payload), "clic")
      last_button_dec = paytotrame(trame,payload)
      exportbt(last_button_dec)
    print("\n")
  
  elif len(trame) == 10:
    print("Acknowledgement")
    print("\n")
  
  elif len(trame) == 7:
    #print("Bouton")
    last_button_dec = readbt()
    # Extraction de la première chaîne de caractères
    chaine = last_button_dec[0]
    # Conversion de la chaîne de caractères en une chaîne de caractères simple
    last_button_dec = ''.join(chaine)
    #print("Last button:",last_button_dec)
    send_trame = incrementTrame(last_button_dec)
    send_trame = concatenageTrame(send_trame)
    #send_trame = decrypt(send_trame)
    #print("Trame incr :",send_trame)
    exportbt(send_trame)
    exporttrame(send_trame)
    sendTrame(send_trame)
    #time.sleep(1)
    #print("\n")