Beispiel #1
0
def test_boutons(affichage=False,console=False,stockage=False):
    listeB = [22,18,16]
    lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])
    GPIO.setup(listeB[0],GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(listeB[1],GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(listeB[2],GPIO.IN, pull_up_down=GPIO.PUD_UP)
    if affichage == True:
        lcd.clear()
    while True:
        if affichage == True:
            lcd.cursor_pos = (0, 0)
            lcd.write_string("Boutons :      ")
            lcd.cursor_pos = (1, 0)
            lcd.write_string("1: o  2: o  3: o")
        bouton1 = GPIO.input(listeB[0])
        if bouton1 == False:
            print('Button 1 Pressed')
            if affichage == True:
                lcd.cursor_pos = (1, 3)
                lcd.write_string("X")
        bouton2 = GPIO.input(listeB[1])
        if bouton2 == False:
            print('Button 2 Pressed')
            if affichage == True:
                lcd.cursor_pos = (1, 9)
                lcd.write_string("X")
        bouton3 = GPIO.input(listeB[2])
        if bouton3 == False:
            print('Button 3 Pressed')
            if affichage == True:
                lcd.cursor_pos = (1, 15)
                lcd.write_string("X")
        time.sleep(0.2)
Beispiel #2
0
    def run(self):
        #This is so that the light works
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BOARD)
        userLightColor = 3
        if self.author in self.users:
            userLightColor = self.users[self.author]
        GPIO.setup(userLightColor, GPIO.OUT)
        GPIO.output(userLightColor, True)

        #this is the lcd stuff
        lcd = CharLCD(cols=16,
                      rows=2,
                      pin_rs=22,
                      pin_e=18,
                      pins_data=[16, 11, 12, 15],
                      numbering_mode=GPIO.BOARD)
        lcd.cursor_pos = (1, 0)
        lcd.write_string(self.author)
        for i in range(0, 2):
            currentPositionLCD = 0
            for char in self.message:
                lcd.cursor_pos = (0, currentPositionLCD)
                #increasing the cursor position
                currentPositionLCD += 1
                currentPositionLCD = currentPositionLCD % 16
                lcd.write_string(char)
                time.sleep(.1)
            time.sleep(.5)
        GPIO.output(userLightColor, False)
        lcd.clear()
Beispiel #3
0
def test_caching(mocker):
    """
    Characters should only be written if they have changed
    """
    lcd = CharLCD()
    send = mocker.patch.object(lcd, '_send')

    lcd.write_string('hello')
    assert send.call_count == 5
    calls = [c[0] for c in send.call_args_list]
    assert calls[0] == (104, RS_DATA)
    assert calls[1] == (101, RS_DATA)
    assert calls[2] == (108, RS_DATA)
    assert calls[3] == (108, RS_DATA)
    assert calls[4] == (111, RS_DATA)

    lcd.home()
    send.reset_mock()

    lcd.write_string('he77o')
    assert send.call_count == 5
    calls = [c[0] for c in send.call_args_list]
    assert calls[0] == (LCD_SETDDRAMADDR | 1, RS_INSTRUCTION)
    assert calls[1] == (LCD_SETDDRAMADDR | 2, RS_INSTRUCTION)
    assert calls[2] == (55, RS_DATA)
    assert calls[3] == (55, RS_DATA)
    assert calls[4] == (LCD_SETDDRAMADDR | 5, RS_INSTRUCTION)
Beispiel #4
0
def test_caching(mocker, charlcd_kwargs):
    """
    Characters should only be written if they have changed
    """
    lcd = CharLCD(**charlcd_kwargs)
    send_data = mocker.patch.object(lcd, '_send_data')
    send_instruction = mocker.patch.object(lcd, '_send_instruction')

    lcd.write_string('hello')
    assert send_data.call_count == 5
    data_calls = [c[0] for c in send_data.call_args_list]
    assert data_calls[0] == (104,)
    assert data_calls[1] == (101,)
    assert data_calls[2] == (108,)
    assert data_calls[3] == (108,)
    assert data_calls[4] == (111,)

    lcd.home()
    send_data.reset_mock()
    send_instruction.reset_mock()

    lcd.write_string('he77o')
    assert send_data.call_count == 2
    assert send_instruction.call_count == 3
    data_calls = [c[0] for c in send_data.call_args_list]
    instruction_calls = [c[0] for c in send_instruction.call_args_list]
    assert instruction_calls[0] == (LCD_SETDDRAMADDR | 1,)
    assert instruction_calls[1] == (LCD_SETDDRAMADDR | 2,)
    assert data_calls[0] == (55,)
    assert data_calls[1] == (55,)
    assert instruction_calls[2] == (LCD_SETDDRAMADDR | 5,)
Beispiel #5
0
class LCD:

    line1 = ""
    line2 = ""

    def __init__(self):
        self.lcd = CharLCD(pin_rs=26,
                           pin_e=19,
                           pins_data=[13, 6, 5, 11],
                           numbering_mode=GPIO.BCM)

    def writeLine1(self, text: str):
        self.line1 = text
        self._toDisplay()

    def writeLine2(self, text: str):
        self.line2 = text
        self._toDisplay()

    def _toDisplay(self):
        #self.clear()
        self.lcd.write_string(f"{self.line1}\n{self.line2}")

    def clear(self):
        self.lcd.clear()

    def close(self):
        self.lcd.close(clear=True)
    def display(self, message):
        lcd = CharLCD(pin_rs=22, pin_rw=24, pin_e=23, pins_data=[21, 16, 12, 20],
                  numbering_mode=GPIO.BCM,

        cols=16, rows=2, dotsize=8,
                  charmap='A02',
                  auto_linebreaks=True)

        lcd.write_string(message)
Beispiel #7
0
class Lcd:
    def __init__(self):
        print("Init LCD...")
        self.lcd = CharLCD(numbering_mode=GPIO.BOARD,
                           cols=16,
                           rows=2,
                           pin_rs=37,
                           pin_e=35,
                           pins_data=[33, 31, 29, 23])

    def display(self, output):
        self.lcd.clear()
        self.lcd.write_string(output)
Beispiel #8
0
def lcd_write(text):
    text = text.replace('\n', '\n\r')
    lcd = CharLCD(pin_rs=15,
                  pin_rw=16,
                  pin_e=18,
                  pins_data=[21, 22, 23, 24],
                  numbering_mode=GPIO.BOARD,
                  cols=16,
                  rows=2,
                  dotsize=8,
                  charmap='A02',
                  auto_linebreaks=True)

    lcd.clear()
    lcd.write_string(text)
Beispiel #9
0
def test_charmap(mocker, charmap, ue):
    """
    The charmap should be used. The "ü" Umlaut should be encoded correctly.
    """
    lcd = CharLCD(charmap=charmap)
    send = mocker.patch.object(lcd, '_send')

    text = 'Züri'

    lcd.write_string(text)
    assert send.call_count == 4, 'call count was %d' % send.call_count
    calls = [c[0] for c in send.call_args_list]
    assert calls[0] == (90, RS_DATA)
    assert calls[1] == (ue, RS_DATA)
    assert calls[2] == (114, RS_DATA)
    assert calls[3] == (105, RS_DATA)
Beispiel #10
0
class LcdManager:
    def __init__(self, config):
        config = config['lcd_manager']
        self.dimmer_pin = int(config['dimmer_pin'])
        GPIO.setup(self.dimmer_pin, GPIO.OUT)
        self.turn_on_backlight()

        self.lcd_width = int(config['width'])

        self.lcd = CharLCD(
            pin_rs=int(config['rs']),
            pin_e=int(config['e']),
            pins_data=[int(y) for y in config['data_pins'].split(",")],
            auto_linebreaks=True,
            numbering_mode=GPIO.BCM,
            cols=self.lcd_width)

        for foo, bar in zip(range(len(register_char)), register_char):
            self.lcd.create_char(foo, bar)

        self.lines = [
            TextLine('', self.lcd_width),
            TextLine('', self.lcd_width)
        ]

    def turn_on_backlight(self):
        GPIO.output(self.dimmer_pin, GPIO.HIGH)

    def turn_off_backlight(self):
        GPIO.output(self.dimmer_pin, GPIO.LOW)

    def close(self):
        self.turn_off_backlight()
        self.lcd.close(clear=True)

    def set_lines(self, line, line2):
        self.lines[0].set_text(line)
        self.lines[1].set_text(line2)

    def update(self):
        i = 0
        for line in self.lines:
            self.lcd.cursor_pos = (i, 0)
            self.lcd.write_string(str(line).ljust(self.lcd_width))
            i += 1
Beispiel #11
0
class Display:
    def __init__(self):
        self.lcd = CharLCD(cols=16,
                           rows=2,
                           pin_rs=16,
                           pin_e=36,
                           pins_data=[38, 32, 11, 37],
                           numbering_mode=GPIO.BOARD)

    def show_message(self, text):
        self.lcd.clear()
        self.lcd.write_string(text)

    def clear(self):
        self.lcd.clear()

    def close(self):
        self.lcd.close(clear=True)
Beispiel #12
0
def test_write_simple(mocker, charlcd_kwargs):
    """
    Write "HelloWorld" to the display.
    """
    lcd = CharLCD(**charlcd_kwargs)
    send_data = mocker.patch.object(lcd, '_send_data')
    text = 'HelloWorld'
    lcd.write_string(text)
    assert send_data.call_count == len(text)
    calls = [c[0] for c in send_data.call_args_list]
    assert calls[0] == (72,)
    assert calls[1] == (101,)
    assert calls[2] == (108,)
    assert calls[3] == (108,)
    assert calls[4] == (111,)
    assert calls[5] == (87,)
    assert calls[6] == (111,)
    assert calls[7] == (114,)
    assert calls[8] == (108,)
    assert calls[9] == (100,)
Beispiel #13
0
def test_write_simple(mocker):
    """
    Write "HelloWorld" to the display.
    """
    lcd = CharLCD()
    send = mocker.patch.object(lcd, '_send')
    text = 'HelloWorld'
    lcd.write_string(text)
    assert send.call_count == len(text)
    calls = [c[0] for c in send.call_args_list]
    assert calls[0] == (72, RS_DATA)
    assert calls[1] == (101, RS_DATA)
    assert calls[2] == (108, RS_DATA)
    assert calls[3] == (108, RS_DATA)
    assert calls[4] == (111, RS_DATA)
    assert calls[5] == (87, RS_DATA)
    assert calls[6] == (111, RS_DATA)
    assert calls[7] == (114, RS_DATA)
    assert calls[8] == (108, RS_DATA)
    assert calls[9] == (100, RS_DATA)
Beispiel #14
0
def print_lcd(temp_f: float, aqi: float, outdoor_f: float, outdoor_aqi: float) -> None:
    """
    Print to Rasperry Pi's LCD screen
    """
    from RPLCD.gpio import CharLCD
    from RPi import GPIO
    GPIO.setwarnings(False)

    lcd = CharLCD(
        cols=16,
        rows=2,
        pin_rs=37,
        pin_e=35,
        pins_data=[33, 31, 29, 23],
        numbering_mode=GPIO.BOARD,
        compat_mode=True,
    )
    aqi_str = f" AQI: {aqi} / {round(outdoor_aqi, 1)}"
    temp_str = f"\r\nTemp: {temp_f} / {round(outdoor_f, 1)}"
    lcd.write_string(aqi_str)
    lcd.write_string(temp_str)
Beispiel #15
0
class LCD:
    def __init__(self):
        self.lcd = CharLCD(pin_rs=16,
                           pin_rw=None,
                           pin_e=20,
                           pins_data=[26, 19, 13, 6],
                           numbering_mode=GPIO.BCM,
                           rows=2,
                           cols=16)
        #self.lcd.write_string(u"Hello")
        #self.lcd = CharLCD (pin_rs=36, pin_rw=None, pin_e=38, pins_data=[31, 33, 35, 37], numbering_mode=GPIO.BOARD, rows=2, cols=16)
        self.lcd.cursor_mode = "hide"

    def clearScreen(self):
        self.lcd.clear()

    def printOut(self, string):
        self.lcd.write_string(u"" + string)

    def println(self, string):
        self.lcd.write_string(u"\r\n" + string)
Beispiel #16
0
def test_write_newline(mocker, rows, cols):
    """
    Write text containing CR/LF chars to the display.
    """
    lcd = CharLCD(rows=rows, cols=cols)
    send = mocker.patch.object(lcd, '_send')
    text = '\nab\n\rcd'
    lcd.write_string(text)
    assert send.call_count == len(text)
    calls = [c[0] for c in send.call_args_list]
    assert calls[0] == (0x80 + 0x40, RS_INSTRUCTION), calls
    assert calls[1] == (97, RS_DATA), calls
    assert calls[2] == (98, RS_DATA), calls
    if rows == 2:
        assert calls[3] == (0x80 + 2, RS_INSTRUCTION), calls
        assert calls[4] == (0x80 + 0, RS_INSTRUCTION), calls
    else:
        assert calls[3] == (0x80 + cols + 2, RS_INSTRUCTION), calls
        assert calls[4] == (0x80 + cols + 0, RS_INSTRUCTION), calls
    assert calls[5] == (99, RS_DATA), calls
    assert calls[6] == (100, RS_DATA), calls
Beispiel #17
0
def test_lcd():
    lcd = CharLCD(cols=16,
                  rows=2,
                  pin_rs=37,
                  pin_e=35,
                  pins_data=[40, 38, 36, 32, 33, 31, 29, 23],
                  numbering_mode=GPIO.BOARD)
    #GPIO.setmode(GPIO.BOARD)
    lcd.clear()
    status = ["NO", "NO", "NO"]
    with open("indication.txt", "r") as fd:
        lines = fd.readlines()
    for i in range(3):
        if ("False" in lines[i]):
            status[i] = "NO"
        else:
            status[i] = "YES"

    lcd.write_string("Inet:" + status[0] + "\n")
    lcd.cursor_pos = (1, 0)
    lcd.write_string("Cam:" + status[1] + "\n")
    lcd.cursor_pos = (1, 8)
    lcd.write_string("Mav:" + status[2] + "\n")
    fd.close()
    GPIO.cleanup()
Beispiel #18
0
class Display():
    def __init__(self):
        # Configure the LCD
        self.lcd = CharLCD(pin_rs=38,
                           pin_rw=None,
                           pin_e=40,
                           pins_data=[36, 18, 16, 12],
                           numbering_mode=GPIO.BOARD,
                           auto_linebreaks=False,
                           cols=COLS,
                           rows=ROWS)

    def print(self, string):
        if len(string) > COLS * ROWS:
            print('WARNING: String \'{}\' too big and overflows the display.'.
                  format(string))

        self.lcd.clear()
        self.lcd.write_string(string)

    def __del__(self):
        self.lcd.close()
Beispiel #19
0
class Wrapper:
    lcd = 1
    text = 'Initializing'
    oldtext = text
    shutDownLCD = False

    def __init__(self):
        self.activate()
        workerThread = threading.Thread(target=self.updateScreenWorker,
                                        args=(),
                                        daemon=True)
        workerThread.start()

    def activate(self):
        # Initialize LCD
        self.lcd = CharLCD(pin_rs=16,
                           pin_e=18,
                           pins_data=[11, 12, 13, 15],
                           numbering_mode=GPIO.BOARD,
                           cols=20,
                           rows=4,
                           dotsize=8,
                           charmap='A02',
                           auto_linebreaks=True,
                           pin_backlight=22)

        self.lcd.clear()

        GPIO.output(22, GPIO.HIGH)  #turn on LCD backlight

    # Main loop
    def updateScreenWorker(self):
        self.text = "\nReady."
        while not self.shutDownLCD:
            if self.text != self.oldtext:
                self.lcd.clear()
                self.lcd.home()
                self.lcd.write_string(self.text)
                self.oldtext = self.text

            time.sleep(1)

        self.cleanShutdown()

    # If clean shut down is requested, shut down cleanly, and display optional message.
    def cleanShutdown(self, closeMessage=''):
        print('\nshutting down LCD')
        if GPIO.getmode() != None:  # If screen can be accessed
            self.lcd.clear()
            self.lcd.home()
            self.lcd.write_string(closeMessage)
            self.lcd.close(clear=False)
        else:  # If screen can not be accessed, activate
            self.activate()
            self.lcd.clear()
            self.lcd.home()
            self.lcd.write_string(closeMessage)
            self.lcd.close(clear=False)
        print('complete')
class Display:
    def __init__(self):
        self.lcd = CharLCD(pin_rs=15,
                           pin_rw=18,
                           pin_e=16,
                           pins_data=[21, 22, 23, 24],
                           numbering_mode=GPIO.BOARD)
        self._create_chars()

    def update_display(self,
                       count,
                       interval,
                       counter=0,
                       camera_connected=False):
        self.lcd.cursor_pos = (0, 0)
        self.lcd.write_string("Interval:")
        self.lcd.cursor_pos = (0, 9)
        self.lcd.write_string(str(interval) + " ")
        if not counter == 0:
            self.lcd.cursor_pos = (0, 13)
            self.lcd.write_string(str(counter)[:3] + " ")
        self.lcd.cursor_pos = (1, 0)
        self.lcd.write_string("Shots:" + str(count) + " ")
        if camera_connected:  # displays camera icon if camera connected
            self.lcd.cursor_pos = (1, 13)
            self.lcd.write_string("\x00\x01\x02")

    def _create_chars(self):
        # camera icon
        bitmap0 = (0b00000, 0b00000, 0b00011, 0b00011, 0b00011, 0b00011,
                   0b00011, 0b00011)
        bitmap1 = (0b01110, 0b11111, 0b11011, 0b10001, 0b00000, 0b10001,
                   0b11011, 0b11111)
        bitmap2 = (0b00000, 0b00000, 0b11000, 0b01000, 0b11000, 0b11000,
                   0b11000, 0b11000)
        self.lcd.create_char(0, bitmap0)
        self.lcd.create_char(1, bitmap1)
        self.lcd.create_char(2, bitmap2)
Beispiel #21
0
def test_write_newline(mocker, rows, cols, charlcd_kwargs):
    """
    Write text containing CR/LF chars to the display.
    """
    lcd = CharLCD(rows=rows, cols=cols, **charlcd_kwargs)
    send_data = mocker.patch.object(lcd, '_send_data')
    send_instruction = mocker.patch.object(lcd, '_send_instruction')
    text = '\nab\n\rcd'
    lcd.write_string(text)
    assert send_data.call_count + send_instruction.call_count == len(text)
    data_calls = [c[0] for c in send_data.call_args_list]
    instruction_calls = [c[0] for c in send_instruction.call_args_list]
    assert instruction_calls[0] == (0x80 + 0x40,), instruction_calls
    assert data_calls[0] == (97,), data_calls
    assert data_calls[1] == (98,), data_calls
    if rows == 2:
        assert instruction_calls[1] == (0x80 + 2,), instruction_calls
        assert instruction_calls[2] == (0x80 + 0,), instruction_calls
    else:
        assert instruction_calls[1] == (0x80 + cols + 2,), instruction_calls
        assert instruction_calls[2] == (0x80 + cols + 0,), instruction_calls
    assert data_calls[2] == (99,), data_calls
    assert data_calls[3] == (100,), data_calls
class CommonHardwarePIHD44780GPIO(object):
    """
    Class for interfacing with pi lcd HD44780
    """

    def __init__(self):
        self.lcd_inst = CharLCDGPIO(pin_rs=15, pin_rw=18, pin_e=16,
                                    pins_data=[21, 22, 23, 24],
                                    numbering_mode=GPIO.BOARD,
                                    cols=20, rows=4, dotsize=8,
                                    charmap='A02',
                                    auto_linebreaks=True)

    def com_hard_pi_hd44780_write(self, lcd_string, x_pos=None, y_pos=None):
        if x_pos is not None:
            self.lcd_inst.cursor_pos = (x_pos, y_pos)
        self.lcd_inst.write_string(lcd_string)

    def com_hard_pi_hd44780_clear(self):
        self.lcd_inst.clear()

    def com_hard_pi_hd44780_close(self, clear_screen=True):
        self.lcd_inst.close(clear=clear_screen)
Beispiel #23
0
class Wrapper:
    i = 0
    lcd = 1
    text = 'Initializing'
    oldtext = text
    shutDownLCD = False

    def __init__(self):
        self.activate()
        workerThread = threading.Thread(target=self.updateScreenWorker,
                                        args=(),
                                        daemon=True)
        workerThread.start()

    def activate(self):
        self.lcd = CharLCD(pin_rs=16,
                           pin_e=18,
                           pins_data=[11, 12, 13, 15],
                           numbering_mode=GPIO.BOARD,
                           cols=20,
                           rows=4,
                           dotsize=8,
                           charmap='A02',
                           auto_linebreaks=True,
                           pin_backlight=22)
        self.lcd.clear()
        GPIO.output(22, GPIO.HIGH)  #turns on backlight

    def updateScreenWorker(self):
        self.text = "Ready."
        while not self.shutDownLCD:
            #print("Text = " + self.text + "    Oldtext = " + self.oldtext)
            if self.text != self.oldtext:
                self.lcd.clear()
                self.lcd.home()
                self.lcd.write_string(self.text)
                self.i = self.i + 1
                self.oldtext = self.text

            time.sleep(1)

        self.cleanShutdown()

    def cleanShutdown(self, closeMessage=''):
        print('\nshutting down LCD')
        if GPIO.getmode() != None:
            self.lcd.clear()
            self.lcd.home()
            self.lcd.write_string(closeMessage)
            self.lcd.close(clear=False)
        else:
            self.activate()
            self.lcd.clear()
            self.lcd.home()
            self.lcd.write_string(closeMessage)
            self.lcd.close(clear=False)
        print('complete')
Beispiel #24
0
              dotsize=8,
              pin_rs=26,
              pin_e=24,
              pins_data=[22, 18, 16, 12],
              numbering_mode=GPIO.BOARD)
