示例#1
0
def test_display():
    device = st7735(serial, gpio=Mock(), framebuffer=full_frame())
    serial.reset_mock()

    recordings = []

    def data(data):
        recordings.append({'data': data})

    def command(*cmd):
        recordings.append({'command': list(cmd)})

    serial.command.side_effect = command
    serial.data.side_effect = data

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    assert serial.data.called
    assert serial.command.called

    # To regenerate test data, uncomment the following (remember not to commit though)
    # ================================================================================
    # from baseline_data import save_reference_data
    # save_reference_data("demo_st7735", recordings)

    assert recordings == get_reference_data('demo_st7735')
示例#2
0
def test_display():
    device = st7735(serial, gpio=Mock())
    serial.reset_mock()

    recordings = []

    def data(data):
        recordings.append({'data': data})

    def command(*cmd):
        recordings.append({'command': list(cmd)})

    serial.command.side_effect = command
    serial.data.side_effect = data

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    assert serial.data.called
    assert serial.command.called

    assert recordings == [{
        'command': [42]
    }, {
        'data': [0, 0, 0, 159]
    }, {
        'command': [43]
    }, {
        'data': [0, 0, 0, 127]
    }, {
        'command': [44]
    }, {
        'data': get_reference_data('demo_st7735')
    }]
示例#3
0
 def init_display(self, autoscroll=False, **kwargs):
     self.device = st7735(self.serial,
                          width=128,
                          height=128,
                          bgr=True,
                          h_offset=1,
                          v_offset=2)
示例#4
0
 def init_display(self, **kwargs):
     self.rotate = kwargs.pop("rotate", self.default_rotate)
     self.h_offset = kwargs.pop("h_offset", self.default_h_offset)
     self.v_offset = kwargs.pop("v_offset", self.default_v_offset)
     width = self.height if self.rotate%2==1 else self.width
     height = self.width if self.rotate%2==1 else self.height
     gpio = kwargs.pop("gpio", None)
     self.device = st7735(self.serial, width=width, height=height, bgr=True, rotate=self.rotate, h_offset=self.h_offset, v_offset=self.v_offset, gpio=gpio)
示例#5
0
def test_init_128x128():
    recordings = []

    def data(data):
        recordings.append({'data': data})

    def command(*cmd):
        recordings.append({'command': list(cmd)})

    serial.command.side_effect = command
    serial.data.side_effect = data

    st7735(serial, gpio=Mock(), width=128, height=128)

    assert serial.data.called
    assert serial.command.called

    assert recordings == [
        {'command': [1]},
        {'command': [17]},
        {'command': [177]}, {'data': [1, 44, 45]},
        {'command': [178]}, {'data': [1, 44, 45]},
        {'command': [179]}, {'data': [1, 44, 45, 1, 44, 45]},
        {'command': [180]}, {'data': [7]},
        {'command': [192]}, {'data': [162, 2, 132]},
        {'command': [193]}, {'data': [197]},
        {'command': [194]}, {'data': [10, 0]},
        {'command': [195]}, {'data': [138, 42]},
        {'command': [196]}, {'data': [138, 238]},
        {'command': [197]}, {'data': [14]},
        {'command': [54]}, {'data': [96]},
        {'command': [32]},
        {'command': [58]}, {'data': [6]},
        {'command': [19]},
        {'command': [224]}, {'data': [15, 26, 15, 24, 47, 40, 32, 34, 31, 27, 35, 55, 0, 7, 2, 16]},
        {'command': [225]}, {'data': [15, 27, 15, 23, 51, 44, 41, 46, 48, 48, 57, 63, 0, 7, 3, 16]},
        {'command': [42]}, {'data': [0, 0, 0, 127]},
        {'command': [43]}, {'data': [0, 0, 0, 127]},
        {'command': [44]}, {'data': [0] * (128 * 128 * 3)},
        {'command': [41]}
    ]
