예제 #1
0
def start():
    """ Function called when start buton is pressed
        It checks that a card has been inserted by looking for
        auto-mounted /dev/sda partitions
    """
    found_sd = False
    for p in psutil.disk_partitions():
        if p.device == "/dev/sda2" and p.mountpoint == "/media/pi/rootfs":
            logger.info("Found SD card - looks like Raspbian")
            found_sd = True
        elif p.device == "/dev/sda1" and p.mountpoint == "/media/pi/boot":
            logger.info("Found SD card- looks like Raspbian")
            found_sd = True
        elif p.device == "/dev/sda1" and p.fstype == "vfat":
            logger.info("Found SD card - looks like NOOBs")
            found_sd = True

    if found_sd:
        instructions.enable()
        image_selecter.enable()
        button_burn.enable(
        )  # do this now becuase users might want to go with the default
        text_start.disable()
        button_start.disable()
        info(
            "Success!",
            "SD card detected. Please choose your operating system and then press 'Burn'"
        )
    else:
        error("Uh oh!", "No SD card detected - please remove it and try again")
def finish_order():
    total_price = 0
    for f in ordered_list:
        total_price += f.get_price()

    if len(ordered_list) == 0:
        error("Error", "There is nothing in the order to complete")
    else:
        finalise_order = app.yesno("Are you done?",
                                   "Are you finished with your order")
        if finalise_order == True:
            new_order = [total_price]
            for food in ordered_list:
                new_order.append(food.get_name())
            '''Add new food using details entered. '''
            import csv
            with open('TomsGarage_Reciept.csv', 'a', newline='') as csvfile:

                writer = csv.writer(csvfile)

                writer.writerow(new_order)
            ordered_list.clear()
            order_listbox.clear()

        else:
            None
def admin_add_food():
    ''' Add new food using details entered. '''

    if name_text.value == "" or price_text.value == "" or course_text.value == "":
        success_lbl.text_color = (230, 50, 10)
        success_lbl.value = "Please complete all fields"
        # error(title, text)
        error("ERROR!", "Please complete all fields!")

    else:

        Food(name_text.value, price_text.value, course_text.value, 1)
        new_item = [name_text.value, price_text.value, course_text.value, 1]
        import csv
        with open('TomsGarage.csv', 'a') as csvfile:

            writer = csv.writer(csvfile)

            writer.writerow(new_item)

        success_lbl.text_color = (30, 230, 15)
        success_lbl.value = "New Food added"
        name_text.clear()
        price_text.clear()
        course_text.clear()
예제 #4
0
파일: client.py 프로젝트: Clacly96/PyMsg
def registrazione():
    global username
    c = socket_client()
    if c != -1:
        r = ["SERVICE", "regUser", usernameReg.value, passwordReg.value]
        r_ser = pickle.dumps(r)
        c.send(r_ser)
        risposta = c.recv(1024)
        risposta_decod = pickle.loads(risposta)
        if risposta_decod != "":
            if risposta_decod == "INSERITO":
                interfaccia.enable()
                finestraReg.hide()
                info("Successo", "Registrazione avvenuta con successo")
                username = usernameReg.value
                labelUsername.value = "Benvenuto " + username
                utenti = richiedi_utenti()
                for utente in utenti:
                    lista_utenti.append(utente)
            elif risposta_decod == "ESISTENTE":
                error("Errore", "Username già esistente, riprova.")
        c.close()
    elif c == -1:
        error(
            "Errore",
            "Errore di connessione, il server potrebbe non essere disponibile")
예제 #5
0
파일: client.py 프로젝트: Clacly96/PyMsg
def login():
    global username
    c = socket_client()
    if c != -1:
        r = ["SERVICE", "checkPwd", usernameLogin.value, passwordLogin.value]
        r_ser = pickle.dumps(r)
        c.send(r_ser)
        risposta = c.recv(1024)
        risposta_decod = pickle.loads(risposta)
        if risposta_decod != "":
            if risposta_decod == "CORRETTO":
                interfaccia.enable()
                finestraLog.hide()
                username = usernameLogin.value
                labelUsername.value = "Benvenuto " + username
                utenti = richiedi_utenti()
                for utente in utenti:
                    lista_utenti.append(utente)
            elif risposta_decod == "ERRORE":
                error("Errore", "Username o password errati, riprova.")
        c.close()
    elif c == -1:
        error(
            "Errore",
            "Errore di connessione, il server potrebbe non essere disponibile")
