示例#1
0
	def __init__(self, rows=64, cols=128, i2c_address=0x3d, i2c_port=1):

		self.i2c_address = i2c_address
		self.i2c_port = i2c_port

		self.rows = rows
		self.cols = cols

		self.fb = [[]]

		# Initialize the default font
		font = fonts.bmfont.bmfont('latin1_5x8_fixed.fnt')
		self.fp = font.fontpkg

		serial = i2c(port=i2c_port, address=i2c_address)
		self.device = ssd1306(serial)
示例#2
0
def getDisplay(config, name):
    if config['type'] == 'i2c':
        from luma.core.interface.serial import i2c
        serial = i2c(port=config['bus'], address=config['address'])
    # TODO: Add SPI/BB support
    if config['config']['type'] == 'ssd1306':
        from luma.oled.device import ssd1306
        reference = ssd1306
        display = reference(serial, rotate=config['config']['rotate'])
    # add support for other displays
    else:
        return (None)

    # save reference and name in display
    display.reference = reference
    display.name = name

    # overwrite the display method
    def display_(self, data):
        # dont write the data to the display. First save it in the thread
        self.thread.setData(data, self.name)

    display.display = display_
    return (display)
示例#3
0
def test_init_device_address_error():
    address = 'foo'
    with pytest.raises(luma.core.error.DeviceAddressError) as ex:
        i2c(address=address)
    assert str(ex.value) == 'I2C device address invalid: {}'.format(address)
示例#4
0
def test_i2c_data_chunked():
    data = list(fib(100))
    serial = i2c(bus=smbus, address=0x66)
    serial.data(data)
    calls = [call(0x66, 0x40, data[i:i + 32]) for i in range(0, 100, 32)]
    smbus.write_i2c_block_data.assert_has_calls(calls)
示例#5
0
文件: oled.py 项目: eragefe/pi4
import time
import subprocess
from socket import error as socket_error
import os.path
import RPi.GPIO as GPIO

from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106
from mpd import MPDClient, MPDError, CommandError, ConnectionError

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

serial = i2c(port=1, address=0x3C)
device = sh1106(serial, rotate=0)

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
GPIO.output(17, GPIO.HIGH)

os.system('echo 22 > /sys/class/gpio/export')
os.system('echo out > /sys/class/gpio/gpio22/direction')
os.system('echo 1 > /sys/class/gpio/gpio22/value')


class MPDConnect(object):
    def __init__(self, host='localhost', port=6600):
示例#6
0
#!/usr/bin/env python
import time, sys, os, glob, subprocess
from luma.core.sprite_system import framerate_regulator
from time import sleep
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import subprocess
brite = 50
#----------------------------LUMA SETUP-----------------------------------------
from luma.core.interface.serial import i2c, spi
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106

botserial = i2c(port=1, address=0x3D)
# substitute ssd1331(...) or sh1106(...) below if using that device
disp = sh1106(botserial)
topserial = i2c(port=1, address=0x3C)
disptop = sh1106(topserial)
#----------------------------------------------

# Raspberry Pi pin configuration:
RST = None
line1 = str()
#------------------------------- PI INPUTS ---------------------------------
# pull up GPIO23-25 (tact switches)
up = 0
down = 0
select = 0
a = 1
import RPi.GPIO as GPIO
示例#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=', '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)
示例#8
0
 def _off(self):
     self.next.clear()
     serial = i2c(port=1, address=0x3c)
     device = ssd1306(serial)  #挂载设备
     device.cleanup()
示例#9
0
list_clk = 27
list_dt = 22
list_sw = 17
vol_clk = 4
vol_dt = 18
vol_sw = 23
conf_push = 12
preset_sw: list = [[21, 0], [20, 0], [16, 0], [13, 0], [19, 0], [26, 0]]

# Preset assigned to radio buttons
# ----------------------------------------------------------
preset_list: list = [0, 0, 0, 0, 0, 0]

# Setup OLED display
# ----------------------------------------------------------
serial = i2c(port=1, address=0x3C)  #default value
device = sh1106(serial, rotate=0)

# File for song info
# ----------------------------------------------------------
songFile = open('/home/pi/WoodStream/radio_info.txt', 'r')

# Lock for display competition
# ----------------------------------------------------------
sem = threading.Lock()