lcd.clear()

GPIO.setup(selectBtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(incBtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(decBtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

startUp()

while inSetUp:
    time.sleep(1)

lcd.clear()
lcd.write_string("Welcome to")
lcd.crlf()
lcd.write_string("Planet Finder")
time.sleep(2)

lcd.clear()
lcd.write_string("Select a planet")
lcd.crlf()
lcd.write_string("Mercury")
time.sleep(2)

while True:
    time.sleep(1)
Beispiel #25
0
    55: '>',
    56: '?'
}
fp = open('/dev/hidraw0', 'rb')
rfid_number = ""
shift = False
done = False

### Begin run loop
while True:
    ### Wait for RFID
    while not done:  ## Get the character from the HID
        lcd.clear()  ## Clear the LCD before writing
        blue_backlight.on()  ## Turn on the blue backlight
        lcd.cursor_pos = (0, 3)  ## Set cursor pos on first line
        lcd.write_string('Swipe Badge')

        buffer = fp.read(8)
        for c in buffer:
            if ord(
                    c
            ) > 0:  ##  40 is carriage return which signifies we are done looking for characters
                if int(ord(c)) == 40:
                    done = True
                    break
                    ##  If we are shifted then we have to  use the hid2 characters.
                if shift:  ## If it is a '2' then it is the shift key
                    if int(ord(c)) == 2:
                        shift = True
                    else:  # if not a 2, lookup mapping
                        rfid_number += hid2[int(ord(c))]
Beispiel #26
0
        substr_c = get_line("Folsom: ", 'folsom_c.txt', " C")
        substr_hf = get_line("Today:  ", 'folsom_hf.txt', " F")
        substr_hc = get_line("Today:  ", 'folsom_hc.txt', " C")

        fp = open('folsom_desc.txt', 'r')
        line = fp.readline()
        fp.close()
        line = line[:-1]
        line.ljust(15)[:15]
        substr_desc = (line + 15 * " ")[:15]
        print(substr_desc)

    counter = counter + 1
    x = datetime.datetime.now()
    lcd.cursor_pos = (0, 0)
    lcd.write_string(x.strftime("%d %b  %H:%M:%S"))
    lcd.cursor_pos = (1, 0)

    len = 11
    if ((counter % len) < 2):
        lcd.write_string(substr_c)
    elif ((counter % len) <= 4):
        lcd.write_string(substr_f)
    elif ((counter % len) <= 6):
        lcd.write_string(substr_hc)
    elif ((counter % len) <= 8):
        lcd.write_string(substr_hf)
    elif ((counter % len) <= 10):
        lcd.write_string(substr_desc)

#    else:
Beispiel #27
0
import RPi.GPIO as GPIO
from RPLCD.gpio import CharLCD
from time import sleep

# When numbering_mode is set to BOARD, reference PIN number.
# When numbering_mode is set to BCM, reference the number after GP in the pinout name.
lcd = CharLCD(pin_rs=15, pin_rw=18, pin_e=16, pins_data=[8, 10, 11, 12], numbering_mode=GPIO.BOARD, cols=20, rows=4, dotsize=8)

# Clear the screen of any previous input
lcd.clear()
sleep(2)

counter = 0

lcd.cursor_pos = (0, 0)
lcd.write_string(str('It works!'))

while(True):
    # Set the cursor to the second row, 0th column
    lcd.cursor_pos = (1, 0)

    # Timer print string builder
    secondRow = ('UpTime %s m %s s' % (counter/60, counter%60))

    # Add spaces at the end to force out 'hanging' characters
    # This is a symptom of the LCD screen and printed character 'hanging' in memory.
    # If you don't overwrite EVERY character space on a row, anything extending past
    # the last char of the new row will remain.
    while(20 > len(secondRow)):
            secondRow = secondRow + u' '
Beispiel #28
0
from RPLCD.gpio import CharLCD
from RPi import GPIO

lcd = CharLCD(numbering_mode=GPIO.BOARD,
              cols=16,
              rows=2,
              pin_rs=37,
              pin_e=35,
              pins_data=[40, 38, 36, 32, 33, 31, 29, 23])
lcd.write_string(u'Hello world!2')
Beispiel #29
0
class Ticker:
    def __init__(self, lcd_rs, lcd_e, lcd_data, buzzer_pin, red_led_pin,
                 yellow_led_pin, green_led_pin, button_pins, fm_username: str,
                 fm_key: str, spot_client: str, spot_secret: str,
                 spot_refresh: str):
        self.lcd = CharLCD(numbering_mode=GPIO.BCM,
                           cols=lcd_width,
                           rows=2,
                           pin_rs=lcd_rs,
                           pin_e=lcd_e,
                           pins_data=lcd_data,
                           auto_linebreaks=True)
        self.lcd.cursor_mode = 'hide'
        self.leds = TrafficLights(red=red_led_pin,
                                  yellow=yellow_led_pin,
                                  green=green_led_pin,
                                  pwm=True)

        self.buzzer = TonalBuzzer(buzzer_pin)
        self.buzzer_lock = Lock()

        self.notif_button = Button(button_pins[0])
        self.notif_button.when_activated = self.handle_notif_click

        self.button2 = Button(button_pins[1])
        self.button2.when_activated = lambda: self.queue_text('hey', 'hey')

        self.button3 = Button(button_pins[2])
        self.button4 = Button(button_pins[3])
        self.button4.when_held = self.handle_network_hold

        self.location = DisplayLocation.home

        self.pulled_idle_text = dict()

        self.notification_queue = Queue()
        self.display_queue = Queue()
        self.display_thread = Thread(target=self.display_worker,
                                     name='display',
                                     daemon=True)

        self.network_active = True

        self.rsession = Session()
        self.fmnet = FMNetwork(username=fm_username, api_key=fm_key)
        self.spotnet = SpotNetwork(
            NetworkUser(client_id=spot_client,
                        client_secret=spot_secret,
                        refresh_token=spot_refresh)).refresh_access_token()

        self.network_pull_thread = Thread(target=self.network_pull_worker,
                                          name='puller',
                                          daemon=True)

    def start(self):
        logger.info('starting ticker')

        self.lcd.clear()
        self.display_thread.start()
        self.network_pull_thread.start()
        self.set_status(green=True)

    def set_status(self, green: bool = False, yellow: bool = False):
        self.leds.green.value = 1 if green else 0
        self.leds.yellow.value = 1 if yellow else 0

    # HANDLERS

    def handle_notif_click(self):
        if not self.notification_queue.empty():
            while not self.notification_queue.empty():
                self.display_queue.put(self.notification_queue.get())
            self.leds.red.off()
        else:
            self.queue_text('No Notifications', '', interrupt=True, time=1)

    def handle_network_hold(self):
        self.network_active = not self.network_active

        logger.info(f'setting network activity {self.network_active}')

        if self.network_active:
            self.set_status(green=True)
        else:
            self.set_status(yellow=True)

        self.beep()

    # THREADS

    def network_pull_worker(self):
        """thread function for pulling network display items and update cache"""
        while True:
            if self.network_active:
                try:
                    total = self.fmnet.get_scrobble_count_from_date(
                        input_date=date.today())
                    logger.debug(f'loaded daily scrobbles {total}')

                    # self.queue_text('Scrobbles Today', total)
                    self.pulled_idle_text['daily_scrobbles'] = DisplayItem(
                        'Scrobbles Today', str(total))
                except LastFMNetworkException as e:
                    logger.exception(e)
                    self.queue_text(
                        'Last.FM Error',
                        f'{e.http_code}, {e.error_code}, {e.message}')

                try:
                    artists = self.fmnet.get_top_artists(
                        period=FMNetwork.Range.WEEK, limit=3)
                    logger.debug(f'loaded top artists')

                    self.pulled_idle_text['weekly_artists'] = DisplayItem(
                        'Weekly Artists',
                        ', '.join([str(i) for i in artists]),
                        iterations=1)
                except LastFMNetworkException as e:
                    logger.exception(e)
                    self.queue_text(
                        'Last.FM Error',
                        f'{e.http_code}, {e.error_code}, {e.message}')

                # try:
                #     from_time = date.today()
                #     from_time = datetime(year=from_time.year, month=from_time.month, day=1)
                #
                #     to_time = datetime.now()
                #
                #     total = len(self.fmnet.get_recent_tracks(from_time=from_time, to_time=to_time, page_limit=200))
                #     logger.debug(f'loaded monthly scrobbles {total}')
                #
                #     # self.queue_text('Scrobbles Today', total)
                #     self.pulled_idle_text['monthly_scrobbles'] = DisplayItem('This Month', str(total))
                # except LastFMNetworkException as e:
                #     logger.exception(e)
                #     self.queue_text('Last.FM Error', f'{e.http_code}, {e.error_code}, {e.message}')

                try:
                    playlist_total = len(self.spotnet.get_user_playlists())
                    logger.debug(f'loaded daily scrobbles {playlist_total}')

                    self.pulled_idle_text['playlist_count'] = DisplayItem(
                        'Playlists', str(playlist_total))
                except SpotifyNetworkException as e:
                    logger.exception(e)
                    self.queue_text('Spotify Error',
                                    f'{e.http_code}, {e.message}')

            sleep(net_thread_interval)

    def display_worker(self):
        """LCD controller, reads queue for new items to display or roll over idle items"""
        while True:
            if not self.display_queue.empty():
                display_item = self.display_queue.get(block=False)
                logger.info(
                    f'dequeued {display_item}, size {self.display_queue.qsize()}'
                )

                self.write_display_item(display_item)
                self.display_queue.task_done()

            else:
                if len(self.idle_text
                       ) > 0 and self.location == DisplayLocation.home:
                    for key, item in self.idle_text.items():
                        if not self.display_queue.empty():
                            break

                        logger.debug(f'writing {key}')
                        self.write_display_item(item)
                else:
                    self.write_to_lcd(['Ticker...', ''])
            sleep(display_thread_interval)

    # DISPLAY

    def write_display_item(self, display_item):
        """write display item to LCD now"""
        if display_item.message is None:
            display_item.message = ''

        if len(display_item.message) > lcd_width:
            buffer = [display_item.title, '']
            self.write_to_lcd(buffer)
            self.loop_string(display_item.message,
                             buffer,
                             row=1,
                             iterations=display_item.iterations)
        else:
            buffer = [display_item.title, display_item.message]
            self.write_to_lcd(buffer)
            sleep(display_item.time)

    def queue_notification(self,
                           title,
                           message,
                           wrap_line=False,
                           iterations=2):
        logger.debug(
            f'queueing {title}/{message} {iterations} times, wrapped: {wrap_line}'
        )
        self.notification_queue.put(
            DisplayItem(title, str(message), wrap_line, iterations))
        self.leds.red.pulse()

    def queue_text(self,
                   title,
                   message,
                   wrap_line=False,
                   time=5,
                   iterations=2,
                   interrupt=False):
        logger.debug(
            f'queueing {title}/{message} {iterations} times, wrapped: {wrap_line}'
        )

        item = DisplayItem(title,
                           str(message),
                           wrap_line=wrap_line,
                           iterations=iterations,
                           time=time)
        if interrupt:
            self.write_display_item(item)
        else:
            self.display_queue.put(item)

    def write_to_lcd(self, framebuffer):
        """Write the framebuffer out to the specified LCD."""
        self.lcd.home()
        for row in framebuffer:
            self.lcd.write_string(row.ljust(lcd_width)[:lcd_width])
            self.lcd.write_string('\r\n')

    def loop_string(self, string, framebuffer, row, delay=0.4, iterations=2):
        padding = ' ' * lcd_width
        s = padding + string + padding
        for round_trip in range(iterations):
            for i in range(len(s) - lcd_width + 1):
                framebuffer[row] = s[i:i + lcd_width]
                self.write_to_lcd(framebuffer)
                sleep(delay)

    @property
    def idle_text(self) -> dict:
        """merge last pulled with system pullable text items"""
        system_idle = dict()

        now = datetime.now()
        system_idle['date'] = DisplayItem(title=now.strftime('%d.%m.%y'),
                                          message=now.strftime('%R'))

        return {**system_idle, **self.pulled_idle_text}

    # SOUND

    def beep(self):
        self.buzzer_lock.acquire()

        self.buzzer.play(Tone("A4"))
        sleep(0.1)
        self.buzzer.stop()
        sleep(0.1)

        self.buzzer_lock.release()
import RPLCD as RPLCD
from RPLCD.gpio import CharLCD
import RPi.GPIO as GPIO
import time

GPIO.setwarnings(False)

lcd = CharLCD(numbering_mode=GPIO.BOARD,
              cols=16,
              rows=2,
              pin_rs=37,
              pin_e=35,
              pins_data=[33, 31, 29, 26])
lcd.clear()
lcd.write_string(u'Test')
time.sleep(3)

GPIO.cleanup()
import RPi.GPIO as GPIO
from RPLCD.gpio import CharLCD
GPIO.setwarnings(False)
lcd = CharLCD(cols=16,
              rows=2,
              pin_rs=37,
              pin_e=35,
              pins_data=[33, 31, 29, 23],
              numbering_mode=GPIO.BOARD)
heart = [
    0b00000, 0b01010, 0b11111, 0b11111, 0b11111, 0b01110, 0b00100, 0b00000
]
lcd.cursor_pos = (0, 6)
lcd.write_string(u'I ')
lcd.create_char(0, heart)
lcd.write_string(unichr(0))
lcd.cursor_pos = (1, 2)
lcd.write_string(u'Raspberry Pi')