Esempio n. 1
0
class ConnectionFrame(Frame):
    def __create_connection(self):
        self.connection = BeetleConnection()

        def connection_callback(state):
            if state == ConnectionStatus.DISCONNECTED:
                self.event_disconnected()
            elif state == ConnectionStatus.CONNECTED:
                self.event_connected()
            elif state == ConnectionStatus.FAILED_TO_CONNECT:
                self.event_failed_to_connect()
            elif state == ConnectionStatus.DISCONNECTED_TIMEOUT:
                self.event_disconnected_timeout()
            elif state == ConnectionStatus.DISCONNECTED_ERROR:
                self.event_disconnected_error()
            else:
                raise Exception("Unhandled connection callback")

        self.connection.register_status_callback(connection_callback)

    def __set_connected_button(self):
        def connect_button_callback():
            self.connection.disconnect()

        self.connection.write(b"U")
        self.connection.write(b"\n")

        self.connect_button["command"] = connect_button_callback
        self.connect_button["text"] = "Disconnect"
        self.device_picker["state"] = "disabled"

    def __set_disconnected_button(self):
        def connect_button_callback():
            device = self.device_picker.get()
            self.connection.connect(device)

        self.connect_button["command"] = connect_button_callback
        self.connect_button["text"] = "Connect"

        self.device_picker["state"] = "normal"

    def __init__(self, main):
        self.main = main
        Frame.__init__(self, self.main.window, relief="ridge")

        self.__create_connection()

        self.device_label = ttk.Label(self, text="Device")
        self.device_label.grid(column=0, row=0, sticky="W")

        self.connection_label = ttk.Label(self, text="Connection")
        self.connection_label.grid(column=0, row=1, sticky="W")

        self.device_picker = ttk.Combobox(self, values=())
        self.device_picker.grid(column=1, row=0, sticky="WE", columnspan=2)

        self.connection_status_label = ttk.Label(self, text="")
        self.connection_status_label.grid(column=1, row=1, sticky="WE", columnspan=2)

        self.connect_button = ttk.Button(self, text="Connect")
        self.connect_button.grid(column=0, row=2, sticky="WE", columnspan=2)

        self.clear_button = ttk.Button(self, text="Clear all")
        self.clear_button.grid(column=2, row=2, sticky="WE")

        self.type_label = ttk.Label(self, text="Type : ")
        self.type_label.grid(column=0, row=4, sticky="W")

        self.type_entry = ttk.Entry(self)
        self.type_entry.grid(column=0, row=4, sticky="E")

        self.port_label = ttk.Label(self, text="Port : ")
        self.port_label.grid(column=1, row=4, sticky="W")

        self.port_entry = ttk.Entry(self)
        self.port_entry.grid(column=1, row=4, sticky="E")

        self.Uptime_button = ttk.Button(self, command = self.UptimeReturn, text="Uptime")
        self.Uptime_button.grid(column=2, row=4, sticky="WE")

        self.request_button = ttk.Button(self,command = self.SendRequest, text="Send Request")
        self.request_button.grid(column=0, row=5, sticky="WE", columnspan=3)

        self.reset_button = ttk.Button(self,command = self.reset, text="Reset")
        self.reset_button.grid(column=0, row=7, sticky="WE", columnspan=3)

        self.return_text = Text(self)
        self.return_text.config(state='disabled')
        self.return_text.grid(column=0, row=6, sticky="WE", columnspan=3)
        self.return_text.see("end")
        self.clear()

        self.DEBUGMODE = False
        self.main.window.after(2000, self.refresh_debug)#self.printSerialReturn())

        def clear_button_callback():
            self.clear()

        self.clear_button["command"] = clear_button_callback

    def refresh_debug(self):

        if self.DEBUGMODE == True and self.connection.is_connected():
            self.printSerialReturn()
        self.main.window.after(2000, self.refresh_debug)#self.printSerialReturn())

    def event_connected(self):
        self.connection_label["text"] = "Connected"

        self.__set_connected_button()

    def event_disconnected(self):
        self.connection_label["text"] = "Disconnected"

        self.__set_disconnected_button()

    def event_disconnected_timeout(self):
        self.connection_label["text"] = "Disconnected (Timeout)"

        self.__set_disconnected_button()

    def event_disconnected_error(self):
        self.connection_label["text"] = "Disconnected (Error)"

        self.__set_disconnected_button()

    def event_failed_to_connect(self):
        self.connection_label["text"] = "Disconnected (Failed to connect)"

        self.__set_disconnected_button()

    def SendRequest(self):
        CommandType = self.type_entry.get()  #String is saved in Command
        CommandPort = self.port_entry.get()

        if not self.connection.is_connected():
            self.connection_status_label["text"] = "Cannot write when not connected"
            return

        # Entry validation:
        if CommandType not in ['0','1','2','X','x']:
            txt = "Please enter valid type (0,1,2,X)"
            self.connection_status_label["text"] = txt
            return

        else:
            self.connection_status_label["text"] = ''

        if CommandType == '1':
            if CommandPort not in ['0','1','2']:
                txt = "Please enter valid analogue port number (0,1,2)"
                self.connection_status_label["text"] = txt
                return
			    

        elif CommandType == '2':
            if CommandPort not in ['0','1','2']:
                txt = "Please enter valid digital port number (0,1,2)"
                self.connection_status_label["text"] = txt
                return


        elif CommandType in ['x','X']:
            if CommandPort not in ['0','1']:
                txt = "Please enter 0 (debug off) or 1 (debug on) in port field"
                self.connection_status_label["text"] = txt
                return
            else:
                if CommandPort == '1':
                    self.DEBUGMODE = True
                    self.return_text.config(state='normal')
                    self.return_text.insert(END,"\n"+'Debug-Mode On')
                    self.return_text.config(state='disabled')
                    self.return_text.see("end")

                    self.connection.write(CommandType.encode('utf-8'))
                    self.connection.write(CommandPort.encode('utf-8'))
                else:
                    self.DEBUGMODE = False
                    self.type_entry.config(state='normal')

                    self.return_text.config(state='normal')
                    self.return_text.insert(END,"\n"+'Debug-Mode Off')
                    self.return_text.config(state='disabled')
                    self.return_text.see("end")

                    self.connection.write(CommandType.encode('utf-8'))
                    self.connection.write(CommandPort.encode('utf-8'))
        else:
            self.connection_status_label["text"] = ''

        self.connection.write(CommandType.encode('utf-8'))
        self.connection.write(CommandPort.encode('utf-8'))
        self.connection.write(b"\n")
        self.printSerialReturn()

    def printSerialReturn(self):
        sleep(0.02)
        OutputText = self.CleanList(self.connection.receive())

        if OutputText != '[]':
            self.return_text.config(state='normal')
            self.return_text.insert(END,"\n"+OutputText)
            self.return_text.config(state='disabled')
            self.return_text.see("end")

    def CleanList(self,InputList):
        OutputString = "["
        for returnstring in range(0,len(InputList)):
            if (returnstring != (len(InputList) - 1)):
                OutputString += str(InputList[returnstring][:-1]) + ', '
            else:
                OutputString += str(InputList[returnstring][:-1])

        OutputString += "]"
        return OutputString

    def UptimeReturn(self):
        if self.connection.is_connected():
            self.connection.write(b"U")
            self.connection.write(b"\n")
            self.printSerialReturn()

    def clear(self):

        if self.connection.is_connected():

            self.return_text.config(state='normal')
            self.return_text.delete(1.0,END)
            self.return_text.config(state='disabled')
            self.type_entry.delete(0,'end')
            self.port_entry.delete(0,'end')
            self.type_entry.config(state='normal')
            self.port_entry.config(state='normal')
            self.request_button.config(state='normal')
        else:
            self.return_text.config(state='normal')
            self.return_text.delete(1.0,END)
            self.return_text.config(state='disabled')
            self.type_entry.delete(0,'end')
            self.port_entry.delete(0,'end')
            self.type_entry.config(state='normal')
            self.port_entry.config(state='normal')
            self.request_button.config(state='normal')

            self.device_list = BeetleConnection.possible_connections()

            possible_values = [
                x.device for x in self.device_list if "Arduino" in str(x)
            ]
            self.device_picker["values"] = possible_values
            if len(possible_values) > 0:
                self.device_picker.current(0)
            self.event_disconnected()
			
    def reset(self):
        if self.connection.is_connected():
            self.connection.write(b"R")
            self.connection.write(b"\n")
            print('yeet')