def readRadioList():
    """
    Reads radio URLS and names from text file
    Format: (preset.)Radio name|Radio URL
示例#10
0
def test_command():
    cmds = [3, 1, 4, 2]
    serial = i2c(bus=smbus, address=0x83)
    serial.command(*cmds)
    smbus.write_i2c_block_data.assert_called_once_with(0x83, 0x00, cmds)
示例#11
0
def test_init_bus_provided():
    i2c(bus=smbus, address=0x71)
    smbus.open.assert_not_called()
示例#12
0
def test_i2c_data():
    data = list(fib(10))
    serial = i2c(bus=smbus, address=0x21)
    serial.data(data)
    smbus.write_i2c_block_data.assert_called_once_with(0x21, 0x40, data)
示例#13
0
 def __init__(self, ssd1306address, threshold, rotation):
     serial = i2c(port=1, address=ssd1306address)
     self.image_threshold = threshold
     self.device = ssd1306(serial, rotate=rotation)
     self.background = Image.new(self.device.mode, self.device.size, 'black')
     logging.info("Display with {}x{} Pixel".format(self.device.width, self.device.height))
示例#14
0
 def plugin_init(self,enableplugin=None):
  plugin.PluginProto.plugin_init(self,enableplugin)
  if self.enabled:
   if self.taskdevicepin[0]>=0:
    try:
     gpios.HWPorts.remove_event_detect(int(self.taskdevicepin[0]))
    except:
     pass
    try:
     self.btntime = 0
     self.btnval = -1
     self.initval = int(gpios.HWPorts.input(int(self.taskdevicepin[0])))
     gpios.HWPorts.add_event_detect(int(self.taskdevicepin[0]),gpios.BOTH,self.p036_handler)
    except:
     pass
   try:
     i2cl = self.i2c
   except:
     i2cl = -1
   try:
    i2cport = gpios.HWPorts.geti2clist()
    if i2cl==-1:
      i2cl = int(i2cport[0])
   except:
    i2cport = []
   if len(i2cport)>0 and i2cl>-1:
    if self.interval>2:
      nextr = self.interval-2
    else:
      nextr = self.interval

    self.initialized = False
    serialdev = None
    self.taskdevicepluginconfig[1] = int(float(self.taskdevicepluginconfig[1]))
    if self.taskdevicepluginconfig[1] != 0: # i2c address
     serialdev = i2c(port=i2cl, address=self.taskdevicepluginconfig[1])
    else:
     return self.initialized
    self.device = None
    try:
     if "x" in str(self.taskdevicepluginconfig[3]):
      resstr = str(self.taskdevicepluginconfig[3]).split('x')
      self.width = int(resstr[0])
      self.height = int(resstr[1])
     else:
      self.width  = None
      self.height = None
    except:
     self.width  = None
     self.height = None

    if str(self.taskdevicepluginconfig[0]) != "0" and str(self.taskdevicepluginconfig[0]).strip() != "": # display type
     try:
      if str(self.taskdevicepluginconfig[0])=="ssd1306":
       from luma.oled.device import ssd1306
       if self.height is None:
        self.device = ssd1306(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])))
       else:
        self.device = ssd1306(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])), width=self.width, height=self.height)
       self.initialized = True
      elif str(self.taskdevicepluginconfig[0])=="sh1106":
       from luma.oled.device import sh1106
       if self.height is None:
        self.device = sh1106(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])))
       else:
        self.device = sh1106(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])), width=self.width, height=self.height)
       self.initialized = True
      elif str(self.taskdevicepluginconfig[0])=="ssd1309":
       from luma.oled.device import ssd1309
       if self.height is None:
        self.device = ssd1309(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])))
       else:
        self.device = ssd1309(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])), width=self.width, height=self.height)
       self.initialized = True
      elif str(self.taskdevicepluginconfig[0])=="ssd1331":
       from luma.oled.device import ssd1331
       if self.height is None:
        self.device = ssd1331(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])))
       else:
        self.device = ssd1331(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])), width=self.width, height=self.height)
       self.initialized = True
      elif str(self.taskdevicepluginconfig[0])=="ssd1351":
       from luma.oled.device import ssd1351
       if self.height is None:
        self.device = ssd1351(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])))
       else:
        self.device = ssd1351(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])), width=self.width, height=self.height)
       self.initialized = True
      elif str(self.taskdevicepluginconfig[0])=="ssd1322":
       from luma.oled.device import ssd1322
       if self.height is None:
        self.device = ssd1322(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])))
       else:
        self.device = ssd1322(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])), width=self.width, height=self.height)
       self.initialized = True
      elif str(self.taskdevicepluginconfig[0])=="ssd1325":
       from luma.oled.device import ssd1325
       if self.height is None:
        self.device = ssd1325(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])))
       else:
        self.device = ssd1325(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])), width=self.width, height=self.height)
       self.initialized = True
      elif str(self.taskdevicepluginconfig[0])=="ssd1327":
       from luma.oled.device import ssd1327
       if self.height is None:
        self.device = ssd1327(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])))
       else:
        self.device = ssd1327(serialdev, rotate=int(float(self.taskdevicepluginconfig[2])), width=self.width, height=self.height)
       self.initialized = True
     except Exception as e:
      misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"OLED can not be initialized! "+str(e))
      self.enabled = False
      self.device = None
      return False
    if self.device is not None:
     try:
      lc = int(self.taskdevicepluginconfig[4])
      self.width = self.device.width
      self.height = self.device.height
     except:
      lc = 1
     if lc < 1:
      lc = 1
     elif lc>4:
      lc = 4
     try:
      defh = 10
      if self.height!=64: # correct y coords
       defh = int(defh * (self.height/64))

      self.hfont=ImageFont.truetype('img/UbuntuMono-R.ttf', defh)
      lineheight=11
      if lc==1:
       lineheight = 24
       self.ypos = [20,0,0,0]
      elif lc==2:
       lineheight = 16
       self.ypos = [15,34,0,0]
      elif lc==3:
       lineheight = 12
       self.ypos = [13,25,37,0]
      elif lc==4:
       lineheight = 10
       self.ypos = [12,22,32,42]

      if self.height!=64: # correct y coords
       for p in range(len(self.ypos)):
        self.ypos[p] = int(self.ypos[p] * (self.height/64))
       lineheight = int(lineheight * (self.height/64))

      self.ufont=ImageFont.truetype('img/UbuntuMono-R.ttf', lineheight) # use size
     except Exception as e:
      print(e)
     try:
      self.device.show()
      self.displaystate = 1
     except:
      self.displaystate = 0
     if self.interval>2:
       nextr = self.interval-2
     else:
       nextr = 0
     self._lastdataservetime = rpieTime.millis()-(nextr*1000)
     try:
       self.dispimage = Image.new('1', (self.device.width,self.device.height), "black")
       self.conty1 = 12
       if self.height!=64: # correct y coords
        self.conty1 = int(self.conty1 * (self.height/64))
       self.conty2 = self.device.height-self.conty1
       self.textbuffer = []
       self.actualpage = 0
       self.lastlineindex = self.P36_Nlines
       for l in reversed(range(self.P36_Nlines)):
        if (str(self.lines[l]).strip()!="") and (str(self.lines[l]).strip()!="0"):
         self.lastlineindex = l
         break
       try:
        self.pages = math.ceil((self.lastlineindex+1) / int(self.taskdevicepluginconfig[4]))
       except:
        self.pages = 0
     except Exception as e:
      self.initialized = False
     try:
      cont = int(self.taskdevicepluginconfig[6])
     except:
      cont = 0
     if cont>0:
      self.device.contrast(cont)

     draw = ImageDraw.Draw(self.dispimage)
     maxcols = int(self.taskdevicepluginconfig[7]) # auto decrease font size if needed
     if maxcols < 1:
       maxcols = 1
     tstr = "X"*maxcols
     try:
       sw = draw.textsize(tstr,self.ufont)[0]
     except:
       sw = self.device.width
     while (sw>self.device.width):
       lineheight-=1
       self.ufont=ImageFont.truetype('img/UbuntuMono-R.ttf', lineheight)
       sw = draw.textsize(tstr,self.ufont)[0]
     self.writeinprogress = 0
    else:
     self.initialized = False
  else:
   self.plugin_exit()
示例#15
0
 def __init__(self):
     self.serial = i2c(port=1, address=0x3C)
     self.device = ssd1306(self.serial)
     self.chinese_font = ImageFont.truetype('NotoSansSC-Regular.ttf', 17)
示例#16
0
from luma.core.render import canvas
from PIL import ImageFont, ImageDraw
import serial
import time
import keypad as key
import nmcli
from ESPSSD import Screen
key.Setup()

enableGPS = "XIO-P0"
GPIO.setup(enableGPS, GPIO.OUT, initial=1)
GPIO.output(enableGPS, GPIO.LOW)  #pull GND pin NEO-6M down to enable module
print "GPS enabled............."
time.sleep(2)

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

GPGLL = ""  #Geographic Position, Latitude / Longitude and time
GPRMC = ""  #Recommended minimum specific GPS/Transit data
GPVTG = ""  #Track made good and ground speed
GPGGA = ""  #Global Positioning System Fix Data
GPGSA = ""  #GPS DOP and active satellites
GPGSV = ""  #GPS Satellites in view
timeZone = 1
speed = "0"
Latitude = "XXXXXXXXXXXX"
Longitude = "XXXXXXXXXXXXX"
utc = "XX:XX:XX"
fix = "0"
button = 0
示例#17
0
def main(argv):

    # Check and get arguments
    try:
        options, remainder = getopt.getopt(argv, '', [
            'help', 'i2c-port=', 'i2c-address=', 'display=', 'display-width=',
            'display-height=', 'room=', '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 ('--i2c-port'):
            s.i2c_port = arg
        elif opt in ('--i2c-address'):
            s.i2c_address = int(arg, 16)
        elif opt in ('--display'):
            if arg not in ['sh1106', 'ssd1306']:
                print 'Unknown display type (choose between \'sh1106\' and \'ssd1306\')'
                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 ('--room'):
            if arg not in ['RRF', 'TEC', 'FON']:
                print 'Unknown room name (choose between \'RRF\', \'TEC\' and \'FON\')'
                sys.exit()
            s.room = arg
        elif opt in ('--latitude'):
            s.latitude = float(arg)
        elif opt in ('--longitude'):
            s.longitude = float(arg)

    # Set serial
    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)
    else:
        s.device = ssd1306(serial,
                           width=s.display_width,
                           height=s.display_height,
                           rotate=0)

    # Set url
    if s.room == 'RRF':
        url = 'http://rrf.f5nlg.ovh/api/svxlink/RRF'
    elif s.room == 'TEC':
        url = 'http://rrf.f5nlg.ovh/api/svxlink/technique'
    elif s.room == 'FON':
        url = 'http://fon.f1tzo.com:81'

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

    while (True):

        # If midnight...
        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.now[:5] == '00:00'):
            s.qso_total += s.qso
            s.qso = 0
            for q in xrange(0, 24):  # Clean histogram
                s.qso_hour[q] = 0
            s.history.clear()  # Clear history

        # Request HTTP datas
        try:
            r = requests.get(url, verify=False, timeout=10)
            page = r.content
        except requests.exceptions.ConnectionError as errc:
            print('Error Connecting:', errc)
        except requests.exceptions.Timeout as errt:
            print('Timeout Error:', errt)

        search_start = page.find('TXmit":"')  # Search this pattern
        search_start += 8  # Shift...
        search_stop = page.find('"', search_start)  # And close it...

        # If transmitter...
        if search_stop != search_start:

            if s.transmit is False:  # Wake up screen...
                s.transmit = l.wake_up_screen(s.device, s.display, s.transmit)

            # Clean call
            tmp = page[search_start:search_stop]
            tmp = tmp.replace('(', '')
            tmp = tmp.replace(') ', ' ')
            tmp = tmp.replace('\u0026U', '&')  # Replace ampersand...

            s.call_current = tmp

            if (s.call_previous != s.call_current):
                s.tot_start = time.time()
                s.tot_current = s.tot_start
                s.call_previous = s.call_current

                for i in xrange(4, 0, -1):
                    s.call[i] = s.call[i - 1]
                    s.call_time[i] = s.call_time[i - 1]

                s.call[0] = s.call_current
            else:
                if s.tot_start is '':
                    s.tot_start = time.time()
                    s.tot_current = s.tot_start

                    for i in xrange(4, 0, -1):
                        s.call[i] = s.call[i - 1]
                        s.call_time[i] = s.call_time[i - 1]

                    s.call[0] = s.call_current
                else:
                    s.tot_current = time.time()

            s.duration = int(s.tot_current) - int(s.tot_start)

            # Save stat only if real transmit
            if (s.stat_save is False and s.duration > 2):
                s.history = l.save_stat(s.history, s.call[0])
                s.qso += 1
                s.stat_save = True

            # Format call time
            tmp = datetime.datetime.now()
            s.now = tmp.strftime('%H:%M:%S')
            s.hour = int(tmp.strftime('%H'))

            s.qso_hour[s.hour] = s.qso - sum(s.qso_hour[:s.hour])

            s.call_time[0] = s.now

            s.message[0] = s.call[2]
            s.message[1] = s.call[1]
            s.message[2] = s.call[0]

        # If no Transmitter...
        else:
            if s.transmit is True:  # Sleep screen...
                s.transmit = l.wake_up_screen(s.device, s.display, s.transmit)
                s.stat_save = False
                s.tot_current = ''
                s.tot_start = ''

            s.message[0] = s.call[1]
            s.message[1] = s.call[0]
            if s.qso == 0:
                s.call_time[0] = 'Waiting TX'
                s.message[2] = s.call_time[0]
            else:
                s.message[2] = 'Last TX ' + s.call_time[0]

        if (s.blanc_alternate == 0):  # TX today
            tmp = 'TX Today '
            tmp += str(s.qso)

            s.message[4] = tmp

            s.blanc_alternate = 1

        elif (s.blanc_alternate == 1):  # Boot time
            tmp = 'Up '
            tmp += l.calc_uptime(time.time() - s.timestamp_start)

            s.message[4] = tmp

            s.blanc_alternate = 2

        elif (s.blanc_alternate == 2):  # TX total
            tmp = 'TX Total '
            tmp += str(s.qso_total + s.qso)

            s.message[4] = tmp

            s.blanc_alternate = 3

        elif (s.blanc_alternate == 3):  # Best link
            if len(s.history) >= 5:
                best = max(s.history, key=s.history.get)
                s.message[4] = best + ' ' + str(s.history[best]) + ' TX'
            else:
                s.message[4] = 'Need more datas'

            s.blanc_alternate = 4

        elif (s.blanc_alternate == 4):  # count node

            search_start = page.find('nodes":[')  # Search this pattern
            search_start += 9  # Shift...
            search_stop = page.find('],"TXmit"',
                                    search_start)  # And close it...

            tmp = page[search_start:search_stop]

            tmp = tmp.split(',')

            s.message[4] = 'Online nodes ' + str(len(tmp))

            s.blanc_alternate = 0

        # Print screen
        if s.device.height == 64:
            d.display_64()
        else:
            d.display_32()

        time.sleep(2)
示例#18
0
    full_Data += stringData
# print(full_Data)

data= base64.b64decode(full_Data)
print(data)
s.close()
nparr = numpy.frombuffer(data,dtype='uint8')
decimg=cv2.imdecode(nparr,0)
"""