示例#6
0
import time
import CHIP_IO.GPIO
import os.path
import pyscreenshot as ImageGrab
from PIL import Image
from luma.core.interface.serial import spi
from luma.core.render import canvas
from luma.lcd.device import pcd8544, st7735, uc1701x

img_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'PAL.png'))
serial = spi(port=32766,
             device=0,
             gpio=CHIP_IO.GPIO,
             gpio_DC="CSID1",
             gpio_RST="CSID0")
device = st7735(serial)
'''
with canvas(device) as draw:
    draw.rectangle(device.bounding_box, outline="white", fill="black")
    draw.text((30, 40), "Hello World", fill="red")
time.sleep(1)
'''

logo = Image.open(img_path).convert("RGBA").resize(device.size)
#img = Image.new(logo.mode, logo.size, (255,) * 4)

background = Image.new("RGBA", device.size, "black")
posn = ((device.width - logo.width) // 2, 0)
background.paste(logo, posn)
device.display(background.convert(device.mode))
time.sleep(5)
示例#7
0
def main(argv):

    # Check and get arguments
    try:
        options, remainder = getopt.getopt(argv, '', [
            'help', 'interface=', 'i2c-port=', 'i2c-address=', 'display=',
            'display-width=', 'display-height='
        ])
    except getopt.GetoptError:
        l.usage()
        sys.exit(2)
    for opt, arg in options:
        if opt == '--help':
            l.usage()
            sys.exit()
        elif opt in ('--interface'):
            if arg not in ['i2c', 'spi']:
                print 'Unknown interface type (choose between \'i2c\' and \'spi\')'
                sys.exit()
            s.interface = arg
        elif opt in ('--i2c-port'):
            s.i2c_port = int(arg)
        elif opt in ('--i2c-address'):
            s.i2c_address = int(arg, 16)
        elif opt in ('--display'):
            if arg not in [
                    'sh1106', 'ssd1306', 'ssd1327', 'ssd1351', 'st7735'
            ]:
                print 'Unknown display type (choose between \'sh1106\', \'ssd1306\',  \'ssd1327\', \'ssd1351\' and \'st7735\')'
                sys.exit()
            s.display = arg
        elif opt in ('--display-width'):
            s.display_width = int(arg)
        elif opt in ('--display-height'):
            s.display_height = int(arg)

    # Set serial
    if s.interface == 'i2c':
        serial = i2c(port=s.i2c_port, address=s.i2c_address)
        if s.display == 'sh1106':
            s.device = sh1106(serial,
                              width=s.display_width,
                              height=s.display_height,
                              rotate=0)
        elif s.display == 'ssd1306':
            s.device = ssd1306(serial,
                               width=s.display_width,
                               height=s.display_height,
                               rotate=0)
        elif s.display == 'ssd1327':
            s.device = ssd1327(serial,
                               width=s.display_width,
                               height=s.display_height,
                               rotate=0,
                               mode='RGB')
    else:
        serial = spi(device=0, port=0)
        if s.display == 'ssd1351':
            s.device = ssd1351(serial,
                               width=s.display_width,
                               height=s.display_height,
                               rotate=1,
                               mode='RGB',
                               bgr=True)
        elif s.display == 'st7735':
            s.device = st7735(serial,
                              width=s.display_width,
                              height=s.display_height,
                              rotate=3,
                              mode='RGB')

    while True:
        print 'Start'
        l.scroll_message("Il etait une fois tout petit chaton.")
        print 'Stop'
示例#8
0
def test_show():
    device = st7735(serial, gpio=Mock())
    serial.reset_mock()
    device.show()
    serial.command.assert_called_once_with(41)
示例#9
0
def test_contrast():
    device = st7735(serial, gpio=Mock())
    serial.reset_mock()
    with pytest.raises(AssertionError):
        device.contrast(300)
示例#10
0
# First define some constants to allow easy resizing of shapes.
padding = 0
top = padding
bottom = height - padding

# Move left to right keeping track of the current x position for drawing shapes.
x = 0

serial = spi(device=0,
             port=0,
             bus_speed_hz=8000000,
             transfer_size=4096,
             gpio_DC=25,
             gpio_RST=27)

device = st7735(serial)

device = st7735(serial,
                width=128,
                height=128,
                h_offset=1,
                v_offset=2,
                bgr=True,
                persist=False)

try:
    redis_db = redis.StrictRedis(host="localhost",
                                 port=6379,
                                 db=0,
                                 charset="utf-8",
                                 decode_responses=True)
示例#11
0
def main(argv):

    # Check and get arguments
    try:
        options, remainder = getopt.getopt(argv, '', ['help', 'interface=', 'i2c-port=', 'i2c-address=', 'display=', 'display-width=', 'display-height=', 'display-theme=', 'follow=', 'refresh=', 'latitude=', 'longitude='])
    except getopt.GetoptError:
        l.usage()
        sys.exit(2)
    for opt, arg in options:
        if opt == '--help':
            l.usage()
            sys.exit()
        elif opt in ('--interface'):
            if arg not in ['i2c', 'spi']:
                print('Unknown interface type (choose between \'i2c\' and \'spi\')')
                sys.exit()
            s.interface = arg
        elif opt in ('--i2c-port'):
            s.i2c_port = int(arg)
        elif opt in ('--i2c-address'):
            s.i2c_address = int(arg, 16)
        elif opt in ('--display'):
            if arg not in ['sh1106', 'ssd1306', 'ssd1327', 'ssd1351', 'st7735']:
                print('Unknown display type (choose between \'sh1106\', \'ssd1306\',  \'ssd1327\', \'ssd1351\' and \'st7735\')')
                sys.exit()
            s.display = arg
        elif opt in ('--display-width'):
            s.display_width = int(arg)
        elif opt in ('--display-height'):
            s.display_height = int(arg)
        elif opt in ('--follow'):
            if arg in ['RRF', 'TECHNIQUE', 'INTERNATIONAL', 'LOCAL', 'BAVARDAGE', 'FON']:
                s.room_current = arg
            else:
                tmp = l.scan(arg)
                if tmp is False:
                    s.room_current = 'RRF'
                else:
                    s.room_current = tmp
                    s.callsign = arg
                    s.scan = True
        elif opt in ('--refresh'):
            s.refresh = float(arg)
        elif opt in ('--latitude'):
            s.latitude = float(arg)
        elif opt in ('--longitude'):
            s.longitude = float(arg)
        elif opt in ('--display-theme'):
            s.display_theme = arg

    # Set serial
    if s.interface == 'i2c':
        serial = i2c(port=s.i2c_port, address=s.i2c_address)
        if s.display == 'sh1106':
            s.device = sh1106(serial, width=s.display_width, height=s.display_height, rotate=0)
        elif s.display == 'ssd1306':
            s.device = ssd1306(serial, width=s.display_width, height=s.display_height, rotate=0)
        elif s.display == 'ssd1327':
            s.device = ssd1327(serial, width=s.display_width, height=s.display_height, rotate=0, mode='RGB')
    else:
        serial = spi(device=0, port=0)
        if s.display == 'ssd1351':        
            s.device = ssd1351(serial, width=s.display_width, height=s.display_height, rotate=1, mode='RGB', bgr=True)
        elif s.display == 'st7735':
            s.device = st7735(serial, width=s.display_width, height=s.display_height, rotate=3, mode='RGB')

    init_message = []

    # Let's go
    init_message.append('RRFDisplay ' + s.version)
    init_message.append('')
    init_message.append('88 et 73 de F4HWN')
    init_message.append('')
    d.display_init(init_message)

    # Lecture du fichier de theme
    init_message.append('Chargement Theme')
    d.display_init(init_message)
    s.theme = cp.ConfigParser()
    s.theme.read('./themes/' + s.display_theme)

    # Lecture initiale de la progation et du cluster
    init_message.append('Requete Propagation')
    d.display_init(init_message)
    l.get_solar()

    init_message.append('Requete Cluster')
    d.display_init(init_message)
    l.get_cluster()

    init_message.append('Let\'s go')
    d.display_init(init_message)

    # Boucle principale
    s.timestamp_start = time.time()

    rrf_data = ''
    rrf_data_old = ''

    #print s.scan
    #print s.callsign
    #print s.room_current

    while(True):
        chrono_start = time.time()

        tmp = datetime.datetime.now()
        s.day = tmp.strftime('%Y-%m-%d')
        s.now = tmp.strftime('%H:%M:%S')
        s.hour = int(tmp.strftime('%H'))
        s.minute = int(s.now[3:-3])
        s.seconde = int(s.now[-2:])

        if s.seconde % 15 == 0 and s.scan == True: # On scan
            tmp = l.scan(s.callsign)
            if tmp is not False:
                #print s.now, tmp
                s.room_current = tmp

        if s.minute == 0: # Update solar propagation
            l.get_solar()

        if s.minute % 4 == 0: # Update cluster
            l.get_cluster()

        url = s.room[s.room_current]['url']

        # Requete HTTP vers le flux json du salon produit par le RRFDisplay 
        try:
            r = requests.get(url, verify=False, timeout=0.5)
        except requests.exceptions.ConnectionError as errc:
            #print ('Error Connecting:', errc)
            pass
        except requests.exceptions.Timeout as errt:
            #print ('Timeout Error:', errt)
            pass

        # Controle de la validité du flux json
        try:
            rrf_data = r.json()
        except:
            pass

        if rrf_data != '' and rrf_data != rrf_data_old: # Si le flux est valide
            rrf_data_old = rrf_data
            data_abstract = rrf_data['abstract'][0]
            data_activity = rrf_data['activity']
            data_transmit = rrf_data['transmit'][0]
            data_last = rrf_data['last']
            data_all = rrf_data['all']

            s.message[1] = l.sanitize_call(data_last[0]['Indicatif'])
            s.message[2] = l.sanitize_call(data_last[1]['Indicatif'])
            s.message[3] = l.sanitize_call(data_last[2]['Indicatif'])

            if s.device.height == 128:      # Only if place...
                try:
                    data_elsewhere = rrf_data['elsewhere'][0]

                    i = 0
                    s.transmit_elsewhere = False
                    for data in rrf_data['elsewhere'][6]:
                        if data in ['RRF', 'TECHNIQUE', 'INTERNATIONAL', 'LOCAL', 'BAVARDAGE', 'FON']:
                            tmp = rrf_data['elsewhere'][6][data]
                            if tmp != 0:
                                s.transmit_elsewhere = True
                                s.raptor[i] = l.convert_second_to_time(tmp) + '/' + data[:3] + '/' + l.sanitize_call(rrf_data['elsewhere'][1][data]) + '/' + str(rrf_data['elsewhere'][5][data])
                            else:
                                s.raptor[i] = l.convert_second_to_time(tmp) + '/' + data[:3] + '/' + l.convert_time_to_string(rrf_data['elsewhere'][3][data]) + '/' + str(rrf_data['elsewhere'][5][data])

                            i += 1
                except:
                    pass

            if data_transmit['Indicatif'] != '':
                if s.transmit is False:      # Wake up screen...
                    s.transmit = l.wake_up_screen(s.device, s.display, s.transmit)

                s.call_current = l.sanitize_call(data_transmit['Indicatif'])
                s.call_type = data_transmit['Type']
                s.call_description = data_transmit['Description']
                s.call_tone = data_transmit['Tone']
                s.call_locator = data_transmit['Locator']
                s.call_sysop = data_transmit['Sysop']
                s.call_prenom = data_transmit['Prenom']
                s.call_latitude = data_transmit['Latitude']
                s.call_longitude = data_transmit['Longitude']

                s.duration = data_transmit['TOT']

            else:
                if s.transmit is True:       # Sleep screen...
                    s.transmit = l.wake_up_screen(s.device, s.display, s.transmit)

                # Load Histogram
                for q in range(0, 24):
                    s.qso_hour[q] = data_activity[q]['TX']

                # Load Last
                limit = len(rrf_data['last'])
                s.call = [''] * 10 
                s.call_time = [''] * 10 

                for q in range(0, limit):
                    s.call[q] = l.sanitize_call(rrf_data['last'][q]['Indicatif'])
                    s.call_time[q] = rrf_data['last'][q]['Heure']

                # Load Best
                limit = len(rrf_data['all'])
                s.best = [''] * 10 
                s.best_time = [0] * 10 

                for q in range(0, limit):
                    s.best[q] = l.sanitize_call(rrf_data['all'][q]['Indicatif'])
                    s.best_time[q] = l.convert_time_to_second(rrf_data['all'][q]['Durée'])

            if(s.seconde < 10):     # TX today
                s.message[0] = 'TX total ' + str(data_abstract['TX total'])

            elif(s.seconde < 20):   # Active node
                s.message[0] = 'Links actifs ' + str(data_abstract['Links actifs'])

            elif(s.seconde < 30):   # Online node
                s.message[0] = 'Links total ' + str(data_abstract['Links connectés'])
                
            elif(s.seconde < 40):   # Total emission
                tmp = l.convert_time_to_string(data_abstract['Emission cumulée'])
                if 'h' in tmp:
                    tmp = tmp[0:6]
                s.message[0] = 'BF total ' + tmp

            elif(s.seconde < 50):   # Last TX
                s.message[0] = 'Dernier ' + data_last[0]['Heure']

            elif(s.seconde < 60):   # Scan
                if s.scan is True:
                    s.message[0] = 'Suivi de ' + s.callsign
                else:
                    s.message[0] = 'Salon ' + s.room_current[:3]

        # Print screen
        if s.device.height == 128:
            d.display_128()
        else:
            d.display_64()

        chrono_stop = time.time()
        chrono_time = chrono_stop - chrono_start
        if chrono_time < s.refresh:
            sleep = s.refresh - chrono_time
        else:
            sleep = 0
        #print "Temps d'execution : %.2f %.2f secondes" % (chrono_time, sleep)
        #sys.stdout.flush()

        time.sleep(sleep)
示例#12
0
 def init_st7735(self):
     light = backlight(gpio=GPIO, gpio_LIGHT=18, active_low=False)
     light.enable(True)
     serial = spi(port=0, device=0, gpio_DC=23, gpio_RST=24)
     device = st7735(serial)
     return device
示例#13
0
def serial_displays(**kwargs):

    if kwargs['serial_display_type'] == 'oled_sh1106':
        from luma.core.interface.serial import i2c, spi
        from luma.core.render import canvas
        # from luma.core import lib
        from luma.oled.device import sh1106
        # from PIL import Image
        # from PIL import ImageDraw
        from PIL import ImageFont
        from time import sleep
        import logging
        # import socket

        # Load default font.
        font = ImageFont.load_default()
        # Create blank image for drawing.
        # Make sure to create image with mode '1' for 1-bit color.
        width = 128
        height = 64
        # image = Image.new('1', (width, height))
        # First define some constants to allow easy resizing of shapes.
        padding = 0
        top = padding
        bottom = height - padding
        display_rotate = kwargs['serial_display_rotate']
        # Move left to right keeping track of the current x position for drawing shapes.
        x = 0

        logging.basicConfig(
            filename='/tmp/rpims_serial_display.log',
            level=logging.DEBUG,
            format='%(asctime)s %(levelname)s %(name)s %(message)s')
        logger = logging.getLogger(__name__)

        serial_type = kwargs['serial_type']

        #if serial_type == 'i2c':
        serial = i2c(port=1, address=0x3c)
        if serial_type == 'spi':
            serial = spi(device=0,
                         port=0,
                         bus_speed_hz=8000000,
                         transfer_size=4096,
                         gpio_DC=24,
                         gpio_RST=25)

        try:
            device = sh1106(serial, rotate=display_rotate)
            while True:
                with canvas(device) as draw:
                    # get data from redis db
                    values = redis_db.mget('BME280_Temperature',
                                           'BME280_Humidity',
                                           'BME280_Pressure', 'GPIO_5',
                                           'GPIO_6', 'CPU_Temperature',
                                           'hostip')

                    t, h, p = values[0], values[1], values[2]
                    if t == None or h == None or p == None:
                        temperature = '--.--'
                        humidity = '--.--'
                        pressure = '--.--'
                    elif t.replace('.', '', 1).isdigit() and h.replace(
                            '.', '', 1).isdigit() and p.replace('.', '',
                                                                1).isdigit():
                        temperature = round(float(t), 1)
                        humidity = int(round(float(h), 1))
                        pressure = int(round(float(p), 1))

                    door_sensor_1, door_sensor_2 = values[3], values[4]
                    if door_sensor_1 == None or door_sensor_2 == None:
                        door_sensor_1 = '-----'
                        door_sensor_2 = '-----'

                    cputemp = values[5]
                    if cputemp == None:
                        cputemp = '-----'
                    else:
                        cputemp = round(float(cputemp), 1)
                    hostip = values[6]
                    if hostip == None:
                        hostip = '---.---.---.---'

                    # draw on oled
                    draw.text((x, top),
                              'IP:' + str(hostip),
                              font=font,
                              fill=255)
                    draw.text((x, top + 9),
                              f'Temperature..{temperature}°C',
                              font=font,
                              fill=255)
                    draw.text((x, top + 18),
                              f'Humidity.....{humidity}%',
                              font=font,
                              fill=255)
                    draw.text((x, top + 27),
                              f'Pressure.....{pressure}hPa',
                              font=font,
                              fill=255)
                    draw.text((x, top + 36),
                              f'Door 1.......{door_sensor_1}',
                              font=font,
                              fill=255)
                    draw.text((x, top + 45),
                              f'Door 2.......{door_sensor_2}',
                              font=font,
                              fill=255)
                    draw.text((x, top + 54),
                              f'CpuTemp......{cputemp}°C',
                              font=font,
                              fill=255)
                sleep(1 / kwargs['serial_display_refresh_rate'])
        except Exception as err:
            logger.error(err)

    if kwargs['serial_display_type'] == 'lcd_st7735':
        from luma.core.interface.serial import spi
        from luma.core.render import canvas
        # from luma.core import lib
        from luma.lcd.device import st7735
        # from PIL import Image
        # from PIL import ImageDraw
        from PIL import ImageFont
        # from PIL import ImageColor
        # import RPi.GPIO as GPIO
        from time import time, sleep
        import datetime
        import logging
        # import socket
        import redis
        # Load default font.
        font = ImageFont.load_default()
        # Display width/height
        width = 128
        height = 128
        # First define some constants to allow easy resizing of shapes.
        padding = 0
        top = padding
        # bottom = height-padding
        # Move left to right keeping track of the current x position for drawing shapes.
        x = 0

        logging.basicConfig(
            filename='/tmp/rpims_serial_display.log',
            level=logging.DEBUG,
            format='%(asctime)s %(levelname)s %(name)s %(message)s')
        logger = logging.getLogger(__name__)
        display_rotate = kwargs['serial_display_rotate']
        serial = spi(device=0,
                     port=0,
                     bus_speed_hz=8000000,
                     transfer_size=4096,
                     gpio_DC=25,
                     gpio_RST=27)

        try:
            device = st7735(serial)
            device = st7735(serial,
                            width=128,
                            height=128,
                            h_offset=1,
                            v_offset=2,
                            bgr=True,
                            persist=False,
                            rotate=display_rotate)

            while True:
                # get data from redis db
                values = redis_db.mget('BME280_Temperature', 'BME280_Humidity',
                                       'BME280_Pressure', 'GPIO_5', 'GPIO_6',
                                       'CPU_Temperature', 'hostip')

                t, h, p = values[0], values[1], values[2]
                if t == None or h == None or p == None:
                    temperature = '--.--'
                    humidity = '--.--'
                    pressure = '--.--'
                elif t.replace('.', '', 1).isdigit() and h.replace(
                        '.', '', 1).isdigit() and p.replace('.', '',
                                                            1).isdigit():
                    temperature = round(float(t), 1)
                    humidity = int(round(float(h), 1))
                    pressure = int(round(float(p), 1))

                door_sensor_1, door_sensor_2 = values[3], values[4]
                if door_sensor_1 == None or door_sensor_2 == None:
                    door_sensor_1 = '-----'
                    door_sensor_2 = '-----'

                cputemp = values[5]
                if cputemp == None:
                    cputemp = '-----'
                else:
                    cputemp = round(float(cputemp), 1)

                hostip = values[6]
                if hostip == None:
                    hostip = '---.---.---.---'

                now = datetime.datetime.now()
                # Draw
                with canvas(device) as draw:
                    draw.text((x + 35, top),
                              'R P i M S',
                              font=font,
                              fill="cyan")
                    draw.text((x, top + 15),
                              ' Temperature',
                              font=font,
                              fill="lime")
                    # draw.text((x+71, top+15),'', font=font, fill="blue")
                    draw.text((x + 77, top + 15),
                              str(temperature) + ' *C',
                              font=font,
                              fill="lime")

                    draw.text((x, top + 28),
                              ' Humidity',
                              font=font,
                              fill="lime")
                    # draw.text((x+70, top+28),'', font=font, fill="blue")
                    draw.text((x + 77, top + 28),
                              str(humidity) + ' %',
                              font=font,
                              fill="lime")

                    draw.text((x, top + 41),
                              ' Pressure',
                              font=font,
                              fill="lime")
                    # draw.text((x+70, top+41),'', font=font, fill="blue")
                    draw.text((x + 77, top + 41),
                              str(pressure) + ' hPa',
                              font=font,
                              fill="lime")

                    draw.text((x, top + 57),
                              ' Door 1',
                              font=font,
                              fill="yellow")
                    # draw.text((x+70, top+57),'', font=font, fill="yellow")
                    draw.text((x + 77, top + 57),
                              str(door_sensor_1),
                              font=font,
                              fill="yellow")

                    draw.text((x, top + 70),
                              ' Door 2',
                              font=font,
                              fill="yellow")
                    # draw.text((x+70, top+70),'', font=font, fill="yellow")
                    draw.text((x + 77, top + 70),
                              str(door_sensor_2),
                              font=font,
                              fill="yellow")

                    draw.text((x, top + 86),
                              ' CPUtemp',
                              font=font,
                              fill="cyan")
                    draw.text((x + 77, top + 86),
                              str(cputemp) + " *C",
                              font=font,
                              fill="cyan")

                    draw.text((x, top + 99), ' IP', font=font, fill="cyan")
                    draw.text((x + 17, top + 99), ':', font=font, fill="cyan")
                    draw.text((x + 36, top + 99),
                              str(hostip),
                              font=font,
                              fill="cyan")

                    draw.text((x + 5, top + 115),
                              now.strftime("%Y-%m-%d %H:%M:%S"),
                              font=font,
                              fill="floralwhite")

                sleep(1 / kwargs['serial_display_refresh_rate'])
        except Exception as err:
            logger.error(err)
示例#14
0
import os
import CHIP_IO.GPIO
from luma.core.interface.serial import spi
from luma.core.render import canvas
from luma.lcd.device import st7735
from PIL import ImageFont
from socketIO_client import SocketIO, BaseNamespace


serial = spi(port=32766, device=0, gpio=CHIP_IO.GPIO, gpio_DC="CSID1", gpio_RST="CSID0")
device = st7735(serial, 128, 128, bgr=True)

font_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'Roboto-Medium.ttf'))
roboto = ImageFont.truetype(font_path, 20)


