예제 #1
0
class MyThermalPrinter:
    """Thermal Printer class with added button and LED"""

    # Poll initial button state and time

    def __init__(self, *args, **kwargs):
        self.button_pin = int(kwargs.pop('button_pin'))
        LED_PIN = int(kwargs.pop('led_pin'))
        self.hold_time = int(kwargs.pop('hold_time'))
        self.available = True
        self.tap_time = 0.01  # Debounce time for button taps
        self.next_interval = 0.0   # Time of next recurring operation
        self.daily_flag = False  # Set after daily trigger occurs
        GPIO.setup(LED_PIN, GPIO.OUT)
        GPIO.setup(self.button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        self.tp = AdafruitThermal(*args, **kwargs)
        #self.available = False
        # Enable LED and button (w/pull-up on latter)
        self.prev_button_state = GPIO.input(self.button_pin)
        self.prev_time = time.time()
        self.tap_enable = False
        self.hold_enable = False


    def check_network(self):
        # Processor load is heavy at startup; wait a moment to avoid
        # stalling during greeting.
        if self.available:
            time.sleep(0)

        # Show IP address (if network is available)
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 0))
            if self.available:
                GPIO.output(LED_PIN, GPIO.HIGH)
                #self.tp.print_line('My IP address is ' + s.getsockname()[0])
                logger.debug('My IP address is ' + s.getsockname()[0])
                #self.tp.feed(3)
                GPIO.output(LED_PIN, GPIO.LOW)
        except:
            if self.available:
                GPIO.output(LED_PIN, GPIO.HIGH)
                self.tp.bold_on()
                self.tp.print_line('Network is unreachable.')
                logger.debug('Network is unreachable.')
                self.tp.bold_off()
                self.tp.print('Connect display and keyboard\n' + \
                              'for network troubleshooting.')
                self.tp.feed(3)
                GPIO.output(LED_PIN, GPIO.LOW)
            exit(0)

    def greeting(self):
        GPIO.output(LED_PIN, GPIO.HIGH)
        # Print greeting image
        if self.available:
            self.tp.print_image(Image.open('gfx/hello.png'), True)
            self.tp.feed(3)
        GPIO.output(LED_PIN, GPIO.LOW)

    def query_button(self):
        # Poll current button state and time
        button_state = GPIO.input(self.button_pin)
        t = time.time()
        # Has button state changed?
        if button_state != self.prev_button_state:
            if button_state:
                GPIO.output(LED_PIN, GPIO.HIGH)
            else:
                GPIO.output(LED_PIN, GPIO.LOW)
            #print('Button changed')
            self.prev_button_state = button_state   # Yes, save new state/time
            self.prev_time = t
        else:                             # Button state unchanged
            if (t - self.prev_time) >= self.hold_time:  # Button held more than 'holdTime'?
                # Yes it has.  Is the hold action as-yet untriggered?
                if self.hold_enable == True:        # Yep!
                    print('Hold action to be exec')
                    self.hold()                      # Perform hold action (usu. shutdown)
                    self.hold_enable = False          # 1 shot...don't repeat hold action
                    self.tap_enable  = False          # Don't do tap action on release
            elif (t - self.prev_time) >= self.tap_time: # Not holdTime.  tapTime elapsed?
                #print('tap')
                # Yes.  Debounced press or release...
                if button_state == True:       # Button released?
                    #print('button_state', button_state)
                    if self.tap_enable == True:       # Ignore if prior hold()
                        self.tap()                     # Tap triggered (button released)
                        print('tap action executed')
                        self.hold_enable = False
                else:                         # Button pressed
                    
                    self.tap_enable  = True           # Enable tap and hold actions
                    self.hold_enable = True
                    #print('tap_enable', self.tap_enable)

        # LED blinks while idle, for a brief interval every 2 seconds.
        # Pin 18 is PWM-capable and a "sleep throb" would be nice, but
        # the PWM-related library is a hassle for average users to install
        # right now.  Might return to this later when it's more accessible.
        if ((int(t) & 1) == 0) and ((t - int(t)) < 0.05):
            GPIO.output(LED_PIN, GPIO.HIGH)
        else:
            GPIO.output(LED_PIN, GPIO.LOW)

        # Once per day (currently set for 6:30am local time, or when script
        # is first run, if after 6:30am), run forecast and sudoku scripts.
        loc_time = time.localtime()
        if loc_time.tm_hour ==  6 and loc_time.tm_min == 30:
            if self.daily_flag == False:
                self.daily()
                self.daily_flag = True
        else:
            self.daily_flag = False  # Reset daily trigger


    def tap(self):
        """Called when button is briefly tapped.  Invokes time/temperature script."""
        GPIO.output(LED_PIN, GPIO.HIGH)  # LED on while working
        subprocess.call(["python", "timetemp.py"])
        GPIO.output(LED_PIN, GPIO.LOW)

    def hold(self):
        """Called when button is held down.  Prints image, invokes shutdown process."""
        GPIO.output(LED_PIN, GPIO.HIGH)
        self.tp.print_line('Switching off...')
        self.tp.feed(3)
        for i in range(10):
            GPIO.output(LED_PIN, GPIO.HIGH)
            time.sleep(0.5)
            GPIO.output(LED_PIN, GPIO.LOW)
        subprocess.call("sync")
        subprocess.call(["shutdown", "-h", "now"])
        GPIO.output(LED_PIN, GPIO.LOW)

    
    def interval(self):
        """Called at periodic intervals (30 seconds by default).
            Invokes twitter script.
        """
        GPIO.output(LED_PIN, GPIO.HIGH)
        p = subprocess.Popen(["python", "twitter.py", str(lastId)],
                stdout=subprocess.PIPE)
        GPIO.output(LED_PIN, GPIO.LOW)
        return p.communicate()[0] # Script pipes back lastId, returned to main


    
    def daily(self):
        """ Called once per day (6:30am by default).
        
            Invokes weather forecast and sudoku-gfx scripts.
        """
        GPIO.output(LED_PIN, GPIO.HIGH)
        subprocess.call(["python", "forecast.py"])
        subprocess.call(["python", "sudoku-gfx.py"])
        GPIO.output(LED_PIN, GPIO.LOW)
예제 #2
0
# Test character double-height on & off
printer.double_height_on()
printer.print_line("Double Height ON")
printer.double_height_off()

# Set justification (right, center, left) -- accepts 'L', 'C', 'R'
printer.justify('R')
printer.print_line("Right justified")
printer.justify('C')
printer.print_line("Center justified")
printer.justify('L')
printer.print_line("Left justified")

# Test more styles
printer.bold_on()
printer.print_line("Bold text")
printer.bold_off()

printer.underline_on()
printer.print_line("Underlined text")
printer.underline_off()

printer.set_size('L')   # Set type size, accepts 'S', 'M', 'L'
printer.print_line("Large")
printer.set_size('M')
printer.print_line("Medium")
printer.set_size('S')
printer.print_line("Small")

printer.justify('C')