n_rows = 3
n_images_per_row = 3
width = 384
height = 192
dim = (width, height)
serial9 = i2c(port=11, address=0x3C)
device9 = ssd1306(serial9)
serial8 = i2c(port=10, address=0x3C)
device8 = ssd1306(serial8)
serial7 = i2c(port=9, address=0x3C)
device7 = ssd1306(serial7)
serial6 = i2c(port=8, address=0x3C)
device6 = ssd1306(serial6)
serial5 = i2c(port=7, address=0x3C)
device5 = ssd1306(serial5)
serial4 = i2c(port=6, address=0x3C)
device4 = ssd1306(serial4)
serial3 = i2c(port=5, address=0x3C)
device3 = ssd1306(serial3)
serial2 = i2c(port=4, address=0x3C)
device2 = ssd1306(serial2)
示例#19
0
文件: demo.py 项目: CM44/dockerfiles
#!/usr/bin/env python

from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import ssd1306

serial = i2c(port=1, address=0x3C)
device = ssd1306(serial)
device.cleanup = lambda _: None

with canvas(device) as draw:
    draw.rectangle(device.bounding_box, outline="white", fill="black")
    draw.text((30, 40), "Hello World", fill="white")
示例#20
0
def main():
    time.sleep(10)
    serial = i2c(port=1, address=0x3C)
    oled = sh1106(serial)
    stats(oled)
    time.sleep(60 * 60)
