def main():
    if debug == 1:
        prGreen(scriptname)
        prGreen(scriptversion)
        prRed('Server Details')
        print ' Hostname        :', hostnamePI
        ver = server.system.client_version()
        print ' rtorrent ver    :', ver
        totalUpload = server.get_up_total()
        totalDownload = server.get_down_total()
        print ' Total Upload    :', totalUpload / 1024 / 1024 / 1024, 'GB'
        print ' Total Download  :', totalDownload / 1024 / 1024 / 1024, 'GB'
        print ''
        prRed('Current Speeds')
        print ' Current Upload Rate  :', rate_ul(), 'KB/s'
        print ' Current Download Rate:', rate_dl(), 'KB/s'
        print ''
        prRed('Torrents Currently Leeching')
        getLeechingData()
        print ''

    getLeechingData()
    oled = ssd1306(port=1, address=0x3C)
    prGreen(scriptname)
    prGreen(scriptversion)
    prYellow(
        "Sending Data to SSD1306 OLED over i2C -enable debug mode for more info"
    )
    while 1 > 0:  #infiniteloop :) probably not best practice. may be revised.
        stats(oled)
        time.sleep(1)
示例#2
0
def Write(dateTime, temp, humidity):
	device = ssd1306(port=1, address=0x3C)

	with canvas(device) as draw:
		font = ImageFont.truetype("FreeSans.ttf", 12)
		draw.text((10,5), "Time: {0}".format(time.strftime('%Y-%m-%d %H:%M:%S', dateTime)), font=font, fill=255)
		draw.text((10,25), "Temp: {0:0.1f}\xb0C".format(temp), font=font, fill=255)
		draw.text((10,45), "Humi: {0:0.1f}%".format(humidity), font=font, fill=255)