예제 #6
0
파일: client.py 프로젝트: Clacly96/PyMsg
def invia_dati():
    global username
    if textbox.value == "":
        return -1
    if lista_utenti.value == None:
        avvisi.value = "Inserisci nome desinatario"
        return -1
    c = socket_client()
    if c != -1:
        testo_messaggio = textbox.value
        richiesta = [
            "POST",
            str(testo_messaggio),
            str(lista_utenti.value), username
        ]
        richiesta_ser = pickle.dumps(richiesta)
        c.send(richiesta_ser)
        risposta = c.recv(1024)
        avvisi.value = pickle.loads(risposta)
        c.close()
        textbox.clear()
    elif c == -1:
        error(
            "Errore",
            "Errore di connessione, il server potrebbe non essere disponibile")
def clear_order():
    ''' Clear the listbox'''
    if len(ordered_list) == 0:
        error("Error", "There is nothing in the order to clear")
    else:
        order_listbox.clear()
        del ordered_list[:]
        update_total_price()
def undo():
    ''' Undo the last order that was appended to the list '''
    # deleting the last item that was appended to the list
    if len(ordered_list) == 0:
        error("Error", "There is nothing in the order to undo")
    else:
        del ordered_list[-1]
    # updating the listbox to redisplay the context of the listbox
    update_order_listbox()
    update_total_price()
예제 #9
0
def BlueDot_control():

    if BlueDot.is_connected == True:
        info( 'BlueDot', 'Press bluedot when ready to capture' )
        try:
            BlueDot.wait_for_press()
            BlueDot.wait_for_release()
            capture_Image()
        finally:
            return
    else:
        error( 'BlueDot', 'Device not connected' )
    def run(self):
        while self._running:
            '''
            连接硬件 串口
            '''
            env_is_valid = check_env()
            if not env_is_valid:
                try:
                    # 使其在cli下能用
                    error("错误信息", "请连接ubtrobot")
                except RuntimeError:
                    self.logger.info("错误信息: %s", "请插入ubtrobot")
                time.sleep(5)
            else:
                try:
                    port = find_ubtrobot()
                    self.ser = serial.Serial(port, 115200, timeout=1)  # 9600
                    break
                except OSError:
                    try:
                        # 使其在cli下能用
                        error("错误信息", "请连接ubtrobot")
                    except RuntimeError:
                        self.logger.info("错误信息: %s", "请插入ubtrobot")
                    time.sleep(5)

        while self._running:
            '''
            订阅到的是什么消息 消息体是怎样的
            '''
            message = self.read()
            cmd_map = {
                "forward": [],
                "backward": [],
                "left": [],
                "right": [],
                "push ups": [],
                "stop": [],
                "init": [],
                "happy birthday": [],
                "left punch": []
            }
            self.logger.debug("message {}".format(message))
            if message.get("topic") == "eim":
                cmd = cmd_map.get(message.get("data"))
            if cmd:
                self.logger.debug("cmd:{}".format(cmd))
                # 如果是linux每次都要重连
                if platform.system() == "Linux":
                    port = find_linux_port()
                    self.ser = serial.Serial(port, 115200, timeout=1)
                self.ser.write(cmd)