class PeriodicSampleNamespace(BaseNamespace):
    def __init__(self, io, path):
        super(PeriodicSampleNamespace, self).__init__(io, path)
        self.on('periodic-sample', self.on_sample)

    def on_sample(self, sample):
        with canvas(device) as draw:
            draw.text((3, 3), self.format_sample(sample), font=roboto, fill="white")

    def format_sample(self, sample):
        if(abs(sample) < 1 / float(1000) / 1000):
            return str("%dnA" % round(sample * 1000 * 1000 * 1000))
        elif(abs(sample) < 1 / float(1000)):
            return str("%guA" % round(sample * 1000 * 1000, 2))
        elif(abs(sample) < 1):
示例#15
0
# -*- coding: UTF-8 -*-

from luma.core.interface.serial import spi
from luma.lcd.device import st7735
from PIL import Image, ImageDraw, ImageFont

serial = spi(port=0, device=0)
device = st7735(serial,
                width=128,
                height=128,
                rotate=2,
                h_offset=1,
                v_offset=2,
                bgr=True)

buffer = Image.new(device.mode, device.size)
draw = ImageDraw.Draw(buffer)

while True:
    draw.rectangle(device.bounding_box, outline=None, fill=(152, 152, 3))
    draw.text((30, 50), "hello world!", "white")
    device.display(buffer)
