#File: logic.py
from landline import *
import serial
from PyQt5.QtCore import QTimer

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)
        # A partir de aqui ya va lo tuyo (tu logica)
        self.page = 0 #Create a variable for the page number
        self.serial = serial.Serial('COM20',115200, timeout=0.05) #Establish communication port and frecuency

        self.timer = QTimer() #Set a variable for a timer
        self.timer.setInterval(80) #Establish the timer to read every 80 miliseconds, as in microcontroller
        self.timer.timeout.connect(self.read_sensor) #Go to the function read_sensor when timer goes
        self.timer.start() #Begin with the timer

    def read_sensor(self): #Create the function read_sensor
        try: #For it to not collapse, use the try command
            self.page = int(self.serial.readline().decode('utf-8')) #Set the page number from what's sent
            print(self.page) 
            self.stackedWidget.setCurrentIndex(self.page) #Use page number in the index of the stacked widget
        except:
            print("D':") #If the process somehow fails, send a sad face, but not stop there and continue
        
        
if __name__ == '__main__': #To open the interface
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    app.exec()