示例#21
0
 def i2c(self):
     from luma.core.interface.serial import i2c
     return i2c(port=self.opts.i2c_port, address=self.opts.i2c_address)
示例#22
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)
示例#23
0
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import sh1106

print("""This Pimoroni Breakout Garden example requires an
LSM303D 6DoF Breakout and a 1.12" OLED Breakout.

The Dino-Detect v1.2 beta is a dino stomp detector. It's a
UNIX system, I know this.

Press Ctrl+C to exit.
""")

# Set up OLED

oled = sh1106(i2c(port=1, address=0x3C), rotate=2, height=128, width=128)

# Load fonts

rr_path = os.path.abspath(
    os.path.join(os.path.dirname(__file__), 'fonts', 'Roboto-Regular.ttf'))
print(rr_path)
rb_path = os.path.abspath(
    os.path.join(os.path.dirname(__file__), 'fonts', 'Roboto-Black.ttf'))
rr_24 = ImageFont.truetype(rr_path, 24)
rb_20 = ImageFont.truetype(rb_path, 20)
rr_12 = ImageFont.truetype(rr_path, 12)

# Set up LSM303D motion sensor

lsm = LSM303D(0x1d)
示例#24
0
    exc = sys.exc_info()[0]
    stack = traceback.extract_stack()[:-1]  # last one would be full_stack()
    if exc is not None:  # i.e. an exception is present
        del stack[-1]  # remove call of full_stack, the printed exception
        # will contain the caught exception caller instead
    trc = 'Traceback (most recent call last):\n'
    stackstr = trc + ''.join(traceback.format_list(stack))
    if exc is not None:
        stackstr += '  ' + traceback.format_exc().lstrip(trc)
    return stackstr


