#!/usr/bin/env python

###############################################################################
#
# Copyright 2017 - 2019 NXP
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
###############################################################################

# DESCRIPTION:        Dispaly whether the data is HEALTHY or ANOMALY 
# INPUT/S:            NA  
# OUTPUT/S:           Dispaly with either HEALTHY or ANOMALY message

import serial
import sys
import time
from serial.serialutil import portNotOpenError
import tkinter as tk
  

###################################################################
# Common configurations
###################################################################
COMPORT     = "COM16"                    # Serial Port number of EVKB i.MXRT1050 development board
BAUDRATE    = "115200"

HEALTHY     = "Healthy"
ANOMALY     = "Anomaly"

X_Detection = 1
Y_Detection = 3
Z_Detection = 5


###################################################################
# Class for the serial operation
###################################################################
class SerLine(object):
    
    def __init__(self,device,baudrate):
        self._device = device
        self._baudrate = "115200"
        self._serial = None
        
    def opne(self):
        """
        Open serial line with predefined settings.
        """
        try:
            self._serial = serial.Serial(
                port=self._device,
                baudrate=self._baudrate)
            
            return self._serial
        except serial.SerialException:
            print("Serial Failure")
            self._serial = None
            sys.exit()
            
    def close(self):
        """
        Close serial line.
        """
        if self._serial is not None:
            self._serial.close()
            self._serial = None
            
    def writeBytes(self, message):
        """
        Write message, given as bytes or byte array, to serial line.
        
        message - data to be written.
        
        Returns the number of bytes written.
        
        Remarks: wait until all data is written.
        """
        self._serial.flushInput()
        self._serial.flushOutput()
        
        if self._serial is None:
            print ("Port is not opened")
            raise portNotOpenError
        
        message = message.encode()
        dataLength = self._serial.write(message)
        time.sleep(0.2)        
        return message
    
    def readBytes(self):
        """
        Read data from the serial line until there is no more data to be read.
        
        Returns the bytes read from the serial line when line is open.
        """
        if self._serial is None:
            raise portNotOpenError
        
        dataList = []
        while (len(dataList) != 6):
            temp = self._serial.readline()
            data = str(temp.decode('utf-8'))
            temp_ = data.split(":")
            for value in temp_:
                dataList.append(value)
        return dataList
 

###################################################################
# Function to dispaly HEALTHY/ANOMALY  message
################################################################### 

def counter_label(SerialComm,label_X_Value,label_Y_Value,label_Z_Value):  

    def count():
        ReceivedData = SerialComm.readBytes()

        if HEALTHY in ReceivedData[X_Detection]:
            label_X_Value.config(text=(str(ReceivedData[X_Detection-1])+":"+str(ReceivedData[X_Detection])),bg="green")
        elif ANOMALY in ReceivedData[X_Detection]:
            label_X_Value.config(text=(str(ReceivedData[X_Detection-1])+":"+str(ReceivedData[X_Detection])),bg="red")
            
        if HEALTHY in ReceivedData[Y_Detection]:    
            label_Y_Value.config(text=(str(ReceivedData[Y_Detection-1])+":"+str(ReceivedData[Y_Detection])),bg="green")
        elif ANOMALY in ReceivedData[Y_Detection]:                         
            label_Y_Value.config(text=(str(ReceivedData[Y_Detection-1])+":"+str(ReceivedData[Y_Detection])),bg="red")
        
        if HEALTHY in ReceivedData[Z_Detection]:                        
            label_Z_Value.config(text=(str(ReceivedData[Z_Detection-1])+":"+str(ReceivedData[Z_Detection])),bg="green")
        elif ANOMALY in ReceivedData[Z_Detection]:    
            label_Z_Value.config(text=(str(ReceivedData[Z_Detection-1])+":"+str(ReceivedData[Z_Detection])),bg="red")                   
        
        label_X_Value.after(1, count)
        
    count()
    
    

###################################################################
# Main function
###################################################################        
if __name__ == "__main__":

    print ("="*73)
    print ("="*32," Start ","="*32)
    print ("="*73)

    SerialComm = SerLine(COMPORT,BAUDRATE)
    SerialPort = SerialComm.opne()
     
    root = tk.Tk()
    root.title("Anomaly Detection")
    root.geometry("500x500")

    label_X_Value=tk.Label(root, font=("Arial", 45),anchor="center")
    label_X_Value.pack(fill=tk.X)
    
    label_Y_Value=tk.Label(root, font=("Arial", 45),anchor="center")
    label_Y_Value.pack(fill=tk.X)
    
    label_Z_Value=tk.Label(root, font=("Arial", 45),anchor="center")
    label_Z_Value.pack(fill=tk.X)
    
    tk.Button(root, text="Quit", command=root.quit,bg="red").pack()
    
    counter_label(SerialComm,label_X_Value,label_Y_Value,label_Z_Value)
    root.mainloop()

    print ("="*73)
    print ("="*33," End ","="*33)
    print ("="*73)