def test_init_96x16():
    ssd1306(serial, width=96, height=16)
    serial.command.assert_has_calls([
        # Initial burst are initialization commands
        call(174, 213, 96, 168, 15, 211, 0, 64, 141, 20, 32, 0,
             160, 200, 218, 2, 217, 241, 219, 64, 164, 166),
        # set contrast
        call(129, 207),
        # reset the display
        call(33, 0, 95, 34, 0, 1),
        # called last, is a command to show the screen
        call(175)
    ])

    # Next 192 are all data: zero's to clear the RAM
    # (192 = 96 * 16 / 8)
    serial.data.assert_called_once_with([0] * (96 * 16 // 8))
def test_init_128x32():
    ssd1306(serial, width=128, height=32)
    serial.command.assert_has_calls([
        # Initial burst are initialization commands
        call(174, 213, 128, 168, 31, 211, 0, 64, 141, 20, 32, 0,
             160, 200, 218, 2, 217, 241, 219, 64, 164, 166),
        # set contrast
        call(129, 207),
        # reset the display
        call(33, 0, 127, 34, 0, 3),
        # called last, is a command to show the screen
        call(175)
    ])

    # Next 512 are all data: zero's to clear the RAM
    # (512 = 128 * 32 / 8)
    serial.data.assert_called_once_with([0] * (128 * 32 // 8))
def test_init_128x64():
    ssd1306(serial)
    serial.command.assert_has_calls([
        # Initial burst are initialization commands
        call(174, 213, 128, 168, 63, 211, 0, 64, 141, 20, 32, 0,
             160, 200, 218, 18, 217, 241, 219, 64, 164, 166),
        # set contrast
        call(129, 207),
        # reset the display
        call(33, 0, 127, 34, 0, 7),
        # called last, is a command to show the screen
        call(175)
    ])

    # Next 1024 are all data: zero's to clear the RAM
    # (1024 = 128 * 64 / 8)
    serial.data.assert_called_once_with([0] * (128 * 64 // 8))
示例#6
0
    def __init__(self):

        self.device = ssd1306(port=1, address=0x3C)
        self.font = ImageFont.truetype(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), 'oled/font/OpenSans.ttf'), 14)
        self.width = self.device.width
        self.height = self.device.height
        # Clear the screen, as it sometimes draws some artifacts when initialized
        self.clear()
示例#7
0
    def __init__(self, message, version, config, sw_rev, heartbeat):
        Thread.__init__(self)
        self.event = Event()
        self.log = logging.getLogger()

        self.heartbeat = heartbeat

        if sw_rev == 1:
            self.reset()  # Needed for V2

        self.config = config
        self.version = version
        self.sw_rev = sw_rev
        self.message = message

        # TODO: gracefully handle exception when OLED absent
        if self.config.hw_rev == 1:
            self.device = sh1106(port=1, address=0x3C)
        else:
            # self.device = Adafruit_SSD1306.SSD1306_128_64(rst=24)
            self.device = ssd1306(port=1, address=0x3C)
        self.font = ImageFont.load_default()
        # self.font = ImageFont.truetype("5by7.ttf",10)
        self.mode = m_IDLE

        self.row_index = 0
        self.col_index = 0
        self.char_space = 6
        self.char_size = 4
        self.row_height = 12
        self.screen_row_size = 5
        self.screen_col_size = 21
        self.horiz_min = 0
        self.horiz_max = self.screen_col_size
        self.horiz_index = 0
        self.horiz_reset_cnt = 0
        self.horiz_start_cnt = 0
        self.viz_min = 0
        self.viz_max = self.screen_row_size

        self.dialog_msg = ""
        self.dialog_msg2 = ""
        self.dialog_msg3 = ""
        self.dialog_confirmed = False
        self.dialog_cmd = 0
        self.dialog_task_done = False
        self.dialog_next_mode = m_MAIN_MENU

        self.cursor = True
        self.cursor_x = 0
        self.cursor_y = 0
        self.key_repeating = False

        self.log_tail_results = []

        self.reg_stage = 1  # WNode Registration Stage. 1/Name,2/NetKey,3/GrpKey
        self.log.info("Initialized Display Thread.")
示例#8
0
def test_init():
    ssd1306(bus)
    assert len(bus.recordings) == 35
    # Bursts 0/1 are initialization commands
    cmds = [174, 213, 128, 168, 63, 211, 0, 64, 141, 20, 32, 0,
            160, 200, 218, 18, 129, 207, 217, 241, 219, 64, 164,
            166, 33, 0, 127, 34, 0, 7]
    assert bus.recordings[0].mode == 0
    assert bus.recordings[1].mode == 0
    assert bus.recordings[0].data + bus.recordings[1].data == cmds

    # Next 32 bursts are all data: zero's to clear the RAM
    # (32 * 32 = 1024 = 128 * 64 / 8)
    for i in range(32):
        assert bus.recordings[i + 2] == mock.recording(60, 64, [0] * 32)

    # Last burst is a command to show the screen
    assert bus.recordings[34] == mock.recording(60, 0, [175])
示例#9
0
 def connect(self):
     while constant.CHECK_OLED:
         try:
             self.device = ssd1306(port=1, address=0x3C)
             break
         except Exception as e:
             debug("[ERROR] OLED NOT CONNECTED")
             debug(e)
             sleep(5)
示例#10
0
def demo(iterations):
    device = ssd1306(port=1, address=0x3C)
    screen = (128, 64)
    for loop in range(iterations):
        for scale in [2,3,4,3]:
            sz = map(lambda z: z/scale-1, screen)
            with canvas(device) as draw:
                Maze(sz).render(draw, lambda z: int(z * scale))
                time.sleep(1)
示例#11
0
def demo(iterations):
    device = ssd1306(port=1, address=0x3C)
    screen = (128, 64)
    for loop in range(iterations):
        for scale in [2, 3, 4, 3]:
            sz = map(lambda z: z / scale - 1, screen)
            with canvas(device) as draw:
                Maze(sz).render(draw, lambda z: int(z * scale))
                time.sleep(1)
示例#12
0
    def __init__(self, options=[]):
        self.options = options
        self.highlightOption = None
        self.rowCount = 6

        self.oled = ssd1306(port=3, address=0x3C)

        self.font = ImageFont.truetype('fonts/mobitec.ttf', 8)

        self.renderThread = None
def test_display():
    device = ssd1306(serial)
    serial.reset_mock()

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

    # Initial command to reset the display
    serial.command.assert_called_once_with(33, 0, 127, 34, 0, 7)

    # Next 1024 bytes are data representing the drawn image
    serial.data.assert_called_once_with(baseline_data.demo_ssd1306)
示例#14
0
    def oled_init2(self):
        from oled.serial import i2c
        from oled.device import ssd1306, ssd1331, sh1106
        from oled.render import canvas

        # rev.1 users set port=0
        # substitute spi(device=0, port=0) below if using that interface
        serial = i2c(port=1, address=0x3C)

        # substitute ssd1331(...) or sh1106(...) below if using that device
        device = ssd1306(serial)
        with canvas(device) as draw:
            draw.rectangle(device.bounding_box, outline="white", fill="black")
            draw.text((30, 40), "Hello World", fill="white")
示例#15
0
def test_diplay():
    device = ssd1306(bus)
    bus.reset()

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

    assert len(bus.recordings) == 33

    # Initial command to reset the display
    assert bus.recordings[0] == mock.recording(60, 0, [33, 0, 127, 34, 0, 7])

    # Next 32 recordings are data representing the drawn image
    for i in range(32):
        assert bus.recordings[i + 1] == baseline_data.demo_ssd1306[i]
示例#16
0
def main():
    oled = ssd1306(port=0, address=0x3C)
    font = ImageFont.load_default()
    font2 = ImageFont.truetype('./FreeSans.ttf', 20)

    while True:
        print("o")
        result = instance.read()
        if result.is_valid():
            print(".")
            with canvas(oled) as draw:
                draw.text((0, 0),
                          "Temp: %d C" % result.temperature,
                          font=font2,
                          fill=255)
                draw.text((0, 40),
                          "Um: %d %%" % result.humidity,
                          font=font2,
                          fill=255)
        time.sleep(5)
示例#17
0
def main():
    oled = ssd1306(port=0, address=0x3C)
    font = ImageFont.load_default()
    font2 = ImageFont.truetype('./FreeSans.ttf', 20)

    c = 0
    t_ok = 0
    h_ok = 0

    while True:
        result = instance.read()

        if result.is_valid():
            t_ok = result.temperature
            h_ok = result.humidity
            str_status = "."
        else:
            str_status = "o"

        if c <= 0:
            c = 10
        else:
            c = c - 1

        with canvas(oled) as draw:
            draw.text((0, 0), "Temp: %d C" % t_ok, font=font2, fill=255)
            draw.text((0, 40),
                      "Um: %d %%    %s" % (h_ok, str_status),
                      font=font2,
                      fill=255)

        # debug
        #print(str_status)
        #print(c)
        #print("%d - %d" % (t_ok,h_ok))

        time.sleep(1)
def main():
    if debug == 1: 
        prGreen(scriptname) ; prGreen(scriptversion)
        prRed('Server Details')
        print ' Hostname        :', hostnamePI   
        ver = server.system.client_version();     
        print ' rtorrent ver    :', ver
        totalUpload = server.get_up_total(); 
        totalDownload = server.get_down_total(); 
        print ' Total Upload    :', totalUpload/1024/1024/1024,'GB'
        print ' Total Download  :', totalDownload/1024/1024/1024,'GB'; print '' 
        prRed('Current Speeds')
        print ' Current Upload Rate  :', rate_ul(),'KB/s'
        print ' Current Download Rate:', rate_dl(),'KB/s'; print '' 
        prRed('Torrents Currently Leeching')
        getLeechingData()
        print ''

    getLeechingData()
    oled = ssd1306(port=1, address=0x3C)
    prGreen(scriptname) ; prGreen(scriptversion) ; prYellow("Sending Data to SSD1306 OLED over i2C -enable debug mode for more info")
    while 1 > 0: #infiniteloop :) probably not best practice. may be revised.            
        stats(oled)
        time.sleep(1)
示例#19
0
#!/usr/bin/env python
# coding: Latin-1

# Load library functions we want
import time, os, pygame
import RPi.GPIO as GPIO
from oled.device import ssd1306, sh1106
from oled.render import canvas
from PIL import ImageDraw, ImageFont


# oled stuff
oled = ssd1306(port=1, address=0x3C)
font = ImageFont.truetype('redalert.ttf', 60)

GPIO.setmode(GPIO.BOARD) # Set pins by location
GPIO.setwarnings(False)

# Configure servo
GPIO.setup(12, GPIO.OUT)
pwm = GPIO.PWM(12, 100)
pwm.start(5)
global servoAngle

# Configure DC
MotorPin1   = 11    # pin11
MotorPin2   = 16    # pin12
MotorEnable = 13    # pin13
GPIO.setup(MotorPin1, GPIO.OUT)   # mode --- output
GPIO.setup(MotorPin2, GPIO.OUT)
GPIO.setup(MotorEnable, GPIO.OUT)
示例#20
0
def main():
    oled = ssd1306(port=3, address=0x3C)
    test_menu()
示例#21
0
def main():
    oled = ssd1306(port=1, address=0x3C)
    stats(oled)
示例#22
0
def test_hide():
    device = ssd1306(bus)
    bus.reset()
    device.hide()
    assert len(bus.recordings) == 1
    assert bus.recordings[0] == mock.recording(60, 0, [174])
示例#23
0
 def _request_device(self):
     return ssd1306(port=self.port, address=self.address)
示例#24
0
    def run(self):
        font2 = ImageFont.truetype('/etc/stratux-screen/CnC_Red_Alert.ttf', 12)
        oled = ssd1306(port=1, address=0x3C)

        with canvas(oled) as draw:
            logo = Image.open('/etc/stratux-screen/stratux-logo-64x64.bmp')
            draw.bitmap((32, 0), logo, fill=1)

        time.sleep(10)
        n = 0

        while 1:
            time.sleep(1)
            response = urllib2.urlopen('http://localhost/getStatus')
            getStatusHTML = response.read()
            getStatusData = json.loads(getStatusHTML)
            CPUTemp = getStatusData["CPUTemp"]
            uat_current = getStatusData["UAT_messages_last_minute"]
            uat_max = getStatusData["UAT_messages_max"]
            es_current = getStatusData["ES_messages_last_minute"]
            es_max = getStatusData["ES_messages_max"]
    
            response = urllib2.urlopen('http://localhost/getTowers')
            getTowersHTML = response.read()
            getTowersData = json.loads(getTowersHTML)
            NumTowers = 0
            for towerLatLng in getTowersData:
                print getTowersData[towerLatLng]["Messages_last_minute"]
                if (getTowersData[towerLatLng]["Messages_last_minute"] > 0):
                    NumTowers += 1

            with canvas(oled) as draw:
                pad = 2 # Two pixels on the left and right.
                text_margin = 25
                # UAT status.
                draw.text((50, 0), "UAT", font=font2, fill=255)
                # "Status bar", 2 pixels high.
                status_bar_width_max = oled.width - (2 * pad) - (2 * text_margin)
                status_bar_width = 0
                if uat_max > 0:
                    status_bar_width = int((float(uat_current) / uat_max) * status_bar_width_max)
                draw.rectangle((pad + text_margin, 14, pad + text_margin + status_bar_width, 20), outline=255, fill=255) # Top left, bottom right.
                # Draw the current (left) and max (right) numbers.
                draw.text((pad, 14), str(uat_current), font=font2, fill=255)
                draw.text(((2*pad) + text_margin + status_bar_width_max, 14), str(uat_max), font=font2, fill=255)
                # ES status.
                draw.text((44, 24), "1090ES", font=font2, fill=255)
                status_bar_width = 0
                if es_max > 0:
                    status_bar_width = int((float(es_current) / es_max) * status_bar_width_max)
                draw.rectangle((pad + text_margin, 34, pad + text_margin + status_bar_width, 40), outline=255, fill=255) # Top left, bottom right.
                # Draw the current (left) and max (right) numbers.
                draw.text((pad, 34), str(es_current), font=font2, fill=255)
                draw.text(((2*pad) + text_margin + status_bar_width_max, 34), str(es_max), font=font2, fill=255)
                # Other stats.
                seq = (n / 5) % 2
                t = ""
                if seq == 0:
                    t = "CPU: %0.1fC, Towers: %d" % (CPUTemp, NumTowers)
                if seq == 1:
                    t = "GPS Sat: %d/%d/%d" % (getStatusData["GPS_satellites_locked"], getStatusData["GPS_satellites_seen"], getStatusData["GPS_satellites_tracked"])
                    if getStatusData["GPS_solution"] == "GPS + SBAS (WAAS / EGNOS)":
                        t = t + " (WAAS)"
                #print t
                draw.text((pad, 45), t, font=font2, fill=255)

            n = n+1
示例#25
0
def main():
    """Start the bot."""
    global bot, oled, logo_img, FONT2, serial, SCREENS_DIR, mail_thread, work_thread, FONT2

    # Проверяем есть ли папка для сохранения данных
    if not os.path.isdir(LIB_DIR):
        os.mkdir(LIB_DIR)

    if not os.path.exists(LOG_PATH):
        os.mkdir(LOG_PATH)

    logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")

    pkg_name = vars(sys.modules[__name__])['__package__']
    if pkg_name is None:
        pkg_name = __name__

    fileHandler = logging.FileHandler('{0}/{1}.log'.format(LOG_PATH, pkg_name))
    fileHandler.setFormatter(logFormatter)
    logger.addHandler(fileHandler)

    consoleHandler = logging.StreamHandler(sys.stdout)
    consoleHandler.setFormatter(logFormatter)
    logger.addHandler(consoleHandler)

    logger.setLevel(logging.INFO)

    logger.info("Service started")

    #Проверяем можно ли писать в эту папку
    try:
        fd, name = tempfile.mkstemp(dir=LIB_DIR)
    except Exception as _e:
        logger.error("Storage is not writable")
    else:
        os.close(fd)
        os.remove(os.path.join(LIB_DIR, name))

    SCREENS_DIR = os.path.join(LIB_DIR, SCREENS_DIR)
    if not os.path.isdir(SCREENS_DIR):
        os.mkdir(SCREENS_DIR)

    loadSettings()

    try:
        model = None
        board_json = '/etc/board.json'
        if os.path.isfile(board_json):
            with open(board_json) as json_file:
                board = json.load(json_file)
                if board['model'] is not None and board['model']['id'] is not None:
                    _manuf, model = board['model']['id'].split(',', 2)

        GPIO.setwarnings(False)

        if model == 'orangepi-zero':
            import orangepi.zero # pylint: disable=unused-import, import-outside-toplevel
            GPIO.setmode(orangepi.zero.BOARD)
        else:
            import orangepi.zeroplus2 # pylint: disable=unused-import, import-outside-toplevel
            GPIO.setmode(orangepi.zeroplus2.BOARD)

        GPIO.setup(PIN_NUM, GPIO.OUT)
        GPIO.output(PIN_NUM, GPIO.LOW if INVERT_PIN else GPIO.HIGH)

        oled = ssd1306(port=0, address=0x3C)
    except Exception as e:
        logger.error("Unable to init Hardware %s", e)

    try:
        FONT2 = ImageFont.truetype(os.path.join(os.path.dirname(__file__), 'fonts/C&C Red Alert [INET].ttf'), 15)
    except Exception as e:
        logger.error("Unable to Load font: %s", e)

    logo_loaded = False
    logo_file = os.path.join(LIB_DIR, LOGO_FILE)
    if os.path.isfile(logo_file):
        logo_img = Image.open(logo_file)
        logo_img.convert("L")
        logger.info("QR Loaded")
        logo_loaded = True
    if not logo_loaded:
        generate_logo(logo_file)

    ImageDraw.Draw(screen).rectangle([(0, 0), screen.size], fill=0)
    screen.paste(logo_img, (0, 0))

    try:
        oled.display(screen)
    except Exception:
        pass

    serial = getSerial()
    logger.info('My serial is : %s', serial)

    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater(TOKEN, use_context=True, user_sig_handler=sig_handler)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help_command))

    dp.add_handler(CommandHandler("state", bot_state))
    dp.add_handler(CommandHandler("turnon", bot_turnon))
    dp.add_handler(CommandHandler("turnoff", bot_turnoff))
    dp.add_handler(CommandHandler("logs", bot_logs, pass_args=True))
    dp.add_handler(CommandHandler("serial", bot_serial))
    dp.add_handler(CommandHandler("screen", bot_screen))
    dp.add_handler(CommandHandler("savers", bot_savers, pass_args=True, pass_job_queue=True, pass_chat_data=True))
    dp.add_handler(CommandHandler("logo", bot_logo, pass_args=True, pass_job_queue=True, pass_chat_data=True))
    dp.add_handler(CommandHandler("password", bot_password))
    dp.add_handler(MessageHandler(Filters.document, document_handler))

    # ...and the error handler
    dp.add_error_handler(error_handler)

    logger.info("Bot started")

    # Start the Bot
    updater.start_polling()

    bot = updater.bot

    mail_thread = threading.Thread(target=check_mail, name="check_mail")
    mail_thread.e = threading.Event()
    work_thread = threading.Thread(target=check_work, name="check_work")
    work_thread.e = threading.Event()

    loadWork()

    mail_thread.start()
    work_thread.start()

    while True:
        try:
            bot.send_message(CHANNEL_ID, _('Bot Started'), "Markdown", True)
        except Exception:
            time.sleep(10)
            continue
        else:
            break

    bot.send_message(CHANNEL_ID, _('My IP: {}').format(get_ip_address()), "Markdown", True)

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

    GPIO.cleanup()
示例#26
0
import requests
import time
from PIL import Image, ImageFont, ImageDraw, ImageOps
import logging
from requests import ConnectionError

from oled.device import ssd1306
from oled.serial import i2c

SCREEN_HOLD_SECONDS = 10
MAX_CONNECTION_ERRORS = 6

temp = "?"
connection_errors = 0
serial = i2c(port=1, address=0x3c)
device = ssd1306(serial)
ttf = '/usr/share/fonts/truetype/freefont/FreeSerifBold.ttf'
font60 = ImageFont.truetype(ttf, 66)

logger = logging.getLogger('idokep')
logger.setLevel(logging.INFO)
fh = logging.FileHandler('/var/log/idokep.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)


def update_screen():
    global temp
示例#27
0
def main():

    oled = ssd1306(port=2, address=0x3C)
    while True:
        trello(oled)
        time.sleep(60*10)
def main():
    oled = ssd1306(port=0, address=0x3D)
    stats(oled)
from PIL import ImageFont, ImageDraw, Image

filepath = '/home/pi/TestJig'
test_program = 'Espresso-Lite-Testjig-small-rpi2.ino.bin'
test_program_asus = 'Espresso-Lite-Testjig-small-rpi2-asus.ino.bin'
user_program = '_2000_ESPert_workshop.ino.bin'

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(21, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(25, GPIO.IN, GPIO.PUD_UP)

device = ssd1306(port=1, address=0x3C)

#font type
font_dir = '/home/pi/ssd1306/fonts/C&C Red Alert [INET].ttf'
font_dir2 = '/home/pi/ssd1306/fonts/arial.ttf'
#font = ImageFont.load_default()
font1 = ImageFont.truetype(font_dir, 18)
font2 = ImageFont.truetype(font_dir, 12)
font3 = ImageFont.truetype(font_dir2, 16)
font4 = ImageFont.truetype(font_dir2, 12)

stage = 0
current_stage = 1
continue_bit = 0
wifi = 0
err=0
示例#30
0
# @author khinds
# @license http://opensource.org/licenses/gpl-license.php GNU Public License
from math import cos, sin, pi, radians
from oled.device import ssd1306, sh1106
from oled.render import canvas
from PIL import ImageFont
import time
import includes.data as data
 
# define fonts
font = ImageFont.load_default()
titleFont = ImageFont.truetype('/home/pi/CarComputer/computer/fonts/DroidSansMono.ttf', 20)
bodyFont = ImageFont.truetype('/home/pi/CarComputer/computer/fonts/TheNextFont.ttf', 24)

# device and screen settings
device = ssd1306()
currentDirection = 0
while True:
    try:
        with canvas(device) as draw:
        
            # location.data
            locationInfo = data.getJSONFromDataFile('location.data')
            if locationInfo != "":
                # calculate line angle from GPS degrees convert to radians, but only if we're moving more than 5mph
                if (int(locationInfo['speed']) > 5):
                    currentDirection = locationInfo['track']
                draw.text((70, 2), str(int(currentDirection)) + "*", font=titleFont, fill=255)
                draw.text((70, 40), str(data.getHeadingByDegrees(currentDirection)), font=bodyFont, fill=255)
                draw.ellipse((2, 2 , 60, 60), outline=255, fill=0)       
                r = radians(currentDirection)
示例#31
0
def test_show():
    device = ssd1306(bus)
    bus.reset()
    device.show()
    assert len(bus.recordings) == 1
    assert bus.recordings[0] == mock.recording(60, 0, [175])
示例#32
0
        oled_device.show()
        visible = True


# Setup to flash a LED on GPIO-14 (TXD)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(14, GPIO.OUT)
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(15, GPIO.RISING, callback=toggle_display, bouncetime=200)

visible = True
port = 1
bus = smbus2.SMBus(port)

oled_device = ssd1306(bus)

bme280.load_calibration_params(bus)
fmt = '{0:5d}:  {1}  {2:0.3f} deg C,  {3:0.2f} hPa,  {4:0.2f} %'
counter = 1
while True:
    GPIO.output(14, True)
    data = bme280.sample(bus)  # Use default address (0x76)
    print(
        fmt.format(counter, data.timestamp, data.temperature, data.pressure,
                   data.humidity))
    with canvas(oled_device) as draw:
        draw.text((0, 0),
                  text=data.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
                  fill=255)
        draw.line((0, 12, 128, 12), fill=255)
示例#33
0
def main():
    oled = ssd1306(port=oled_port, address=oled_address)
    make_decision(oled)
示例#34
0
#!/usr/bin/env python

from oled.device import ssd1306  # 1
from oled.render import canvas
from PIL import ImageFont  # 2
import time

device = ssd1306(port=1, address=0x3C)  # 3
large_font = ImageFont.truetype('FreeMono.ttf', 24)  # 4

x = 0
while True:
    with canvas(device) as draw:  # 5
        draw.pieslice((x, 30, x + 30, 60), 45, -45, fill=255)  # 6
        x += 10  # 7
        if x > 128:
            x = 0
        now = time.localtime()  # 8
        draw.text((0, 0),
                  time.strftime('%H:%M:%S', now),
                  font=large_font,
                  fill=255)
    time.sleep(0.1)
示例#35
0
def main():
    oled = ssd1306(port=1, address=0x3C)
    stats(oled)
示例#36
0
文件: screen.py 项目: foonix/stratux
#!/usr/bin/env python

from oled.device import ssd1306, sh1106
from oled.render import canvas

from PIL import ImageDraw, ImageFont, Image

import urllib2
import json
import time

font2 = ImageFont.truetype('/root/stratux/test/screen/CnC_Red_Alert.ttf', 12)
oled = ssd1306(port=1, address=0x3C)

with canvas(oled) as draw:
    logo = Image.open('/root/stratux/test/screen/logo.bmp')
    draw.bitmap((32, 0), logo, fill=1)

time.sleep(10)

n = 0

while 1:
    time.sleep(1)
    response = urllib2.urlopen('http://localhost/getStatus')
    getStatusHTML = response.read()
    getStatusData = json.loads(getStatusHTML)
    CPUTemp = getStatusData["CPUTemp"]
    uat_current = getStatusData["UAT_messages_last_minute"]
    uat_max = getStatusData["UAT_messages_max"]
    es_current = getStatusData["ES_messages_last_minute"]
示例#37
0
def printoled():
    oled = ssd1306(port=0, address=0x3C)
    stats(oled)
示例#38
0
redPin                 = 36
greenPin               = 40
bluePin                = 38

# setup gpio pins
GPIO.setmode(GPIO.BOARD)
GPIO.setup(laserPin, GPIO.IN)
GPIO.setup(redPin, GPIO.OUT)
GPIO.setup(greenPin, GPIO.OUT)
GPIO.setup(bluePin, GPIO.OUT)

# setup rfid reader
rfid = RFID.RFID(pin_ce=rfidPin)

# setup display and fonts
disp         = ssd1306(port=1, address=0x3C)
defaultFont  = ImageFont.truetype("fonts/Tahoma.ttf", 15)
raceFont     = ImageFont.truetype("fonts/Tahoma.ttf", 35)
timerFont    = ImageFont.truetype("fonts/LCD-N.ttf", 30)

# setup all the led colors with an initial
# duty cycle of 0 which is off
Freq    = 100 #Hz
RED     = GPIO.PWM(redPin, Freq)
GREEN   = GPIO.PWM(greenPin, Freq)
BLUE    = GPIO.PWM(bluePin, Freq)
RED.start(0)
GREEN.start(0)
BLUE.start(0)

# setup AWS IoT
示例#39
0
def main():
    oled = ssd1306(port=oled_port, address=oled_address)
    make_decision(oled)
示例#40
0
#!/usr/bin/env python

import sys
from os.path import dirname, abspath
from oled.device import ssd1306, sh1106
from oled.render import canvas
from PIL import ImageDraw, ImageFont

oled = ssd1306(port=1, address=0x3C, skipinit=True)
font = ImageFont.load_default()
fpath = "%s/fonts/C&C Red Alert [INET].ttf" % (dirname(abspath(__file__)))
font2 = ImageFont.truetype(fpath, 18)
font3 = ImageFont.truetype(fpath, 20)

# Should get about 18 chars on line 1, 12 on lines 2 & 3
with canvas(oled) as draw:
    if len(sys.argv) >= 2:
        draw.text((0, 0), sys.argv[1], font=font2, fill=255)

    if len(sys.argv) >= 3:
        draw.text((0, 20), sys.argv[2], font=font3, fill=255)

    if len(sys.argv) >= 4:
        draw.text((0, 46), sys.argv[3], font=font3, fill=255)
示例#41
0
def lcdControlProc(lcd_child_conn):
    p = current_process()
    logger = logging.getLogger("ispresso").getChild("lcdControlProc")
    logger.info('Starting:' + p.name + ":" + str(p.pid))

    #lcd = lcddriver.lcd()
    lcd = ssd1306(port=1, address=0x3C)
    font = ImageFont.truetype('courier.ttf', 14)
    font2 = ImageFont.truetype('courier.ttf', 18)

    last_line1 = ""
    last_line2 = ""

    while (True):
        time.sleep(0.25)
        while lcd_child_conn.poll():
            #try:
            #    line1, line2, duration = lcd_child_conn.recv()
            #    if line1 is not None:
            #        if last_line1 != line1:
            #            #lcd.lcd_display_string(line1.ljust(16), 1)
            #            last_line1 = line1
            #            time.sleep(duration)
            #
            #    if line2 is not None:
            #        if last_line2 != line2:
            #            #lcd.lcd_display_string(line2.ljust(16), 2)
            #            last_line2 = line2
            #            time.sleep(duration)

            #except:
            #    exc_type, exc_value, exc_traceback = sys.exc_info()
            #    logger.error(''.join('!! ' + line for line in traceback.format_exception(exc_type, exc_value, exc_traceback)))
            #    subprocess.call(['i2cdetect', '-y', '1'])
            #    try:
            #        lcd = None
            #        time.sleep(0.1)
            #        #lcd = lcddriver.lcd()
            #        time.sleep(0.1)
            #    except:
            #        logger.error("Trying to re-initialize the LCD by nulling it out and re-instantiating.  Couldln't pull it off :(")
            #    continue
            with canvas(lcd) as draw:
                  line1, line2, duration = lcd_child_conn.recv()
                  if line1 is not None:
                     if last_line1 != line1:
            #            #lcd.lcd_display_string(line1.ljust(16), 1)
                        last_line1 = line1
            #            time.sleep(duration)
            #
                  if line2 is not None:
                     if last_line2 != line2:
            #            #lcd.lcd_display_string(line2.ljust(16), 2)
                         last_line2 = line2
            #            time.sleep(duration)
                  padding = 0
                  shape_width = 20
                  top = padding
                  bottom = lcd.height - padding - 1
                  draw.text((1, top),   last_line1,  font=font, fill=255)
                  draw.text((1, top+16), last_line2, font=font2, fill=255)
                  time.sleep(duration)
    sSecond = str(PyTime.tm_sec)
    if (PyTime.tm_sec < 10):
        sSecond = "0" + sSecond

    TheFileName = sYear + sMonth + sDay + str(sHour) + str(sMinute) + str(
        sSecond)

    return TheFileName


# ********************************************************************* main()
# initialize I2C interface
serial = i2c(port=1, address=0x3C)

# Acrobotic SSD1306 128x64 pixels Blue/Yellow Font is 6 x 11
device = ssd1306(serial, width=128, height=64, rotate=0)

# setup GPIO using BCM numbering
GPIO.setmode(GPIO.BCM)

# Pin assignments
logPin = 26  # start logging to file
sbyPin = 19  # standby
hltPin = 13  # exit program

# all logging modes will be selected when HIGH
GPIO.setup(logPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(sbyPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(hltPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# init logging parameters
示例#43
0
def display_process(volumeSync, textSync, text2Sync, playingSync):
    try:
        device = ssd1306(port=1, address=0x3C)

        text = textSync.value
        lastText = text
        offset = 0
        text2offset = 0
        textHeight = 20
        font = ImageFont.truetype('bold_dot_digital-7.ttf', textHeight)

        while (1):
            text = textSync.value
            text2 = text2Sync.value.upper().strip()

            playing = playingSync.value
            volume = volumeSync.value

            bg = 0
            fg = 255

            if lastText != text:
                offset = 0

            textLength = font.getsize("%s " % text)[0]

            # Something nasty - with the font or PIL? Adds in extra gap at the end
            text2Length = font.getsize("%s " % text2)[0] - 16


            text2offset = int(round((device.width/2) - (text2Length/2)))




            if text:
                displayText = "%s %s" % (text, text)
            else:
                displayText = ""

            with canvas(device) as draw:




                # Draw some shapes.
                # First define some constants to allow easy resizing of shapes.
                padding = 2
                top = padding
                # Draw a rectangle of the same size of screen
                #draw.rectangle((0, 0, device.width-1, device.height-1), outline=255, fill=0)
                #draw.rectangle((15, 0, device.width-16, device.height-1), outline=255, fill=0)



                playGap = 14

                # Volume area
                draw.rectangle((0, 0, (device.width - 1) - playGap - padding, 15), outline=255, fill=0)
                volperc = round(((device.width - (playGap + 2 + padding)) * volume) / 100)
                draw.rectangle((0, 1, volperc, 15), outline=255, fill=255)


                # draw.rectangle((0, 16, device.width - 1, device.height - 1), outline=bg, fill=bg)

                x = padding
                # Write two lines of text.
                #draw.rectangle((text2offset, (top + 15 + (padding*2) + textHeight ), text2offset + text2Length, device.height-1), outline=255, fill=0)
                draw.text((x - offset, top + 18), displayText, font=font, fill=fg)
                draw.text((text2offset, top + 15 + (padding*5) + textHeight ), text2, font=font, fill=fg)


                # Play  / Paused

                startx = device.width + padding - playGap
                starty = 2

                if playing == 1:
                    playheight = 9
                    playwidth = 8

                    definition = [(startx, starty + playheight), (startx, starty),
                                  (startx + playwidth, (1 + starty + int(playheight / 2)))]
                    draw.polygon(definition, outline=255, fill=255)

                elif playing == 0:

                    barwidth = 3
                    barheight = 9
                    bargap = 3

                    draw.rectangle((startx, starty, startx + barwidth, starty + barheight), outline=255, fill=255)
                    draw.rectangle((startx + barwidth + bargap, starty, startx + barwidth + barwidth + bargap,
                                    starty + barheight), outline=255, fill=255)


                else:
                    # Off
                    draw.rectangle((0, 0, device.width-1, device.height-1), outline=0, fill=0)







            offset += 7
            if offset > textLength:
                offset = 0

            lastText = text
            time.sleep(0.25)
    except (KeyboardInterrupt, SystemExit):

        with canvas(device) as draw:
            draw.rectangle((0, 0, (device.width - 1), device.height - 1), outline=0, fill=0)
        print "Exiting Display Process"
示例#44
0
from oled.device import ssd1306, sh1106
from oled.render import canvas
from PIL import ImageFont, ImageDraw

device = ssd1306(port=0, address=0x3C)  # rev.1 users set port=0
with canvas(device) as draw:
    #font = ImageFont.load_default()
    font = ImageFont.truetype('./ssd1306/fonts/Volter__28Goldfish_29.ttf', 20)
    #    draw.text((0, 0), "Hello World", font=font, fill=255)
    draw.point((9, 9), fill=255)
示例#45
0
#!/usr/bin/env python

import sys
from os.path import dirname, abspath
from oled.device import ssd1306, sh1106
from oled.render import canvas
from PIL import ImageDraw, ImageFont

oled = ssd1306(port=1, address=0x3C, skipinit=True)
font = ImageFont.load_default()
fpath = "%s/fonts/C&C Red Alert [INET].ttf" % (dirname(abspath(__file__)))
font2 = ImageFont.truetype(fpath, 18)
font3 = ImageFont.truetype(fpath, 20)

# Should get about 18 chars on line 1, 12 on lines 2 & 3
with canvas(oled) as draw:
    if len(sys.argv) >= 2:
        draw.text((0, 0), sys.argv[1], font=font2, fill=255)
        
    if len(sys.argv) >= 3:
        draw.text((0, 20), sys.argv[2], font=font3, fill=255)
        
    if len(sys.argv) >= 4:
        draw.text((0, 46), sys.argv[3], font=font3, fill=255)
示例#46
0
文件: screen.py 项目: jamez70/stratux
    def run(self):
        font2 = ImageFont.truetype('/etc/stratux-screen/CnC_Red_Alert.ttf', 12)
        oled = ssd1306(port=1, address=0x3C)

        with canvas(oled) as draw:
            logo = Image.open('/etc/stratux-screen/stratux-logo-64x64.bmp')
            draw.bitmap((32, 0), logo, fill=1)

        time.sleep(10)
        n = 0

        while 1:
            time.sleep(1)
            response = urllib2.urlopen('http://localhost/getStatus')
            getStatusHTML = response.read()
            getStatusData = json.loads(getStatusHTML)
            CPUTemp = getStatusData["CPUTemp"]
            uat_current = getStatusData["UAT_messages_last_minute"]
            uat_max = getStatusData["UAT_messages_max"]
            es_current = getStatusData["ES_messages_last_minute"]
            es_max = getStatusData["ES_messages_max"]
    
            response = urllib2.urlopen('http://localhost/getTowers')
            getTowersHTML = response.read()
            getTowersData = json.loads(getTowersHTML)
            NumTowers = len(getTowersData)

            with canvas(oled) as draw:
                pad = 2 # Two pixels on the left and right.
                text_margin = 25
                # UAT status.
                draw.text((50, 0), "UAT", font=font2, fill=255)
                # "Status bar", 2 pixels high.
                status_bar_width_max = oled.width - (2 * pad) - (2 * text_margin)
                status_bar_width = 0
                if uat_max > 0:
                    status_bar_width = int((float(uat_current) / uat_max) * status_bar_width_max)
                draw.rectangle((pad + text_margin, 14, pad + text_margin + status_bar_width, 20), outline=255, fill=255) # Top left, bottom right.
                # Draw the current (left) and max (right) numbers.
                draw.text((pad, 14), str(uat_current), font=font2, fill=255)
                draw.text(((2*pad) + text_margin + status_bar_width_max, 14), str(uat_max), font=font2, fill=255)
                # ES status.
                draw.text((44, 24), "1090ES", font=font2, fill=255)
                status_bar_width = 0
                if es_max > 0:
                    status_bar_width = int((float(es_current) / es_max) * status_bar_width_max)
                draw.rectangle((pad + text_margin, 34, pad + text_margin + status_bar_width, 40), outline=255, fill=255) # Top left, bottom right.
                # Draw the current (left) and max (right) numbers.
                draw.text((pad, 34), str(es_current), font=font2, fill=255)
                draw.text(((2*pad) + text_margin + status_bar_width_max, 34), str(es_max), font=font2, fill=255)
                # Other stats.
                seq = (n / 5) % 2
                t = ""
                if seq == 0:
                    t = "CPU: %0.1fC, Towers: %d" % (CPUTemp, NumTowers)
                if seq == 1:
                    t = "GPS Sat: %d/%d/%d" % (getStatusData["GPS_satellites_locked"], getStatusData["GPS_satellites_seen"], getStatusData["GPS_satellites_tracked"])
                    if getStatusData["GPS_solution"] == "GPS + SBAS (WAAS / EGNOS)":
                        t = t + " (WAAS)"
                #print t
                draw.text((pad, 45), t, font=font2, fill=255)

            n = n+1
def main():
    oled = ssd1306(port=1, address=0x3C)
    stats(oled)
    prGreen(scriptname) ; prGreen(scriptversion) ; prYellow("Sending Frame of Test Data to SSD1306 OLED over i2C")