def main(device):
    while True:
        show_info(device)
        time.sleep(5)


if __name__ == "__main__":
    try:
        my_logger.debug('Weathercaster: remote_all Starting ')
        serial = i2c(port=bus_number, address=0x3C)
        device = ssd1306(serial)

        main(device)
    except KeyboardInterrupt:
        my_logger.debug("Weathercaster: remote_all Stopping(Ctrl + C) ")
        pass
    finally:
        my_logger.debug("Weathercaster remote_all exit trace: " + full_stack())
示例#25
0
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import ssd1309
import RPi.GPIO as GPIO  # Import the GPIO module as 'GPIO'
from hcsr04sensor import sensor

import time

serial = i2c(port=1, address=0x3C)  # Set I2C interface
device = ssd1309(serial)  # load the display reference
GPIO.setmode(GPIO.BCM)  # Set the GPIO mode to BCM numbering

trig4 = 23  # mid right
echo4 = 24
trig5 = 13  # far right
echo5 = 19
trig3 = 5  # behind
echo3 = 6
trig2 = 8  # mid left
echo2 = 7
trig1 = 21  # far left
echo1 = 20
configFill = "black"


def draw_display(dist1, dist2, dist3, dist4, dist5):
    try:
        with canvas(device) as draw:
            # First we check for 9-12 ft range, then 6-9, then 0-6.
            #print("sensor 1 is: ", dist1)
            #print("sensor 2 is: ", dist2)