예제 #11
0
def comCheck(baudArg, radioPortArg, loopbackPortArg, stopBitsArg, parityArg,
             byteSizeArg, TX, RX):

    global root

    try:

        cat = serial.Serial(port=radioPortArg,
                            baudrate=baudArg,
                            stopbits=stopBitsArg,
                            parity=parityArg,
                            bytesize=byteSizeArg)
        tnc = serial.Serial(port=loopbackPortArg, rtscts=True)

        while True:

            if killComFlag:

                cat.write(RX)

                break

            if tnc.cts:

                cat.write(TX)

                while tnc.cts:

                    if killComFlag:

                        cat.write(RX)

                        break

                cat.write(RX)

    except serial.SerialException:

        guizero.error("Error", "Cannot open COM port!")

        try:

            cat.write(RX)

        except:

            pass

        StartTxButton.enable()
        EndTxButton.disable()
예제 #12
0
def delete_student():
    '''This function deletes the selected student.'''
    if student_listbox.value == None:
        delete_lbl.value = "No student selected"
        error("ERROR!", "No student selected.")
    else:
        #check if they really want to delete the student
        check_delete = yesno("ALERT",
                             "Are you sure you want to delete this student?")
        if check_delete == True:
            #get the index of the student we are deleting
            i = student_name.index(student_listbox.value)
            #delete from both the student_list and the student_list lists
            del (student_names[i])
            del (student_list[i])
예제 #13
0
def add_student():
    ''' Add new student using details entered. '''
    if name_text.value == "" or age_text.value == "" or phone_text.value == "" or class_listbox.value == None:
        success_lbl.value = "Please complete all fields."
        #error
        error("ERROR!", "Please complete all fields.")
    else:
        Student(name_text.value, age_text.value, phone_text.value,
                gender_combo.value, class_listbox.value)
        success_lbl.value = "New Student entered!"
        success_lbl.clear()
        name_text.clear()
        age_text.clear()
        phone_text.clear()
        name_text.focus()
예제 #14
0
def save_file():
    if not buffer:
        error('Error', 'No file loaded!')
        return
    try:
        buffer_with_data = FilterSteganographer().\
            hide(buffer, bytes(text_box_secret.get(), encoding='utf8'), read_key())
    except AssertionError as e:
        error('Error', e)
        return
    f = asksaveasfile(mode='wb', defaultextension=".png")
    if f is None:  # asksaveasfile return `None` if dialog closed with "cancel".
        return
    f.write(buffer_with_data)
    f.close()
예제 #15
0
 def import_python():
     global framerate
     global current_frame_number
     current_frame_number = 1
     filename = filedialog.askopenfilename(initialdir=HOME,
                                           title="Select file",
                                           filetypes=(("python files",
                                                       "*.py"),
                                                      ("all files", "*.*")))
     if len(filename) != 0:
         with open(filename, "r") as import_file:
             line1 = import_file.readline()
             if line1 == "# m8tricks output file \n":
                 #print("This looks like an 8x8 Grid Editor file")
                 try:
                     for line in import_file:
                         if line.startswith("sh.set_pixels"):
                             grid = line[14:-2]
                             frames[
                                 current_frame_number] = ast.literal_eval(
                                     grid)
                             current_frame_number += 1
                     current_frame_number -= 1
                     load_frame()
                 except:
                     error("Import failed",
                           "Sorry, that file could not be imported")
             else:
                 not_our_file = yesno(
                     "Uh-oh",
                     "This doesn't look like a m8tricks file. Carry on trying to import it?"
                 )
                 if not_our_file == True:
                     try:
                         for line in import_file:
                             if line.startswith("sh.set_pixels"):
                                 grid = line[14:-2]
                                 frames[
                                     current_frame_number] = ast.literal_eval(
                                         grid)
                                 current_frame_number += 1
                         current_frame_number -= 1
                         load_frame()
                     except:
                         error("Import failed",
                               "Sorry, that file could not be imported")
    def run(self):
        while True:
            env_is_valid = check_env()
            # 等待用户连接microbit
            if not env_is_valid:
                try:
                    # 使其在cli下能用
                    error("错误信息", "请插入microbit")
                except RuntimeError:
                    self.logger.info("错误信息: %s", "请插入microbit")
                time.sleep(5)
            else:
                port = find_microbit()
                self.ser = serial.Serial(port, 115200, timeout=1)
                break

        # lock = threading.Lock()

        # def request():
        #     while True:
        #         self.logger.info("in process")
        #         lock.acquire()
        #         self.message = self.read()
        #         lock.release()

        # bg_task = threading.Thread(target=request)
        # self.logger.info("thread start")
        # bg_task.daemon = True
        # bg_task.start()

        while True:
            '''
            订阅到的是什么消息 消息体是怎样的
            '''
            self.message = self.read()
            message = self.message
            self.logger.info(f"message {message}")
            self.message = {}
            if message != {}:
                message = json.dumps(message) + "\r\n"
                message_bytes = message.encode('utf-8')
                self.logger.debug(message_bytes)
                self.ser.write(message_bytes)
                time.sleep(0.2)