示例#16
0
    redis_db = redis.StrictRedis(host="localhost",
                                 port=6379,
                                 db=0,
                                 charset="utf-8",
                                 decode_responses=True)
    config = redis_db.mget('use_BME280_sensor', 'use_CPU_sensor',
                           'use_door_sensor', 'hostip',
                           'serial_display_rotate')
    display_rotate = int(config[4])
    serial = spi(device=0,
                 port=0,
                 bus_speed_hz=8000000,
                 transfer_size=4096,
                 gpio_DC=25,
                 gpio_RST=27)
    device = st7735(serial)
    device = st7735(serial,
                    width=128,
                    height=128,
                    h_offset=1,
                    v_offset=2,
                    bgr=True,
                    persist=False,
                    rotate=display_rotate)

    while True:
        now = datetime.datetime.now()
        with canvas(device) as draw:
            #values = redis_db.mget('BME280_Temperature', 'BME280_Humidity', 'BME280_Pressure', 'CPU_Temperature', 'hostip', 'serial_display_rotate')
            now = datetime.datetime.now()
            hostip = config[3]
示例#17
0
# Load assets
logo = Image.open('assets/picorderOS_logo.png')

# Raspberry Pi hardware SPI config:
DC = 23
RST = 24
SPI_PORT = 0
SPI_DEVICE = 0

TRANSITION = [False]


if not configure.pc:
	serial = spi(port = SPI_PORT, device = SPI_DEVICE, gpio_DC = DC, gpio_RST = RST)# ,bus_speed_hz=24000000)
	device = st7735(serial, width = 160, height = 128, mode = "RGB")
else:
	device = pygame(width = 160, height = 128)


# Standard LCARS colours
lcars_orange = (255,153,0)
lcars_pink = (204,153,204)
lcars_blue = (153,153,204)
lcars_red = (204,102,102)
lcars_peach = (255,204,153)
lcars_bluer = (153,153,255)
lcars_orpeach = (255,153,102)
lcars_pinker = (204,102,153)

theme1 =  [lcars_orange,lcars_blue,lcars_pinker]
示例#18
0
def test_hide():
    device = st7735(serial)
    serial.reset_mock()
    device.hide()
    serial.command.assert_called_once_with(40)