示例#26
0
    test_requirements()

# Setup temp sensor
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

# Setup defaults
flush_counter = args.flush
line_counter = 1
interval = args.interval
flush_off = args.flush_off
exit_on_error = False if args.exit_on_error is False else True

CSV_PATH = '' if args.output_file is False else args.output_file

SERIAL = i2c(port=1, address=0x3C)
oled_device = ssd1306(SERIAL, rotate=2)
oled_device.contrast(5)

# check what output should be initialised
cli_output = False if args.output_file is not False and args.print is False else True
csv_output = False if args.output_file is False else args.output_file
oled_output = False if args.screen is False else True

# Setup CSV output

if csv_output is not False:
    try:
        csv_file = open(CSV_PATH, 'a+')
        if os.stat(CSV_PATH).st_size == 0:
            csv_file.write('Date,Time,Temperature,Humidity\r\n')
import sqlalchemy
import datetime
import pathlib
import json
import smbus
import logging
import pynmea2


################## config GPRS via FONA ##################
target_url = "https://80overland.com/gps_logger.php"



################## config display ##################
device = sh1106(i2c(port=1, address=0x3c), rotate=0)
device.clear()
global pending_redraw
pending_redraw = False

### setup different fonts
FA_solid = ImageFont.truetype('/home/pi/Desktop/fonts/fa-solid-900.ttf', 12)
FA_solid_largest = ImageFont.truetype('/home/pi/Desktop/fonts/fa-solid-900.ttf', 40)
text_largest = ImageFont.truetype('/home/pi/Desktop/fonts/digital-7.ttf', 58)
text_medium = ImageFont.truetype('/home/pi/Desktop/fonts/digital-7.ttf', 24)
text_small = ImageFont.truetype('/home/pi/Desktop/fonts/digital-7.ttf', 12)
 