def admin_change_availability():
    ''' Change availability of selected item. '''

    if admin_listbox_available.value == None and admin_listbox_unavailable.value == None:
        delete_lbl.text_color = (230, 50, 10)
        delete_lbl.value = "Please select a food item to change"
        # error pop up message
        error("ERROR!:", "Please select a food item to delete")
    elif admin_listbox_available.value != None:
        for food in food_list:
            if food.get_name() == admin_listbox_available.value:
                food.set_availability()
                import csv
                with open('TomsGarage.csv', 'w', newline='') as csvfile:

                    writer = csv.writer(csvfile)
                    for f in food_list:
                        new_item = [
                            f.get_name(),
                            f.get_price(),
                            f.get_course(),
                            f.get_availability()
                        ]
                        writer.writerow(new_item)
                admin_update_listboxes()
    else:
        for food in food_list:
            if food.get_name() == admin_listbox_unavailable.value:
                food.set_availability()

                import csv
                with open('TomsGarage.csv', 'w', newline='') as csvfile:

                    writer = csv.writer(csvfile)
                    for f in food_list:
                        new_item = [
                            f.get_name(),
                            f.get_price(),
                            f.get_course(),
                            f.get_availability()
                        ]
                        writer.writerow(new_item)
                admin_update_listboxes()
예제 #18
0
def add_student():
    ''' Add new student using details entered. '''

    if name_text.value == "" or age_text.value == "" or phone_text.value == "" or class_listbox == None:
        success_lbl.text_color = (230, 50, 10)
        success_lbl.value = "Please complete all fields"
        # error(title, text)
        error("ERROR!", "Please complete all fields!")

    else:
        Student(name_text.value, age_text.value, phone_text.value,
                gender_combo.value, class_listbox.value)
        success_lbl.text_color = (30, 230, 15)
        success_lbl.value = "New Student added"
        name_text.clear()
        phone_text.clear()
        age_text.clear()
        class_listbox.clear()
        name_text.focus()
    def run(self):
        while True:
            '''
            连接硬件 串口
            '''
            env_is_valid = check_env()
            # 等待用户连接microbit
            if not env_is_valid:
                try:
                    # 使其在cli下能用
                    error("错误信息", "请连接ubtrobot")
                except RuntimeError:
                    self.logger.info("错误信息: %s", "请插入ubtrobot")
                time.sleep(5)
            else:
                port = find_ubtrobot()
                self.ser = serial.Serial(port, 115200, timeout=1)  # 9600
                break

        while True:
            '''
            订阅到的是什么消息 消息体是怎样的
            '''
            message = self.read()
            # 由于优必选alpha1的蓝牙协议没有公开,所以我暂时不把它放出来,统一用[]代替,有拿到合作的小伙伴,可以自行补上协议
            cmd_map = {
                "forward": [],
                "backward": [],
                "left": [],
                "right": [],
                "push ups": [],
                "stop": [],
                "init": [],
                "happy birthday": [],
                "left punch": []
            }
            self.logger.debug("message {}".format(message))
            if message["topic"] == "eim":
                cmd = cmd_map.get(message.get("data"))
            if cmd:
                self.logger.debug("cmd:{}".format(cmd))
                self.ser.write(cmd)