Esempio n. 2
0
class App(tk.Tk):
    connectframe = -1
    diagnosticframe = -1
    homeframe = -1
    container_global = -1
    voltage_measurements = []
    current_measurements = []
    phase_measurements = []
    time_measurements = []
    runtime = -1
    trip_status = "LOW"
    display_time = 60
    total_real_power = 0
    total_reactive_power = 0
	
    def __init__(self, *args, **kwargs):    
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.grid(row=0, column = 0, sticky='nsew')

        self.__create_connection()
        self.container_global = container
		
        self.title("Smart Power Meter")
        self.call('wm', 'iconphoto', self.winfo_toplevel()._w, tk.PhotoImage(file='baseline_power_black_24dp.png'))
        
        self.geometry("655x660")
        self.resizable(False, False)

        self.diagnosticframe= DiagnosticFrame(self.container_global, self)
        self.diagnosticframe.grid(row=2, column = 0, sticky='NEWS')
		
        self.connectframe= ConnectionFrame(container, self)
        self.connectframe.grid(row=1, column = 0, sticky='NEWS')	

        self.homeframe= HomeFrame(container, self)
        self.homeframe.grid(row=2, column = 0, sticky='NEWS')	
		
        self.remove_grid_diagnostic_frame()
        self.remove_grid_connection_frame()
        #self.remove_grid_home_frame()
		
        self.after(1000, self.sample_data)#self.printSerialReturn())
		
    def sample_data(self):
        if self.connection.is_connected():
           self.parse_input()
        self.after(1000, self.sample_data)
        self.runtime=self.runtime+1
		
    def parse_input(self):
        sleep(0.05)
        input_list = self.connection.receive()
        #print(input_list)
        allocated = False
        for x in range(len(input_list)): 
            if(input_list[x] == 'U\r'): #uptime condition
                self.connectframe.writeToScreen(input_list[x] + ', ' + input_list[x+1])
                allocated = True
            if(input_list[x] == 'X\r'): #debug condition
                self.connectframe.writeToScreen(input_list[x] + ', ' + input_list[x+1])
                allocated = True
            if(input_list[x] == '0\r' and input_list[x-1] != '0\r' and input_list[x-1] != '1\r' and input_list[x-1] != '2\r'):	#student number condition
                self.connectframe.writeToScreen(input_list[x] + ', ' + input_list[x+1] )		
                allocated = True
            if(input_list[x] == '1\r' and input_list[x-1] != '0\r' and input_list[x-1] != '1\r' and input_list[x-1] != '2\r'):	#analog reading condition
                self.connectframe.writeToScreen(input_list[x] + ', ' + input_list[x+1] + ', ' + input_list[x+2])	
                allocated = True				
            if(input_list[x] == '2\r' and input_list[x-1] != '0\r' and input_list[x-1] != '1\r' and input_list[x-1] != '2\r'):	#digital reading condition
                self.connectframe.writeToScreen(input_list[x] + ', ' + input_list[x+1] + ', ' + input_list[x+2])	
                allocated = True				
            if allocated == False and input_list[x] != "[]": 
                self.update_live_data(input_list[x])
                allocated = True	      
		
    def update_live_data(self, input_string):
        measurements = input_string.split()
        self.trip_status = measurements[3]
        self.phase_measurements.append(float(measurements[0]))
        self.current_measurements.append(float(measurements[1]))
        self.voltage_measurements.append(float(measurements[2]))
        self.time_measurements.append(self.runtime)
        if(self.runtime > self.display_time):
            self.phase_measurements.pop(0)
            self.current_measurements.pop(0)
            self.voltage_measurements.pop(0)
            self.time_measurements.pop(0)
        print(input_string)
        self.diagnosticframe.updateUI(self)
        self.homeframe.updateUI(self)			
			
    #going to home frame from other frames
    def show_home_frame_from_diagnostic_frame(self):
        self.remove_grid_diagnostic_frame()
			
        self.setup_grid_home_frame()
        self.connectframe.tkraise()	

    def show_home_frame_from_connection_frame(self):
        self.remove_grid_connection_frame()
			
        self.setup_grid_home_frame()
        self.connectframe.tkraise()	
		
    #going to diagnostic frame from other frames
    def show_diagnostic_frame_from_connection_frame(self):
        self.remove_grid_connection_frame()	
		
        self.setup_grid_diagnostic_frame()
        self.diagnosticframe.tkraise()	

    def show_diagnostic_frame_from_home_frame(self):
        self.remove_grid_home_frame()	
		
        self.setup_grid_diagnostic_frame()
        self.diagnosticframe.tkraise()	
		
    #going to connection frame from other frames
    def show_connection_frame_from_home_frame(self):
        self.remove_grid_home_frame()	
		
        self.setup_grid_connection_frame()
        self.diagnosticframe.tkraise()	

    def show_connection_frame_from_diagnostic_frame(self):
        self.remove_grid_diagnostic_frame()	
		
        self.setup_grid_connection_frame()
        self.diagnosticframe.tkraise()	


    def setup_grid_connection_frame(self):
        self.config(menu=self.connectframe.menubar)
        self.connectframe.statusbar.grid(column=0, row=7, padx=5, pady=5, sticky="WES", columnspan=4)
        self.connectframe.page_title_label.grid(column=0, row=0, padx=100, pady=5, columnspan=4)			
        self.connectframe.device_picker.grid(column=2, row=1, padx=5, pady=5,  sticky="WE", columnspan=2)		
        self.connectframe.device_label.grid(column=0, row=1, padx=5, pady=5, sticky="W", columnspan=2)
        self.connectframe.connect_button.grid(column=0, row=2,padx=5, pady=5, sticky="WE", columnspan=4)
        self.connectframe.type_label.grid(column=0, row=3,padx=5, pady=5, sticky="W")	
        self.connectframe.type_entry.grid(column=1, row=3,padx=5, pady=5, sticky="E", columnspan=1)
        self.connectframe.port_label.grid(column=2, row=3,padx=5, pady=5, sticky="W")
        self.connectframe.port_entry.grid(column=3, row=3,padx=5, pady=5, sticky="E", columnspan=1)	
        self.connectframe.request_button.grid(column=0, row=4,padx=5, pady=5, sticky="WE", columnspan=4)
        self.connectframe.clear_button.grid(column=0, row=6,padx=5, pady=5, sticky="WE", columnspan=2)
        self.connectframe.Uptime_button.grid(column=2, row=6, padx=5, pady=5, sticky="WE", columnspan=2)
        self.connectframe.return_text.grid(column=0, row=5, padx=5, pady=5, sticky="WE", columnspan=4)	
		
    def remove_grid_connection_frame(self):
        self.connectframe.menubar.grid_forget()	
        self.connectframe.statusbar.grid_forget()
        self.connectframe.page_title_label.grid_forget()	
        self.connectframe.device_picker.grid_forget()		
        self.connectframe.device_label.grid_forget()
        self.connectframe.connect_button.grid_forget()
        self.connectframe.type_label.grid_forget()		
        self.connectframe.type_entry.grid_forget()	
        self.connectframe.port_label.grid_forget()
        self.connectframe.port_entry.grid_forget()		
        self.connectframe.request_button.grid_forget()
        self.connectframe.clear_button.grid_forget()
        self.connectframe.Uptime_button.grid_forget()
        self.connectframe.return_text.grid_forget()	 

    def setup_grid_diagnostic_frame(self):
        self.config(menu=self.diagnosticframe.menubar)
        self.diagnosticframe.page_title_label.grid(column=0, row=0, padx=230, pady=5,sticky="NSEW", columnspan=4)
        self.diagnosticframe.voltage_canvas.get_tk_widget().grid(column=0, row=1, padx=10, pady=0,sticky="WE", columnspan=4, rowspan=3)
        self.diagnosticframe.current_canvas.get_tk_widget().grid(column=0, row=4, padx=10, pady=0,sticky="WE", columnspan=4, rowspan=3)
        self.diagnosticframe.phase_canvas.get_tk_widget().grid(column=0, row=7, padx=10, pady=0,sticky="WE", columnspan=4, rowspan=3)
        self.diagnosticframe.statusbar.grid(column=0, row=13, padx=5, pady=0, sticky="WES", columnspan=4)
        #self.diagnosticframe.reset_button.grid(column=0, row=12, padx=5, pady=5, sticky="WES", columnspan=4)	
		
    def remove_grid_diagnostic_frame(self):
        self.diagnosticframe.page_title_label.grid_forget()
        self.diagnosticframe.menubar.grid_forget()
        self.diagnosticframe.voltage_canvas.get_tk_widget().grid_forget()
        self.diagnosticframe.current_canvas.get_tk_widget().grid_forget()			
        self.diagnosticframe.phase_canvas.get_tk_widget().grid_forget()
        self.diagnosticframe.statusbar.grid_forget()
        #self.diagnosticframe.reset_button.grid_forget()

    def setup_grid_home_frame(self):	
        self.config(menu=self.homeframe.menubar)
        self.homeframe.page_title_label.grid(column=0, row=0, padx=230, pady=5,sticky="NSEW", columnspan=4)		
        self.homeframe.newest_measurements_label.grid(column=0, row=1, padx=230, pady=20,sticky="NSEW", columnspan=4)		
        self.homeframe.newest_measurements_label.config(font=("Calibri", 14))
        self.homeframe.newest_voltage_label.grid(column=0, row=2, padx=20, pady=5,sticky="W", columnspan=1)	
        self.homeframe.newest_voltage_entry.grid(column=3, row=2,padx=20, pady=5, sticky="E", columnspan=1)		
        self.homeframe.newest_current_label.grid(column=0, row=3, padx=20, pady=5,sticky="W", columnspan=1)
        self.homeframe.newest_current_entry.grid(column=3, row=3,padx=20, pady=5, sticky="E", columnspan=1)		
        self.homeframe.newest_phase_label.grid(column=0, row=4, padx=20, pady=5,sticky="W", columnspan=1)	
        self.homeframe.newest_phase_entry.grid(column=3, row=4,padx=20, pady=5, sticky="E", columnspan=1)				
        self.homeframe.newest_real_power_label.grid(column=0, row=5, padx=20, pady=5,sticky="W", columnspan=1)	
        self.homeframe.newest_real_power_entry.grid(column=1, row=5,padx=20, pady=5, sticky="E", columnspan=1)			
        self.homeframe.newest_reactive_power_label.grid(column=2, row=5, padx=20, pady=5,sticky="W", columnspan=1)	
        self.homeframe.newest_reactive_power_entry.grid(column=3, row=5,padx=20, pady=5, sticky="E", columnspan=1)			
        self.homeframe.total_power_label.grid(column=0, row=6, padx=250, pady=20,sticky="SEW", columnspan=4)		
        self.homeframe.total_real_power_label.grid(column=0, row=7, padx=20, pady=5,sticky="W", columnspan=1)	
        self.homeframe.total_real_power_entry.grid(column=1, row=7,padx=20, pady=5, sticky="E", columnspan=1)	
        self.homeframe.total_reactive_power_label.grid(column=2, row=7, padx=20, pady=5,sticky="W", columnspan=1)	
        self.homeframe.total_reactive_power_entry.grid(column=3, row=7,padx=20, pady=5, sticky="E", columnspan=1)
        self.homeframe.system_status_label.grid(column=0, row=8, padx=270, pady=20,sticky="SEW", columnspan=4)
        self.homeframe.trip_status_label.grid(column=0, row=9, padx=20, pady=5,sticky="W", columnspan=1)	
        self.homeframe.trip_status_entry.grid(column=3, row=9,padx=20, pady=5, sticky="E", columnspan=1)
        self.homeframe.connection_status_label.grid(column=0, row=10, padx=20, pady=5,sticky="W", columnspan=1)	
        self.homeframe.connection_status_entry.grid(column=3, row=10,padx=20, pady=5, sticky="E", columnspan=1)	    
        self.homeframe.reset_button.grid(column=0, row=11, padx=20, pady=5, sticky="WES", columnspan=4)		
        self.homeframe.labelImage.grid(column=0, row=12, padx=20, pady=5, sticky="SEW", columnspan=4)
		
    def remove_grid_home_frame(self):		
        self.homeframe.menubar.grid_forget()	
        self.homeframe.page_title_label.grid_forget()		
        self.homeframe.newest_measurements_label.grid_forget()		
        self.homeframe.newest_measurements_label.grid_forget()
        self.homeframe.newest_voltage_label.grid_forget()
        self.homeframe.newest_voltage_entry.grid_forget()	
        self.homeframe.newest_current_label.grid_forget()
        self.homeframe.newest_current_entry.grid_forget()
        self.homeframe.newest_phase_label.grid_forget()
        self.homeframe.newest_phase_entry.grid_forget()				
        self.homeframe.newest_real_power_label.grid_forget()	
        self.homeframe.newest_real_power_entry.grid_forget()			
        self.homeframe.newest_reactive_power_label.grid_forget()
        self.homeframe.newest_reactive_power_entry.grid_forget()			
        self.homeframe.total_power_label.grid_forget()		
        self.homeframe.total_real_power_label.grid_forget()
        self.homeframe.total_real_power_entry.grid_forget()
        self.homeframe.total_reactive_power_label.grid_forget()
        self.homeframe.total_reactive_power_entry.grid_forget()
        self.homeframe.system_status_label.grid_forget()
        self.homeframe.trip_status_label.grid_forget()	
        self.homeframe.trip_status_entry.grid_forget()
        self.homeframe.connection_status_label.grid_forget()	
        self.homeframe.connection_status_entry.grid_forget()	
        self.homeframe.reset_button.grid_forget()
        self.homeframe.labelImage.grid_forget()	
		
    def __create_connection(self):
        self.connection = BeetleConnection()

        def connection_callback(state):
            if state == ConnectionStatus.DISCONNECTED:
                self.connectframe.event_disconnected(self)
                self.homeframe.event_disconnected(self)
            elif state == ConnectionStatus.CONNECTED:
                self.connectframe.event_connected(self)
                self.homeframe.event_connected(self)
            elif state == ConnectionStatus.FAILED_TO_CONNECT:
                self.connectframe.event_failed_to_connect(self)
                self.homeframe.event_failed_to_connect(self)
            elif state == ConnectionStatus.DISCONNECTED_TIMEOUT:
                self.connectframe.event_disconnected_timeout(self)
                self.homeframe.event_disconnected_timeout(self)
            elif state == ConnectionStatus.DISCONNECTED_ERROR:
                self.connectframe.event_disconnected_error(self)
                self.homeframe.event_disconnected_error(self)
            else:
                raise Exception("Unhandled connection callback")

        self.connection.register_status_callback(connection_callback)