### Initialize drawing zone (aka entire screen)
output = Image.new("1", (128,64))
add_to_image = ImageDraw.Draw(output)
 def __init__(self):
     self.serial = i2c(port=1, address=0x3C)
     self.device = ssd1306(self.serial, rotate=0)
     self._meters_running = False
     self._scrolling_text_running = False
示例#29
0
def test_cleanup():
    serial = i2c(bus=smbus, address=0x9F)
    serial._managed = True
    serial.cleanup()
    smbus.close.assert_called_once_with()
from luma.core.interface.serial import i2c, spi, pcf8574
from luma.core.interface.parallel import bitbang_6800
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1309, ssd1325, ssd1331, sh1106, ws0010

import RPi.GPIO as GPIO
GPIO.setwarnings(False)

serial_i2c = i2c(port=1, address=0x3C)
serial_spi = spi(device=0, port=0)

# substitute ssd1331(...) or sh1106(...) below if using that device
device_i2c = sh1106(serial_i2c)
device_spi = ssd1306(serial_spi)

# with is een contextmanager die __enter__() en __exit__() methodes aanroept bi jstart en einde

with canvas(device_spi) as draw:
    draw.rectangle(device_spi.bounding_box, outline="white", fill="black")
    draw.text((10, 40), ">Hello World SPI", fill="white")

with canvas(device_i2c) as draw:
    draw.rectangle(device_i2c.bounding_box, outline="white", fill="black")
    draw.text((10, 40), ">Hello World I2C", fill="white")
示例#31
0
def test_init_no_bus():
    with patch.object(smbus2.SMBus, 'open') as mock:
        i2c(port=2, address=0x71)
    mock.assert_called_once_with(2)
示例#32
0
import random
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import sh1106
from PIL import ImageFont, Image, ImageDraw
import pymysql
import csv
import json
import hashlib
import pynmea2
from haversine import haversine, Unit
config = configparser.ConfigParser()
config.read('/home/pi/Desktop/car_computer.ini')

################## start display ##################
device = sh1106(i2c(port=1, address=config['display']['i2c_port']), rotate=0)
device.clear()
pending_redraw = False
output = Image.new("1", (128, 64))
add_to_image = ImageDraw.Draw(output)


def setup_font(font_filename, size):
    return ImageFont.truetype(
        os.path.join(config['general']['folder'],
                     config['general']['folder_fonts'], font_filename), size)


fa_solid = setup_font(config['general']['font_icons'], 12)
fa_solid_largest = setup_font(config['general']['font_icons'], 40)
text_largest = setup_font(config['general']['font_texts'], 58)
示例#33
0
    def run(self):
        font2 = ImageFont.truetype('/etc/stratux-screen/CnC_Red_Alert.ttf', 12)
        serial = i2c(port=1, address=0x3c)
        oled = ssd1306(serial)

        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