예제 #20
0
def loopyloop():

    raw_id = id_scan.value

    global session_user_logged
    global session_user_id

    session_timeout_tick()

    id_type = what_is(raw_id)

    if (id_type == "usr-raw"):
        session_timeout_reset()
        usrid = get_fit_id(raw_id)
        if (session_active()):
            session_log_out(usrid)
        else:
            session_log_in(usrid)
    elif (id_type == "usr"):
        session_timeout_reset()
        usrid = raw_id
        if (session_active()):
            session_log_out(usrid)
        else:
            session_log_in(usrid)
    elif (id_type == "cmd"):
        session_timeout_reset()
        execute(raw_id)
    elif (id_type == "eqp"):
        if (session_active()):
            session_timeout_reset()
            if (eqp_exists(raw_id)):
                check_out(raw_id)
            else:
                error("No such ID", "The scanned ID does not exist.")
            id_scan.value = ""
        else:
            error("Not logged in!",
                  "Please log in prior to scanning equipment!")
            id_scan.value = ""

    app.after(1000, loopyloop)
def add_student():
    ''' Add new student using details entered. '''
    
    # First check if all the fields have been completed
    if name_text.value == "" or age_text.value == "" or phone_text.value == "" or class_listbox.value == None:
        # If not, display an error message
        success_lbl.text_color = (161, 18, 16)
        success_lbl.value = "Please complete all fields" 
        error("ERROR", "Please complete all fields")
    else:
        # If so, add a new Student object and display a success message.
        # Clear all fields and make the name_text field the focus
        Student(name_text.value, age_text.value, phone_text.value, gender_combo.value, class_listbox.value)
        success_lbl.text_color = (23, 135, 53)
        success_lbl.value = "New student added successfully"
        name_text.clear()
        age_text.clear()
        phone_text.clear()
        class_listbox.value = []
        name_text.focus()
예제 #22
0
def main_program(dev):

    if not dev:
        whitelight = LED(21)
        whitelight.on()

    app = App(title="Chemistry Outreach Project v1.1")
    lighton = yesno("Initialisation check.", "Is the LED lit?")
    if not lighton:
        error("Initialisation error.",
              "Please check the connections and run the program again.")
        quit()
    app.destroy()

    tlength = int(
        input('How long would you like to run the simulations for (s)? '))
    run_program(tlength)

    if not dev:
        whitelight.off()
예제 #23
0
def fetch_pokemon():

    name = (input_box.value).lower()
    try:
        poke = pokemon(name)
        info = poke.sprites
        height = poke.height
        weight = poke.weight
        type = poke.type
        pic = get(poke.sprites.front_default).content
        image = Image.open(BytesIO(pic))
        image.save('poke.gif')
        icon.value = 'poke.gif'
        info_box.value = info
        height_box.value = height
        weight_box.value = weight
        type_box.value = abilities

    except:
        error('warning', 'invalid name, plz enetr the name properly')
예제 #24
0
def delete_student():
    ''' Deleting a selected student '''

    if student_listbox.value == None:
        delete_lbl.text_color = (230, 50, 10)
        delete_lbl.value = "Please select a student to delete"
        # error pop up message
        error("ERROR!:", "Please select a student to delete")
    else:
        # check if they really want to delete the selected student using a yes or no popup
        check_delete = yesno("ALERT!",
                             "Are you sure you want to delete this student?")
        if check_delete == True:
            # Get the index of the sutdent we are deleting (position in student_names)
            i = student_names.index(student_listbox.value)
            # delete the objects from student names and student list
            del (student_names[i])
            del (student_list[i])
            delete_lbl.text_color = (210, 45, 17)
            delete_lbl.value = "Student has been deleted"
            search()
    def _database_delete_button(self):
        on_note_number = int(self.textbox_on_number_notes.value)
        number_of_notes = len(self.database_notes)
        try:
            if on_note_number < 1 or on_note_number > number_of_notes:
                app_logger.app_logger.warning("Error: Current Note Number is more or less then total")

                guizero.error("Invalid Current Note Number", (" '" + str(on_note_number) + "' is a invalid option\n" +
                                                              "Please enter a number between 1 and " +
                                                              str(number_of_notes)))
                self._database_change_to_note_plus(0)

            elif guizero.yesno("Delete Note", "Are you sure you want to Delete Note " +
                                              self.textbox_on_number_notes.value + " out of " +
                                              self.textbox_total_notes.value + "?"):

                note_date_times = self.get_database_notes_dates()
                datetime_var = str(note_date_times[on_note_number - 1])

                sql_query = "DELETE FROM " + \
                            str(self.sql_column_names.sql_other_table) + \
                            " WHERE " + \
                            str(self.sql_column_names.date_time) + \
                            " = '" + datetime_var + "'"

                self._sql_execute(sql_query)

                self.database_notes.pop(on_note_number - 1)
                self.database_notes_dates.pop(on_note_number - 1)
                self.database_user_note_dates.pop(on_note_number - 1)

                self._database_change_to_note_plus(0)
        except Exception as error:
            app_logger.app_logger.error("Invalid Current Note number: " + str(error))
            guizero.error("Invalid Current Note Number", (" '" + self.textbox_on_number_notes.value +
                                                          "' is a invalid option\nPlease enter a number between 1 and " +
                                                          str(len(self.get_database_notes_dates()))))
            self._database_change_to_note_plus(0)
def admin_delete_food():
    '''Deletes an item off the menu.'''

    if admin_listbox_available.value == None:
        delete_lbl.text_color = (230, 50, 10)
        delete_lbl.value = "Please select a food item to delete"
        # error pop up message
        error("ERROR!:", "Please select a food item to delete")
    else:
        # check if they really want to delete the selected student using a yes or no popup
        check_delete = yesno(
            "ALERT!", "Are you sure you want to delete this food item?")
        if check_delete == True:
            # Get the index of the food item we are deleting (position in ordered_list)
            i = 0
            for food in food_list:
                if food.get_name() == admin_listbox_available.value:
                    del food_list[i]
                else:
                    i += 1
            # delete the objects from student names and student list

            import csv
            with open('TomsGarage.csv', 'w', newline='') as csvfile:

                writer = csv.writer(csvfile)
                for f in food_list:
                    new_item = [
                        f.get_name(),
                        f.get_price(),
                        f.get_course(),
                        f.get_availability()
                    ]
                    writer.writerow(new_item)
            delete_lbl.text_color = (210, 45, 17)
            delete_lbl.value = "Food item has been deleted"
            admin_update_listboxes()
예제 #27
0
def check_GPIO():
    print( '\nChecking GPIOs' )
    LED_gpio = [LED_Red_gpio.get(), LED_Orange_gpio.get(), LED_Yellow_gpio.get(),
                LED_Green_gpio.get(), LED_Blue_gpio.get() ]
    # check if there are GPIO boxes empty
    if any( gpio == '' for gpio in LED_gpio ):         
        error( 'Error', 'Undefined GPIO(s)!!' )
        print( 'Error: Undefined GPIO(s)!!' )
        print( 'Available GPIOs:', GPIO_list )
        Flag = False
    # check if there are repeated GPIOs in the boxes
    elif any( LED_gpio.count(gpio) > 1 for gpio in LED_gpio ):
        warn( 'Warning', 'Repeated GPIO(s)!!' )
        print( 'Warning: Repeated GPIO(s)!!' )        
        Flag = False
    # check if the gpios are available    
    elif all( gpio in GPIO_list for gpio in LED_gpio ): 
        Flag = True
    else:        
        error( 'Error', 'Unavailable GPIO(s)!!' )
        print( 'Error: Unavailable GPIO(s)!!' )
        print( 'Available GPIOs:', GPIO_list )
        Flag = False
    return  Flag
예제 #28
0
def reload_prompt_error():
    error("Reload Old Program Error", "You must select a old program to reload")
예제 #29
0
def time_prompt_error():
    error("Run Time Error", "Time field must be between values 0 and 3600")
예제 #30
0
def duty_cycle_error_prompt():
    error("Duty Cycle Error", "Duty Cycle fields must be between values 0 and 100")