示例#34
0
    def plugin_init(self, enableplugin=None):
        plugin.PluginProto.plugin_init(self, enableplugin)
        if self.enabled:
            i2cport = -1
            try:
                for i in range(0, 2):
                    if gpios.HWPorts.is_i2c_usable(
                            i) and gpios.HWPorts.is_i2c_enabled(i):
                        i2cport = i
                        break
            except:
                i2cport = -1
            if i2cport > -1:
                if self.interval > 2:
                    nextr = self.interval - 2
                else:
                    nextr = self.interval

                self.initialized = False
                serialdev = None
                self.taskdevicepluginconfig[1] = int(
                    float(self.taskdevicepluginconfig[1]))
                if self.taskdevicepluginconfig[1] != 0:  # i2c address
                    serialdev = i2c(port=i2cport,
                                    address=self.taskdevicepluginconfig[1])
                else:
                    return self.initialized
                self.device = None
                try:
                    if "x" in str(self.taskdevicepluginconfig[3]):
                        resstr = str(self.taskdevicepluginconfig[3]).split('x')
                        self.width = int(resstr[0])
                        self.height = int(resstr[1])
                    else:
                        self.width = None
                        self.height = None
                except:
                    self.width = None
                    self.height = None

                if str(self.taskdevicepluginconfig[0]) != "0" and str(
                        self.taskdevicepluginconfig[0]).strip(
                        ) != "":  # display type
                    try:
                        if str(self.taskdevicepluginconfig[0]) == "ssd1306":
                            from luma.oled.device import ssd1306
                            if self.height is None:
                                self.device = ssd1306(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])))
                            else:
                                self.device = ssd1306(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])),
                                    width=self.width,
                                    height=self.height)
                            self.initialized = True
                        elif str(self.taskdevicepluginconfig[0]) == "sh1106":
                            from luma.oled.device import sh1106
                            if self.height is None:
                                self.device = sh1106(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])))
                            else:
                                self.device = sh1106(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])),
                                    width=self.width,
                                    height=self.height)
                            self.initialized = True
                        elif str(self.taskdevicepluginconfig[0]) == "ssd1309":
                            from luma.oled.device import ssd1309
                            if self.height is None:
                                self.device = ssd1309(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])))
                            else:
                                self.device = ssd1309(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])),
                                    width=self.width,
                                    height=self.height)
                            self.initialized = True
                        elif str(self.taskdevicepluginconfig[0]) == "ssd1331":
                            from luma.oled.device import ssd1331
                            if self.height is None:
                                self.device = ssd1331(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])))
                            else:
                                self.device = ssd1331(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])),
                                    width=self.width,
                                    height=self.height)
                            self.initialized = True
                        elif str(self.taskdevicepluginconfig[0]) == "ssd1351":
                            from luma.oled.device import ssd1351
                            if self.height is None:
                                self.device = ssd1351(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])))
                            else:
                                self.device = ssd1351(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])),
                                    width=self.width,
                                    height=self.height)
                            self.initialized = True
                        elif str(self.taskdevicepluginconfig[0]) == "ssd1322":
                            from luma.oled.device import ssd1322
                            if self.height is None:
                                self.device = ssd1322(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])))
                            else:
                                self.device = ssd1322(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])),
                                    width=self.width,
                                    height=self.height)
                            self.initialized = True
                        elif str(self.taskdevicepluginconfig[0]) == "ssd1325":
                            from luma.oled.device import ssd1325
                            if self.height is None:
                                self.device = ssd1325(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])))
                            else:
                                self.device = ssd1325(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])),
                                    width=self.width,
                                    height=self.height)
                            self.initialized = True
                        elif str(self.taskdevicepluginconfig[0]) == "ssd1327":
                            from luma.oled.device import ssd1327
                            if self.height is None:
                                self.device = ssd1327(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])))
                            else:
                                self.device = ssd1327(
                                    serialdev,
                                    rotate=int(
                                        float(self.taskdevicepluginconfig[2])),
                                    width=self.width,
                                    height=self.height)
                            self.initialized = True
                    except Exception as e:
                        misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                                    "OLED can not be initialized! " + str(e))
                        self.enabled = False
                        self.device = None
                        return False
                if self.device is not None:
                    try:
                        lc = int(self.taskdevicepluginconfig[4])
                    except:
                        lc = self.P23_Nlines
                    if lc < 1:
                        lc = self.P23_Nlines
                    lineheight = int(self.device.height / lc) + 1
                    self.ufont = ImageFont.truetype('img/UbuntuMono-R.ttf',
                                                    lineheight)
                    try:
                        self.device.show()
                    except:
                        pass
                    with canvas(self.device) as draw:
                        maxcols = int(self.taskdevicepluginconfig[5])
                        if maxcols < 1:
                            maxcols = 1
                        tstr = "X" * maxcols
                        try:
                            sw = draw.textsize(tstr, self.ufont)[0]
                        except:
                            sw = self.device.width
                        while (sw > self.device.width):
                            lineheight -= 1
                            self.ufont = ImageFont.truetype(
                                'img/UbuntuMono-R.ttf', lineheight)
                            sw = draw.textsize(tstr, self.ufont)[0]
                        self.charwidth, self.lineheight = draw.textsize(
                            "X", self.ufont)
                        if lc in [2, 4, 6, 8]:
                            self.lineheight += 1
                    if self.interval > 2:
                        nextr = self.interval - 2
                    else:
                        nextr = 0
                    self._lastdataservetime = rpieTime.millis() - (nextr *
                                                                   1000)
                    self.dispimage = Image.new(
                        '1', (self.device.width, self.device.height), "black")
                else:
                    self.initialized = False