예제 #1
0
class SpeedTestCheck(object):

    def __init__(self):
        self.current = {}

    def setup(self):
        self.lcd = Adafruit_CharLCDPlate()
        self.lcd.backlight(self.lcd.GREEN)

    def checkspeed(self):
        cmd = "speedtest-cli --simple --secure"
        raw = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        output, errors = raw.communicate()
        cleaned = filter(None, output.split('\n'))
        self.current = dict(map(str, x.split(':')) for x in cleaned)
        print self.current

    def printspeed(self):
        self.lcd.clear()
        self.lcd.backlight(self.lcd.BLUE)
        msg1 = "D" + self.current['Download'] + '\n' + "U" + self.current['Upload']
        self.lcd.message(msg1)

    def main(self):
        self.setup()
        while True:
            try:
                self.checkspeed()
            except Exception as e:
                print "not sure what happened! %s" %(e)
            try:
                self.printspeed()
            except Exception as e:
                print "not sure what happened! %s" %(e)
            time.sleep(3600)
예제 #2
0
    def lcd_loop(self):
        from time import sleep
        from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate

        # Initialize the LCD plate.  Should auto-detect correct I2C bus.  If not,
        # pass '0' for early 256 MB Model B boards or '1' for all later versions
        lcd = Adafruit_CharLCDPlate()

        # Clear display and show greeting, pause 1 sec
        lcd.clear()
        lcd.message("Deuce Jockey")
        sleep(1)

        # Cycle through backlight colors
        col = (lcd.RED , lcd.YELLOW, lcd.GREEN, lcd.TEAL,
               lcd.BLUE, lcd.VIOLET, lcd.ON   , lcd.OFF)
        for c in col:
            lcd.backlight(c)
            sleep(.1)

        # Poll buttons, display message & set backlight accordingly
        # lcd.backlight(lcd.RED)

        while True:
            if lcd.buttonPressed(lcd.UP):
                print('UP')
                self.sensitivity_up()
            elif lcd.buttonPressed(lcd.DOWN):
                print('DOWN')
                self.sensitivity_down()
            if lcd.buttonPressed(lcd.UP) or lcd.buttonPressed(lcd.DOWN):
                sleep(.1)
            lcd.clear()
            lcd.message("Deuce Jockey\nSensitivity: "+repr(round(self.sensitivity * 100)))
            lcd.backlight(lcd.RED)
예제 #3
0
class Interface:
    def __init__(self, busnum=-1, addr=0x20, debug=False):
        self.lcd = LCD(busnum, addr, debug)
        self.config = Config()
        self.lcd.backlight(int(self.config.get('Display', 'Colour')))
        self.lcd.clear()

    def scytheHome(self):
        self.display('<> Scythe L/R\n^v Choose image')

    def chooseImage(self, imageName):
        output = 'Image chosen:\n' + imageName
        self.display(output)

    def display(self, text):
        self.lcd.display()
        self.lcd.backlight(int(self.config.get('Display', 'Colour')))
        self.lcd.clear()
        self.lcd.message(text)

    def buttons(self):
        return self.lcd.buttons()

    def off(self):
        self.lcd.backlight(self.lcd.OFF)
        self.lcd.noDisplay()
예제 #4
0
def open_dev(encoder_pins):
    '''
    Opens communication with Arduino, GPIO and lcd
    :param encoder_pins: contains the GPIO pins to the encoder
    :type encoder_pins: list of integer
    
    :returns: lcd object, arduino object and iterator
    :rtype: tuple
    '''
    # LCD
    lcd = Adafruit_CharLCDPlate()
    lcd.clear()

    # GPIO
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(encoder_pins[0], GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(encoder_pins[1], GPIO.IN, pull_up_down=GPIO.PUD_UP)

    # Arduino
    # Init Arduino and iterator
    lcd.message("Connection de \nl'Arduino ...")
    board = Arduino('/dev/ttyACM0')
    lcd.clear()
    print('Arduino connected')
    lcd.message("Arduino connecte !")
    # Création itérateur
    iter8 = util.Iterator(board)
    iter8.start()

    dev = (
        lcd,
        board,
    )
    return dev
예제 #5
0
class Interface:
    def __init__(self, busnum=-1, addr=0x20, debug=False):
        self.lcd = LCD(busnum, addr, debug)
        self.config = Config()
        self.lcd.backlight(int(self.config.get('Display', 'Colour')))
        self.lcd.clear()

    def scytheHome(self):
        self.display('<> Scythe L/R\n^v Choose image')

    def chooseImage(self, imageName):
        output = 'Image chosen:\n' + imageName
        self.display(output)

    def display(self, text):
        self.lcd.display()
        self.lcd.backlight(int(self.config.get('Display', 'Colour')))
        self.lcd.clear()
        self.lcd.message(text)

    def buttons(self):
        return self.lcd.buttons()

    def off(self):
        self.lcd.backlight(self.lcd.OFF)
        self.lcd.noDisplay()
예제 #6
0
class Display():
  """
  Creates a display command instance.
  Its update method calles the update method for all the blocks, and
  hence should be called at the frequency which updates are desired.
  """
  def __init__(self):    
    self.lcd = Adafruit_CharLCDPlate()
    self.lcd.begin(16,2)
    self.lcd.clear()
    self.lcd.home()
    self.time = TimeBlock(self.lcd)
    self.status = StatusBlock(self.lcd)
    self.query = QueryBlock(self.lcd)
    self.lastState = OFF
    self.state = OFF
    
  def update(self,state=None):
    self.time.update()
    self.status.update()
    # set our own lastState and state based on the query block
    self.lastState = self.query.lastState
    if state and state == IDLE:
      self.state = self.query.update(enterIdleState=True)
    elif state and state == PROCESS:
      self.state = self.query.update(enterProcessState=True)
    elif state and state == QUERY: self.state = self.query.update(enterQueryState=True)
    else: self.state = self.query.update()
    if DEBUG: print state,self.state

    # turn off if we just changed to OFF
    # turn on if we just changed from OFF
    if self.state == OFF and self.lastState != OFF:
      self.off()
    if self.state != OFF and self.lastState == OFF:
      self.on()

    if DEBUG: print self.state
      
  def on(self):
    self.query.update(enterIdleState=True)
    self.lcd.display()
    self.lcd.backlight(self.lcd.ON)

  def off(self):
    self.lcd.noDisplay()
    self.lcd.backlight(self.lcd.OFF)

  def fail(self,message=''):
    self.lcd.display()
    self.lcd.clear()
    self.lcd.home()
    self.lcd.backlight(self.lcd.ON)
    self.lcd.message("EPIC FAIL\n%s" % message)
예제 #7
0
파일: tl.py 프로젝트: naikon/rpi-timelapse
    def testConfigs():
        print "Testing Configs"
        camera = GPhoto(subprocess)

        for config in CONFIGS:
            print "Testing camera setting: Shutter: %s ISO %d" % (config[1], config[3])
            camera.set_shutter_speed(secs=config[1])
            camera.set_iso(iso=str(config[3]))
            time.sleep(SLEEP_TIME)
            lcd = Adafruit_CharLCDPlate()
            lcd.clear()
            lcd.backlight(lcd.TEAL)
예제 #8
0
파일: ui.py 프로젝트: naikon/rpi-timelapse
class TimelapseUi(object):
    def __init__(self):
        self._lcd = Adafruit_CharLCDPlate()
        #self._lcd = FakeCharLCDPlate()

    def update(self, text):
        self._lcd.clear()
        self._lcd.message(text)
        print(text)

    def show_config(self, configs, current):
        config = configs[current]
        self.update("Timelapse\nT: %s ISO: %s" % (config[1], config[3]))

    def show_status(self, shot, config):
        self.update("Shot %d\nT: %s ISO: %s" % (shot, config[1], config[3]))

    def show_error(self, text):
        self.update(text[0:16] + "\n" + text[16:])
        while not self._lcd.buttonPressed(self._lcd.SELECT):
            sself.backlight(self._lcd.RED)
            sleep(1)

    def main(self, configs, current, network_status):

        while not self._lcd.buttonPressed(self._lcd.SELECT):
            pass

        ready = False
        while not ready:
            while True:
                if (type(self._lcd) == type(FakeCharLCDPlate())):
                    self._lcd.fakeonly_getch()

                if self._lcd.buttonPressed(self._lcd.UP):
                    print "UP"
                    current -= 1
                    if current < 0:
                        current = 0
                    break
                if self._lcd.buttonPressed(self._lcd.DOWN):
                    print "DOWN"
                    current += 1
                    if current >= len(configs):
                        current = len(configs) - 1
                    break
                if self._lcd.buttonPressed(self._lcd.SELECT):
                    print "SELECT"
                    ready = True
                    break
            print "end"
            self.show_config(configs, current)
        return current
예제 #9
0
class LCD():

    # All avalaible colors

    COLOR_RED       = 0
    COLOR_YELLOW    = 1
    COLOR_GREEN     = 2
    COLOR_TEAL      = 3  
    COLOR_BLUE      = 4
    COLOR_VIOLET    = 5
    COLOR_ON        = 6
    COLOR_OFF       = 7

    def __init__(self):
        self.__lcd = Adafruit_CharLCDPlate()

        self.__buttons = (
            self.__lcd.LEFT,
            self.__lcd.UP,
            self.__lcd.DOWN,
            self.__lcd.RIGHT,
            self.__lcd.SELECT,
        )

        self.__col = (
            self.__lcd.RED,
            self.__lcd.YELLOW,
            self.__lcd.GREEN,
            self.__lcd.TEAL,
            self.__lcd.BLUE,
            self.__lcd.VIOLET,
            self.__lcd.ON,
            self.__lcd.OFF
        )

    def stop(self):
        self.changeColor(7)
        self.__lcd.clear()

    def clear(self, clearBackground):
        if clearBackground:
            self.changeColor(6)
        self.__lcd.clear()

    def changeColor(self, index):
        self.__lcd.backlight(self.__col[index])

    def setMessage(self, msg):
        self.__lcd.message(msg)

    def buttonPressed(self):
        return self.__lcd.buttonPressed(self.__buttons[0])
예제 #10
0
class Display():

	def __init__(self):
		self.lcd = Adafruit_CharLCDPlate(busnum=1)

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

	def start(self):
		self.lcd.begin(16, 2)
		self.lcd.backlight(self.lcd.ON)

	def stop(self):
		self.clear()
		self.lcd.backlight(self.lcd.OFF)

	def message(self, message=""):
		self.start()
		self.lcd.message(message)

	def button_pressed(self, button=None):
		if self.lcd.buttonPressed(button):
			time.sleep(.2)
			return(True)
		else:
			return(False)

	def button_left(self):
		return(self.button_pressed(self.lcd.LEFT))

	def button_right(self):
		return(self.button_pressed(self.lcd.RIGHT))

	def button_up(self):
		return(self.button_pressed(self.lcd.UP))

	def button_down(self):
		return(self.button_pressed(self.lcd.DOWN))

	def button_select(self):
		return(self.button_pressed(self.lcd.SELECT))

	def blink_cursor(self):
		self.lcd.blink()

	def move_cursor(self, col=0, row=0):
		self.lcd.setCursor(col, row)
예제 #11
0
class LCDPlate():
    def __init__(self):
        self.lcd = Adafruit_CharLCDPlate()
        self.lcd.begin(16, 2)
        self.lcd.clear()
        self.lcd.backlight(self.lcd.GREEN)

    def update_active(self, result, heat, cool, fan):
        if result == 'cool':
            self.lcd.backlight(self.lcd.BLUE)
        elif result == 'heat':
            self.lcd.backlight(self.lcd.RED)
        elif result == 'off':
            self.lcd.backlight(self.lcd.GREEN)

    def update_temperature(self, temp):
        self.lcd.clear()
        self.lcd.message("Temp: %.1fF" % temp)

    def off(self):
        self.lcd.backlight(self.lcd.OFF)
        self.lcd.clear()
예제 #12
0
class LCDPlate():

    def __init__(self):
        self.lcd = Adafruit_CharLCDPlate()
        self.lcd.begin(16, 2)
        self.lcd.clear()
        self.lcd.backlight(self.lcd.GREEN)

    def update_active(self, result, heat, cool, fan):
        if result == 'cool':
            self.lcd.backlight(self.lcd.BLUE)
        elif result == 'heat':
            self.lcd.backlight(self.lcd.RED)
        elif result == 'off':
            self.lcd.backlight(self.lcd.GREEN)

    def update_temperature(self, temp):
        self.lcd.clear()
        self.lcd.message("Temp: %.1fF" % temp)

    def off(self):
        self.lcd.backlight(self.lcd.OFF)
        self.lcd.clear()
def main():

    ## MPD object instance
    client = MPDClient()
    lcd = Adafruit_CharLCDPlate(1)

    lcd.clear()
    lcd.message("Wellcome to the\nMPD Interface!")
    print "Wellcome to the\nMPD Interface!"
    sleep(1)

    # initialize mpd connection
    startup(client, lcd)

    # Printing first known informations on lcd
    message = generate_status(client)
    display_status(lcd, message)

    print client.status()
    try:
        print client.listplaylists()
    except:
        print "error"
    try:
        print client.listplaylist()
    except:
        print "error"
    try:
        print client.listplaylistinfo()
    except:
        print "error"

        # Poll buttons, display message & set backlight accordingly
    btn = (
        (lcd.LEFT, "LEFT", lcd.ON),
        (lcd.UP, "UP", lcd.ON),
        (lcd.DOWN, "DOWN", lcd.ON),
        (lcd.RIGHT, "RIGHT", lcd.ON),
        (lcd.SELECT, "SELECT", lcd.ON),
    )

    t0 = clock()  # start time
    refresh_display = clock()  # time of the last display refresh
    last_action = clock()  # time of the last action
    prev = -1  # last pressed button

    while True:

        # refresh display every 0.1 sec
        if clock() - refresh_display >= 0.1:
            refresh_display = clock()
            # turn display after 5 sec off
            if clock() - last_action <= 2.5:
                message = generate_status(client)
                display_status(lcd, message)
            else:
                idle(lcd)

        for b in btn:
            # begin "if button pressed"
            if lcd.buttonPressed(b[0]):
                if (b is not prev) or (clock() - t0 >= 0.3):
                    if b[0] == lcd.UP:
                        BTN_UP(client)

                    elif b[0] == lcd.DOWN:
                        BTN_DOWN(client)

                    elif b[0] == lcd.RIGHT:
                        BTN_RIGHT(client)

                    elif b[0] == lcd.LEFT:
                        BTN_LEFT(client)

                    elif b[0] == lcd.SELECT:
                        BTN_SELECT(client)

                    t0 = clock()
                    last_action = clock()
                    prev = b
                break
                # end "if buffon pressed"

    client.disconnect()
    sys.exit(0)
예제 #14
0
class UI_Adafruit(Thread):
	_db = None
	_pi_rev = None
	_lcd = None

	menu = None
	prevmenu = None
	nextmenu = None

	_scandone = False

	_pressedButtons = []

	_index = 0


	# Simple lookup dict for menu class names
	_menus = {
		UIAdaMenus.main : UIAdaMainMenu,
		UIAdaMenus.nodes : UIAdaNodesMenu,
		UIAdaMenus.games : UIAdaGamesMenu,
		UIAdaMenus.config : UIAdaConfigMenu
	}

	def __init__(self, prefs, nodeman, games):
		super(UI_Adafruit, self).__init__()

		self.__logger = logging.getLogger("UI_Adafruit " + str(id(self)))
		self.__logger.debug("init logger")

		self._lcd = Adafruit_CharLCDPlate()

		MBus.add_handler(GameList_ScanEventMessage, self.handle_GameList_ScanEventMessage)
		MBus.add_handler(FOAD, self.die)

		# Let the user know that we're doing things
		self._lcd.begin(16, 2)
		self._lcd.message("CANTBoot Loading\n    Hold up.")

		self._games = games

		self._nodes = nodeman.nodes

	def die(self, data):
		self.line1="Goodbye George<3"
		self.line2=""
		sleep(2)
		self.line1 = ""
		try:
			menu.exitmenu = True
			sleep(0.5)
		except:
			pass

	def handle_GameList_ScanEventMessage(self, message: GameList_ScanEventMessage):
		self._lcd.clear()
		if message.payload == "donelol":
			self._scandone = True
			self._lcd.message("Init Success")
		else:
			self.line1= message.payload
			self.line2 ='Scanning...'

	# THE MEAT(tm)
	def runui(self):

		sel_idx = 0
		nextmenu = None

		while 1:
			# Don't do anything until we've booted up successfully
			if self._scandone:
				menu = UIAdaNodesMenu(self._lcd, self._nodes)

					if nextmenu:
						prevmenu = nextmenu
						if nextmenu == UIAdaMenus.main:
							menu = UIAdaMainMenu(self._lcd)
						elif nextmenu == UIAdaMenus.nodes:
							menu = UIAdaNodesMenu(self._lcd, self._nodes)
						elif nextmenu == UIAdaMenus.games:
							menu = UIAdaGamesMenu(self._lcd, self._games, self._nodes[sel_idx].node_id)
							#menu = UIAdaGamesMenu(self._lcd, self._games, '0')

					menuret = menu.run_menu()
					nextmenu = menuret[0]
					sel_idx = menuret[1]

					#process return values here and determine if we need to do anything special, e.g. load a game
			else:
				# We're not done booting, hang on a second (literally).
				sleep(1)

		'''
예제 #15
0
def handler(signum = None, frame = None):
    lcd = Adafruit_CharLCDPlate()
    lcd.clear()
    lcd.stop()
    sys.exit(0)
예제 #16
0
import logging
import thread
import time
import fcntl
import os
import RPi.GPIO as GPIO
import nfc
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
from Adafruit_CharLCDPlate2 import Adafruit_CharLCDPlate2

emptyLine = "                "
lcd1 = Adafruit_CharLCDPlate()
lcd2 = Adafruit_CharLCDPlate2()
lcd1.begin(20, 4)
lcd2.begin(20, 4);
lcd1.clear()
lcd2.clear()
lcd1.message("Welcome.\nStarting...")
lcd1.backlight(lcd.ON)
time.sleep(2)
def sendPOST (message):

    params = urllib.urlencode({'@number': message, '@type': 'issue', '@action': 'show'})
    headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
    conn = httplib.HTTPConnection("bugs.python.org")
    conn.request("POST", "", params, headers)
    response = conn.getresponse()
    print response.status, response.reason
    data = response.read()
    conn.close()
    return data
예제 #17
0
class lcdScreen(object):
  """Class for handling the Adafruit LCDPlate display"""
  def __init__(self, bgColor, txt):
    self.bgColor = bgColor
    self.lcd = Adafruit_CharLCDPlate()
    self.lcd.clear()
    self.lcd.backlight(bgColor)
    self.lcd.message(txt)

    # Create custom characters for LCD for big clock display
    
    # Create some custom characters
    self.lcd.createChar(0, [0, 0, 0, 0, 0, 0, 0, 0])
    self.lcd.createChar(1, [16, 24, 24, 24, 24, 24, 24, 16])
    self.lcd.createChar(2, [1, 3, 3, 3, 3, 3, 3, 1])
    self.lcd.createChar(3, [17, 27, 27, 27, 27, 27, 27, 17])
    self.lcd.createChar(4, [31, 31, 0, 0, 0, 0, 0, 0])
    self.lcd.createChar(5, [0, 0, 0, 0, 0, 0, 31, 31])
    self.lcd.createChar(6, [31, 31, 0, 0, 0, 0, 0, 31])
    self.lcd.createChar(7, [31, 0, 0, 0, 0, 0, 31, 31])
     


    self.timeSinceAction = 0  # The time since the last keypress. Use timeout to start switching screens
#    self.switchScreenTime = 8 #Number of seconds between switching screens
    self.lastScreenTime = time.time()    # time since last screen switch
    self.prevStr = ""
    self.screens = ((self.bigTimeView,6),          # Rotating list of views on LCD with how many seconds to display each display. Round robin style.
                    (self.connectedUserView,4),
                    (self.bigTimeView,6),
                    (self.precisionView,4),
                    (self.bigTimeView,6),
                    (self.ntptimeInfo,5),
                    (self.bigTimeView,6),
                    (self.clockperfView,5),
                    ) # list of all views for rotation
                    
    self.nrofscreens = len(self.screens)
    self.currentScreen = 0

  def writeLCD(self, s):
    """Checks the string, if different than last call, update screen."""
    if self.prevStr.decode("ISO-8859-1") != s.decode("ISO-8859-1"):  # Oh what a shitty way around actually learning the ins and outs of encoding chars...
      # Display string has changed, update LCD
      self.lcd.clear()
      self.lcd.message(s)
      self.prevStr = s  # Save so we can test if screen changed between calls, don't update if not needed to reduce LCD flicker

  def bigTimeView(self):
    """Shows custom large local time on LCD"""

    now=time.localtime()
    hrs=int(time.strftime("%H"))
    minutes=int(time.strftime("%M"))
    sec=int(time.strftime("%S"))
    
    # Build string representing top and bottom rows
    L1="0"+str(digits[hrs][0]).zfill(5)+str(digits[minutes][0]).zfill(5)+str(digits[sec][0]).zfill(5)
    L2="0"+str(digits[hrs][1]).zfill(5)+str(digits[minutes][1]).zfill(5)+str(digits[sec][1]).zfill(5)
    
    # Convert strings from digits into pointers to custom character
    i=0
    XL1=""
    XL2=""
    while i < len(L1):
        XL1=XL1+chr(int(L1[i]))
        XL2=XL2+chr(int(L2[i]))
        i += 1
    
    self.writeLCD(XL1+"\n" +XL2)


  def precisionView(self):
    """Calculate and display the NTPD accuracy"""
    try:
      output = subprocess.check_output("ntpq -c rv", shell=True)
      returncode = 0
    except subprocess.CalledProcessError as e:
        output = e.output
        returncode = e.returncode
        print returncode
        exit(1)
        
    precision = ""
    clkjitter = ""
    clkwander = ""
    theStr = ""
    searchResult = re.search( r'precision=(.*?),', output, re.S)
    precision = searchResult.group(1)
    searchResult = re.search( r'.*clk_jitter=(.*?),', output, re.S)
    clk_jitter = searchResult.group(1)
    if precision and clk_jitter:
      precision = (1/2.0**abs(float(precision)))*1000000.0
      theStr = "Prec: {:.5f} {}s\n".format(precision,chr(0xE4))
      theStr += "ClkJit: {:>4} ms".format(clk_jitter)
    else:
      theStr = "Error: No\nPrecision data"
    self.writeLCD(theStr)

  def ntptimeInfo(self):
    """Statistics from ntptime command"""
    try:
      output = subprocess.check_output("ntptime", shell=True)
    except subprocess.CalledProcessError as e:
        output = e.output
        returncode = e.returncode
        print returncode
    precision = re.search( r'precision (.* us).*stability (.* ppm)', output, re.M|re.S)
    if precision:
      theStr = "Precis: {:>8}\n".format(precision.group(1))
      theStr += "Stabi: {:>9}".format(precision.group(2))
    else:
      theStr = "No info\nError"
    self.writeLCD(theStr)

  def clockperfView(self):
    """Shows jitter etc"""
    output = subprocess.check_output("ntptime", shell=True)
    search = re.search( r'TAI offset.*offset (.*? us).*jitter (.* us)', output, re.M|re.S)
    if search:
      theStr = "Offset: {:>8}\n".format(search.group(1))
      theStr += "OSjitt: {:>8}".format(search.group(2))
    else:
      theStr = "No offset\ninfo error"
    self.writeLCD(theStr)
    
  def updateLCD(self):
    """Called from main loop to update GPS info on LCD screen"""
    # Check status of GPS unit if it has a lock, otherwise change color of background on LCD to red.
    if time.time() - self.lastScreenTime > self.screens[self.currentScreen][1]: # Time to switch display
      self.currentScreen = self.currentScreen +1
      self.lastScreenTime = time.time()   # reset screen timer
      if self.currentScreen > self.nrofscreens - 1:
        self.currentScreen = 0
    self.screens[self.currentScreen][0]()
      
  def connectedUserView(self):
    """Shows connected clients to ntpd"""
    highestCount = "NaN"
    try:
      output = subprocess.check_output("ntpdc -n -c monlist | awk '{if(NR>2)print $1}' | uniq | wc -l", shell=True)  # Gets all the connected clients from ntp
    except subprocess.CalledProcessError as e:
        output = e.output
        returncode = e.returncode
        print returncode
    
    try:
      highestCount = subprocess.check_output("ntpdc -n -c monlist | awk '{if(NR>2)print $4}' | sort -nrk1,1 | line", shell=True)  # Gets the highest connections from connected clients
    except subprocess.CalledProcessError as e:
        output = e.output
        returncode = e.returncode
        print returncode
    theStr = "Con users: {:>6}".format(output)
    theStr += "Hi cons: {:>8}".format(highestCount)
    self.writeLCD(theStr)
예제 #18
0
    args = parser.parse_args()

    signal.signal(signal.SIGTERM, onShutdown)
    signal.signal(signal.SIGUSR1, onShutdown)

    menuitems = make_menuitems(args)
    
    if args.daemon:
        while True:
            try:
                run_shit(menuitems, args)
            except KeyboardInterrupt:
                break
            except Exception, e:
                lcdFallback = Adafruit_CharLCDPlate()
                lcdFallback.clear()
                lcdFallback.backlight(lcdFallback.RED)

                mes = repr(e)
                if len(mes)>16:
                    mes = mes[:16] + "\n" + mes[16:]

                lcdFallback.message(mes)

                print "Exception", e
                sleep(10)
                del lcdFallback

    else:
       run_shit(menuitems, args)
예제 #19
0
class fppLCD():
    def __init__(self, directory):
        self.THIS_DIRECTORY = directory

        self.BACK_COLOR = 0
        self.PLAYLIST_DIRECTORY = "/home/pi/media/playlists/"
        self.SETTINGS_FILE = "/home/pi/media/settings"

        self.DIRECTION_LEFT = 0
        self.DIRECTION_RIGHT = 1
        self.MAX_CHARS = 16
        self.MAX_STATUS_TIMEOUT = 120
        self.NORMAL_STATUS_TIMEOUT = 3
        self.FPPD_PLAYER_MODE = "2"
        self.FPPD_BRIDGE_MODE = "1"
        self.maxStatusUpdateCount = 5
        self.statusUpdateCounter = 5
        self.FPPD_STATUS_STOPPED = -1
        self.FPPD_STATUS_RUNNING = 1
        self.FPPDstatus = 0
        self.FPPDplayerStatus = 0
        # Status Constants
        self.STATUS_IDLE = "0"
        self.STATUS_PLAYING = "1"
        self.STATUS_STOPPING_GRACEFULLY = "2"

        self.STATUS_INX_PLAYER_MODE = 0
        self.STATUS_INX_STATUS = 1
        self.STATUS_INX_NEXT_PLAY_LIST = 3
        self.STATUS_INX_CURRENT_PLAY_LIST = 3
        self.STATUS_INX_NEXT_TIME = 4
        self.STATUS_INX_PL_TYPE = 4
        self.STATUS_INX_SEQ_NAME = 5
        self.STATUS_INX_SONG_NAME = 6
        self.STATUS_INX_SECS_ELASPED = 9
        self.STATUS_INX_SECS_REMAINING = 10

        # Text to display
        self.line1 = ""
        self.line2 = ""
        # Rotation Variables
        self.rotateEnable = 0
        self.tempLine1 = ""
        self.tempLine2 = ""
        self.rotatePositon1 = 0
        self.rotatePositon2 = 0
        self.rotateSpeed = 0
        self.rotateCount = 0
        self.rotateMaxCount = 3
        self.fixedLocation1 = 0
        self.fixedLocation2 = 0

        self.lcd = Adafruit_CharLCDPlate()
        #self.lcd = VirtualLCD()

        self.lcd.noBlink()
        self.lcd.noCursor()
        self.lcd.clear()

        self.sequenceCount = 0
        self.sequences = ()

        self.playlists = ()
        self.selectedPlaylistIndex = 0
        self.MenuIndex = 0
        self.SubmenuIndex = 0

        self.MENU_INX_STATUS = 0
        self.MENU_INX_STOP_SEQUENCE = 1
        self.MENU_INX_PLAYLISTS = 2
        self.MENU_INX_PLAYLIST_ENTRIES = 3
        self.MENU_INX_SHUTDOWN_REBOOT = 4
        self.MENU_INX_BACKGROUND = 5
        self.MENU_INX_BACKCOLOR = 6
        self.MENU_INX_BACKCOLOR_TIMEOUT = 7

        self.COLOR_WHITE = 6

        self.TimeMode = 0
        self.TIMEMODE_ELASPED = 0
        self.TIMEMODE_REMAINING = 1

        self.BACKGROUND_ALWAYS_ON = 0
        self.BACKGROUND_TIMEOUT_ENABLED = 1
        self.BACKGROUND_TIMEOUT_MAX_COUNT = 1500
        self.BackgroundColor = 0
        self.BackgroundTimeout = 1  #self.BACKGROUND_TIMEOUT_ENABLED
        self.BackgroundTimeoutCount = 0

        self.MENU_BACKCOLOR_TIMEOUT_COUNT = 2
        self.previousBtn = -1

        self.MENU_BACKGROUND_COUNT = 2
        self.menuBackground = ("1)Color         ", "2)Mode          ")

        self.MENU_COLOR_COUNT = 7
        self.colors = (("Red            ", self.lcd.RED), ("Green          ",
                                                           self.lcd.GREEN),
                       ("Blue           ", self.lcd.BLUE), ("Yellow         ",
                                                            self.lcd.YELLOW),
                       ("Teal           ", self.lcd.TEAL), ("Violet         ",
                                                            self.lcd.VIOLET),
                       ("White          ", self.lcd.WHITE))

        self.backgroundModes = ("Always On       ", "Timeout         ")

    def Initialize(self):

        if os.path.exists("/home/fpp/media"):
            self.PLAYLIST_DIRECTORY = "/home/fpp/media/playlists/"
            self.SETTINGS_FILE = "/home/fpp/media/settings"

        strColorIndex = self.readSetting("piLCD_BackColor")
        if strColorIndex.isdigit():
            self.BackgroundColor = int(strColorIndex)
        else:
            self.BackgroundColor = self.COLOR_WHITE

        self.SelectColor(self.BackgroundColor)

        strTimeout = self.readSetting("piLCD_BackgroundTimeout")
        if strTimeout.isdigit():
            self.BackgroundTimeout = int(strTimeout)
        else:
            self.BackgroundTimeout = 1

        strTimeout = self.readSetting("piLCDtimeMode")
        if strTimeout.isdigit():
            self.TimeMode = int(strTimeout)
        else:
            self.TimeMode = 0

        version = fpplcd.getFPPversion()
        self.line1 = self.MakeStringWithLength("FPP Version", 16, 1)
        self.line2 = self.MakeStringWithLength(version, 16, 1)
        self.UpdateDisplay()
        time.sleep(4)

        return

    def SendCommand(self, command):
        count = 0
        max_timeout = 10
        #buf=""
        # Create a UDS socket
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        sock.bind("/tmp/FPP" + str(os.getpid()))
        sock.settimeout(5)
        # Connect the socket to the port where the server is listening
        server_address = "/tmp/FPPD"
        #print >>sys.stderr, 'connecting to %s' % server_address
        try:
            sock.connect(server_address)
            sock.send(command)
            buf = sock.recv(1024)
            sock.close()
            os.unlink("/tmp/FPP" + str(os.getpid()))

        except socket.error, msg:
            #print >>sys.stderr, msg
            sock.close()
            os.unlink("/tmp/FPP" + str(os.getpid()))
            return "false"

        return buf
예제 #20
0
class menuLCD(treeList):

   OFFTIME = 20
   EXITFILE = '/tmp/menuLCD.exit'	
   
   def __init__(self):
      sleep(.5)
      self.lcd = Adafruit_CharLCDPlate(busnum=1)
      sleep(.5)
      self.lcd.begin(16, 2)
      sleep(.5)
      self.lcd.clear()
      self.lcd.message("Menu LCD library \nversion 1.0!")
      treeList.__init__(self)      
      self.button = ((self.lcd.SELECT, 'Select'),
                     (self.lcd.LEFT  , 'Left'  ),
                     (self.lcd.UP    , 'Up'    ),
                     (self.lcd.DOWN  , 'Down'  ),
                     (self.lcd.RIGHT , 'Right' ))     
      self.elapsed = 0 
      self.time2Sleep = 0
      self.displayOn = False

      if os.path.isfile(self.EXITFILE):
         os.remove(self.EXITFILE)
         
      sleep(1) 

##################################################################################################################
   def exitMenu(self):
      if self.ynQuestion('are you sure?'):
         self.shutdown()
         sys.exit(0)

##################################################################################################################
   def ynQuestion(self, text):
      self.lcd.clear()
      sleep(.1)
      self.lcd.message(text+'\n'+'left(n) right(y)')

      response = False
      exitLoop = False
      while not exitLoop:
         for btn in self.button:
            if self.lcd.buttonPressed(btn[0]):
               if btn[0] == self.lcd.RIGHT:
                  exitLoop = True
                  response = True
               if btn[0] == self.lcd.LEFT:
                  exitLoop = True
                  response = False
         sleep(.1)
                  
      return response

##################################################################################################################
   def keyUp(self):
      response = False
      for btn in self.button:
         if self.lcd.buttonPressed(btn[0]):
            if btn[0] == self.lcd.UP:
               response=True
      return response
                  
##################################################################################################################
   def keyDown(self):
      response = False
      for btn in self.button:
         if self.lcd.buttonPressed(btn[0]):
            if btn[0] == self.lcd.DOWN:
               response=True
      return response
                  
##################################################################################################################
   def keyRight(self):
      response = False
      for btn in self.button:
         if self.lcd.buttonPressed(btn[0]):
            if btn[0] == self.lcd.RIGHT:
               response=True
      return response
                  
##################################################################################################################
   def keyLeft(self):
      response = False
      for btn in self.button:
         if self.lcd.buttonPressed(btn[0]):
            if btn[0] == self.lcd.LEFT:
               response=True
      return response
                  
##################################################################################################################
   def keySelect(self):
      response = False
      for btn in self.button:
         if self.lcd.buttonPressed(btn[0]):
            if btn[0] == self.lcd.SELECT:
               response=True
      return response
                  
##################################################################################################################
   def keyPressed(self):
      response = False
      for btn in self.button:
         if self.lcd.buttonPressed(btn[0]):
            if btn[0] == self.lcd.RIGHT or btn[0] == self.lcd.LEFT or btn[0] == self.lcd.UP or btn[0] == self.lcd.DOWN:
               response=True
      return response
                  
##################################################################################################################
   def shutdown(self):
      self.turnOnDisplay()
      self.clearLCD()         
      self.message2LCD('Exiting...')
      sleep(2)      
      self.turnOffDisplay()

##################################################################################################################
   def setTime2Sleep(self,t): 
      self.OFFTIME = t
      
##################################################################################################################
   def message2LCD(self, msn):
      self.lcd.message(msn)

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

##################################################################################################################
   def turnOffDisplay(self):     
      if self.displayOn:
         self.lcd.noDisplay()
         self.lcd.backlight(self.lcd.OFF)
         self.displayOn = False

##################################################################################################################
   def turnOnDisplay(self):
      if not self.displayOn:
         self.lcd.display()
         self.lcd.backlight(self.lcd.ON)
         self.displayOn = True
            
##################################################################################################################
   def resetTime2Sleep(self):
      self.elapsed = time()
      self.time2Sleep = 0

##################################################################################################################
   def lcdRefresh(self):
      self.turnOnDisplay()
      self.lcd.clear()
      sleep(.1)
      menuString = '%s\n[%s]'%(treeList.activeItemString(self),treeList.activePosition(self))
      self.lcd.message(menuString)
      sleep(.1)

##################################################################################################################
   def checkButtons(self):
      for btn in self.button:
         if self.lcd.buttonPressed(btn[0]):
            self.resetTime2Sleep()
            
            if self.displayOn:

               if btn[0] == self.lcd.RIGHT:
                  treeList.goNext(self)

               if btn[0] == self.lcd.LEFT:
                  treeList.goPrev(self)

               if btn[0] == self.lcd.DOWN:
                  if treeList.activeEntryHasItems(self): 
                     treeList.goDown(self)
                  else: 
                     treeList.goNext(self) 

               if btn[0] == self.lcd.UP:
                  treeList.goUp(self)

               if btn[0] == self.lcd.SELECT:
                  if treeList.typeOfActiveItem(self) == treeList.CMD:
                     treeList.command(self)() 
                     self.resetTime2Sleep()

            self.lcdRefresh()

##################################################################################################################
   def check2Sleep(self):
      if self.time2Sleep < self.OFFTIME:
         self.time2Sleep = time() - self.elapsed
      else:
         self.turnOffDisplay()   

##################################################################################################################
   def check4Exit(self):
      returnValue = True
      
      if os.path.isfile(self.EXITFILE):
         os.remove(self.EXITFILE)
         returnValue=False

      return returnValue   

##################################################################################################################
   def play(self):
      treeList.goTop(self)
      self.lcdRefresh()     
      self.resetTime2Sleep()
            
      while self.check4Exit():
         self.check2Sleep() 
         self.checkButtons()

      self.shutdown()
      sys.exit(0)   

##################################################################################################################
   def addExitEntry(self, *parentName):
      if len(parentName)>0:
         treeList.addItem(self,parentName[0],'Exit', self.exitMenu)
      else:
         treeList.addItem(self,treeList.ROOT,'Exit', self.exitMenu)          
예제 #21
0
import sys
import tty
import termios
import logging
import thread
import time
import fcntl
import os
import RPi.GPIO as GPIO
import nfc
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate

emptyLine = "                "
lcd = Adafruit_CharLCDPlate()
lcd.begin(16, 2)
lcd.clear()
lcd.message("Welcome.\nStarting...")
lcd.backlight(lcd.ON)
time.sleep(2)
def sendPOST (message):

    params = urllib.urlencode({'@number': message, '@type': 'issue', '@action': 'show'})
    headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
    conn = httplib.HTTPConnection("bugs.python.org")
    conn.request("POST", "", params, headers)
    response = conn.getresponse()
    print response.status, response.reason
    data = response.read()
    conn.close()
    return data
예제 #22
0
class DisplayLoop(StreamListener):
    """
    This class is a listener for tweet stream data. It's also callable so it
    can run the main display thread loop to update the display.
    """
    PICKLE_FILE = '/home/pi/py/tweetbox.pkl'

    def __init__(self):
        self.lcd = Adafruit_CharLCDPlate()
        self.lcd.backlight(self.lcd.RED)
        self.lcd.clear()
        self.track_text = 'jeremy'
        self.backlight_map = {
            'red': self.lcd.RED,
            'green': self.lcd.GREEN,
            'blue': self.lcd.BLUE,
            'yellow': self.lcd.YELLOW,
            'teal': self.lcd.TEAL,
            'violet': self.lcd.VIOLET
        }
        self.msglist = []
        self.pos = 0
        self.tweet = 'Nothing yet'

    def set_backlight(self):
        words = self.tweet.lower().split(' ')
        use_default = True
        for w in words:
            if w in self.backlight_map:
                self.lcd.backlight(self.backlight_map[w])
                use_default = False
                break
        if use_default:
            self.lcd.backlight(self.lcd.WHITE)

    def on_data(self, data):
        print data
        tweet_data = json.loads(data)
        self.set_text(tweet_data['text'].encode('ascii',
                                                errors='backslashreplace'))

    def set_text(self, text):
        self.tweet = text
        self.msglist = [
            x.ljust(16) for x in textwrap.wrap(str(self.tweet), 16)
        ]
        self.pos = 0
        self.set_backlight()
        self.scroll_message()
        return True

    def on_error(self, status):
        print status

    def write_message(self, msg):
        self.lcd.home()
        self.lcd.message(msg)

    def scroll_message(self):
        "Displays the page of text and updates the scroll position for the next call"
        if len(self.msglist) == 0:
            self.write_message(''.ljust(16) + '\n' + ''.ljust(16))
        elif len(self.msglist) == 1:
            self.write_message(self.msglist[0] + '\n' + ''.ljust(16))
        elif len(self.msglist) == 2:
            self.write_message(self.msglist[0] + '\n' + self.msglist[1])
        else:
            if self.pos >= len(self.msglist) - 1:
                self.pos = 0
            else:
                self.write_message(self.msglist[self.pos] + '\n' +
                                   self.msglist[self.pos + 1])
                self.pos += 1

    def get_ip_address(self, interface):
        "Returns the IP address for the given interface e.g. eth0"
        try:
            s = subprocess.check_output(["ip", "addr", "show", interface])
            return s.split('\n')[2].strip().split(' ')[1].split('/')[0]
        except:
            return '?.?.?.?'

    def write_config(self):
        data = {
            "track_text": self.track_text,
            "backlight_map": self.backlight_map
        }
        output = open(self.PICKLE_FILE, 'wb')
        pickle.dump(data, output)
        output.close()

    def read_config(self):
        if exists(self.PICKLE_FILE):
            pkl_file = open(self.PICKLE_FILE, 'rb')
            data = pickle.load(pkl_file)
            pkl_file.close()
            self.track_text = data["track_text"]
            self.backlight_map = data["backlight_map"]

    def __call__(self):
        while True:
            if self.lcd.buttonPressed(self.lcd.LEFT):
                self.write_message(
                    self.get_ip_address('eth0').ljust(16) + '\n' +
                    self.get_ip_address('wlan0').ljust(16))
            else:
                self.scroll_message()
            time.sleep(1)
예제 #23
0
파일: fablab.py 프로젝트: longblonde/FLACS
            lcd.backlight(lcd.BLUE)
            lcd.message("SCAN BARCODE:")
            x = int(raw_input("SCAN BARCODE: "))
            
        except ValueError: #Input format error handling
            lcd.clear()
            lcd.backlight(lcd.RED)
            lcd.message("User does\nNOT exist!")
            print "User does NOT exist!"
            print ""
            sleep(5)
            continue
        else:
            return (x)

lcd.clear() #Clear LCD
lcd.message("FABLab Login\n%s" % (vers)) #Display program version
col = (lcd.RED, lcd.GREEN, lcd.BLUE, lcd.ON) #Cycle FABLab colors
for c in col:
    lcd.backlight(c)
    sleep(1)


lcd.clear()
lcd.backlight(lcd.YELLOW) #Sets LCD Warning mode
lcd.message("Connecting")
sleep(.25)
lcd.clear()
lcd.message("Connecting.")
sleep(.25)
lcd.clear()
예제 #24
0
파일: plate.py 프로젝트: peshay/pwn
#!/usr/bin/python

from time import sleep
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
from Adafruit_MCP230xx import MCP230XX_GPIO
from Adafruit_CharLCD import Adafruit_CharLCD

# Initiate CharLCDPlate
led = Adafruit_CharLCDPlate()
# clear screen
led.clear()
# turn LED off
led.backlight(led.OFF)

# Initiate Display
bus = 1         # Note you need to change the bus number to 0 if running on a revision 1 Raspberry Pi.
address = 0x20  # I2C address of the MCP230xx chip.
gpio_count = 8  # Number of GPIOs exposed by the MCP230xx chip, should be 8 or 16 depending on chip.
mcp = MCP230XX_GPIO(bus, address, gpio_count)

# Initialize the LCD plate.  Should auto-detect correct I2C bus.  If not,
# pass '0' for early 256 MB Model B boards or '1' for all later versions
lcd = Adafruit_CharLCD(pin_rs=1, pin_e=2, pins_db=[3,4,5,6], GPIO=mcp)

# turn lcd off
lcd.display()

# prepare next message and set LED red
led.clear()
led.message("ahutest")
led.backlight(led.RED)
예제 #25
0
파일: main.py 프로젝트: khibma/GPSLogger2
def go(filename, token):
	print "here we go"


	lcd = Adafruit_CharLCDPlate()
	lcd.begin(16, 2)
	lcd.clear()
	lcd.message("UP=LOG,LFT=fixWW\nDWN=File,RGT=Info")

	sleep(1)
	i=0
	lcd.ON
	prev = -1

	while not (lcd.buttonPressed(lcd.SELECT)):
		# The ELSE on all button pushes which handle multiple clicks is the first entry point

		if (lcd.buttonPressed(lcd.RIGHT)):
			# cycle through: WEATHER, IP, and TIME then repeat
			lcd.clear()

			if prev == "r1":
				prev = "r2"
				lcd.message('Your IP address:\n %s' % _IP())
				sleep(1)
			elif prev == "r2":
				prev = -1
				#lcd.message('The time:\n%s' % strftime('%y/%m/%d %I:%M %p', gmtime()))
				lcd.message('The time:\n%s' % str(gpsd.utc))
				sleep(1)
			else:
				prev = "r1"
				content = _WEATHER(gpsd.fix.latitude, gpsd.fix.longitude)
				lcd.message(content)
				sleep(1)


		if (lcd.buttonPressed(lcd.LEFT)):
			# reconnects the internet if disconnected
			lcd.clear()

			if prev == 'l1':
				prev = -1
				msg = pushSpecial (gpsd, fsURL, userName, passWord)
				lcd.message(msg)
				sleep(1)
			else:
				prev = 'l1'
				sats = gpsd.satellites
				gSatCount = 0
				for item in sats:
				    if item.used == True:
				        gSatCount += 1
				totSats = len(sats)
				lcd.message("%s Sats of\n %s used" % (gSatCount, totSats))
				sleep(1)



		if (lcd.buttonPressed(lcd.UP)):
			# starts the GPS logging
			prev = 'u1'
			while prev == 'u1':
				lcd.clear()
				try:
					msg = push (gpsd, fsURL, userName, passWord, filename, token)
					content = str("{0:.3f},{1:.3f}\n{2}").format(msg[0], msg[1], msg[2])
				except Exception, e:
					print str(e)
					content = str(e)
				lcd.message(content +str(i))
				### press DOWN 1 second after an updated msg to quit logging
				sleep(1)
				if (lcd.buttonPressed(lcd.UP)):
					prev = -1
					lcd.clear()
					lcd.message("stopped\ncollecting")
				###
				i+=1
				sleep(int(pCollectTime))

			'''
			out = True
			while out:
				lcd.clear()
				try:
					msg = push (gpsd, fsURL, userName, passWord, pushOnConnect)
					content = str("{0:.3f},{1:.3f}\n{2}").format(msg[0], msg[1], msg[2])
				except Exception, e:
					print str(e)
					content = "cant get lat/lon"
				lcd.message(content +str(i))
				### press DOWN 1 second after an updated msg to quit logging
				sleep(1)
				if (lcd.buttonPressed(lcd.DOWN)):
					out = False
					lcd.clear()
					lcd.message("stopped\ncollecting")
				###
				i+=1
				sleep(int(pCollectTime))
			'''

		if (lcd.buttonPressed(lcd.DOWN)):
			# shows how many lines in current .CSV file
			# 2nd push starts a new file
			print prev
			lcd.clear()
			if prev == "d1":
				prev = -1
				curNum = os.path.splitext(filename[filename.rfind('_')+1:])[0]
				newNum = int(curNum) +1
				filename= filename.replace(str(curNum), str(newNum))
				lcd.message("now using:\n %s" % filename)
				sleep(1)

			else:
				prev = 'd1'
				try:
					with open(filename) as f:
						for i, l in enumerate(f):
							pass
					lines = i+1
				except IOError: lines = "???"

				lcd.message("f: %s has\n %s lines" % (filename, lines))
				sleep(1)
예제 #26
0
import RPi.GPIO as GPIO
import time
from time import gmtime, strftime
import os

EMAIL = '*****@*****.**'

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(14, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Initialize the LCD plate.
lcd = Adafruit_CharLCDPlate()

# Clear display and show greeting, pause 1 sec
lcd.clear()
lcd.backlight(lcd.ON)
lcd.message("Welcome to your\ndoorbell")
sleep(1)


def internet_on():
    try:
        response = urllib2.urlopen('http://www.google.com', timeout=10)
        return True
    except urllib2.URLError as err:
        pass
    return False


lcd.clear()
예제 #27
0
class DisplayLoop(StreamListener):
    """
    This class is a listener for tweet stream data. It's also callable so it
    can run the main display thread loop to update the display.
    """
    PICKLE_FILE = '/home/pi/py/tweetbox.pkl'
    
    def __init__(self):
        self.lcd = Adafruit_CharLCDPlate()
        self.lcd.backlight(self.lcd.RED)
        self.lcd.clear()
        self.track_text = 'jeremy'
        self.backlight_map = {'red':self.lcd.RED,
                              'green':self.lcd.GREEN,
                              'blue':self.lcd.BLUE,
                              'yellow':self.lcd.YELLOW,
                              'teal':self.lcd.TEAL,
                              'violet':self.lcd.VIOLET}
        self.msglist = []
        self.pos = 0
        self.tweet = 'Nothing yet'
        
    def set_backlight(self):
        words = self.tweet.lower().split(' ')
        use_default = True
        for w in words:
            if w in self.backlight_map:
                self.lcd.backlight(self.backlight_map[w])
                use_default = False
                break    
        if use_default:
            self.lcd.backlight(self.lcd.WHITE)
        
    def on_data(self, data):
        print data
        tweet_data = json.loads(data)
        self.set_text(tweet_data['text'].encode('ascii', errors='backslashreplace'))
                 
    def set_text(self, text):
        self.tweet = text
        self.msglist = [x.ljust(16) for x in textwrap.wrap(str(self.tweet),16)]
        self.pos = 0
        self.set_backlight()
        self.scroll_message()
        return True

    def on_error(self, status):
        print status
        
    def write_message(self,msg):
        self.lcd.home()
        self.lcd.message(msg)

    def scroll_message(self):
        "Displays the page of text and updates the scroll position for the next call"
        if len(self.msglist) == 0:
            self.write_message(''.ljust(16)+'\n'+''.ljust(16))
        elif len(self.msglist) == 1:
            self.write_message(self.msglist[0]+'\n'+''.ljust(16))
        elif len(self.msglist) == 2:
            self.write_message(self.msglist[0]+'\n'+self.msglist[1])
        else:
            if self.pos >= len(self.msglist)-1:
                self.pos = 0
            else:
                self.write_message(self.msglist[self.pos]+'\n'+self.msglist[self.pos+1])
                self.pos+=1        
            
    def get_ip_address(self,interface):
        "Returns the IP address for the given interface e.g. eth0"
        try:
            s = subprocess.check_output(["ip","addr","show",interface])
            return s.split('\n')[2].strip().split(' ')[1].split('/')[0]
        except:
            return '?.?.?.?'        

    def write_config(self):
        data = {"track_text":self.track_text, "backlight_map":self.backlight_map}
        output = open(self.PICKLE_FILE, 'wb')
        pickle.dump(data, output)
        output.close()
        
    def read_config(self):
        if exists(self.PICKLE_FILE):
            pkl_file = open(self.PICKLE_FILE, 'rb')
            data = pickle.load(pkl_file)
            pkl_file.close()
            self.track_text = data["track_text"]
            self.backlight_map = data["backlight_map"]
        
    def __call__(self):
        while True:
            if self.lcd.buttonPressed(self.lcd.LEFT):
                self.write_message(self.get_ip_address('eth0').ljust(16)+'\n'+self.get_ip_address('wlan0').ljust(16))
            else:
                self.scroll_message()
            time.sleep(1)
예제 #28
0
def server():
    """
    """
    if args.simulate != True:
        lcd = Adafruit_CharLCDPlate()
        lcd.clear()
        lcd.message("MoodCloud v1.0!")
        time.sleep(1)

        btn = ((lcd.LEFT, 'Left.', lcd.ON),
                (lcd.RIGHT, 'Right.', lcd.ON),
                (lcd.UP, 'Up.', lcd.ON),
                (lcd.DOWN, 'Down.', lcd.ON),
                (lcd.SELECT, 'Select.', lcd.ON))

    logger.debug("Connecting to server at: %s:%d" % (args.server, args.port))

    pixel_output = bytearray(args.num_leds * PIXEL_SIZE)
    server = "http://%s:%d/" % (args.server, args.port)
    while True:
        serverpath = server + "data/"
        logger.debug("Grabbing next set of sentiment data from %s." % serverpath)
        
        data = json.loads(urllib2.urlopen(serverpath).read())
        if 'fields' not in data:
            logger.debug("No data sent")
            continue

        all_off()
        #logger.debug("Data: ")
        #logger.debug(json.dumps(data, sort_keys=True, indent=2))
        #logger.debug(data)

        ip = get_ip(server)
        
        if args.simulate != True:
            lcd.clear()
            if 'search_term' in data['fields']:
                lcd.message('%s\n%s' % (ip, data['fields']['search_term']))
            else:
                lcd.message('%s' % (ip))
        else:
            if 'search_term' in data['fields']:
                logger.debug("Search Term: %s" % (data['fields']['search_term']))

        logger.debug("Playing sounds...")
        moods = dict()
        for topic in data['fields']['topics']:
            if 'mood' in topic['fields']:
                mood = topic['fields']['mood']['fields']['label']
                if mood in moods.keys():
                    moods[mood] += 1
                else:
                    moods[mood] = 1

                logger.debug("Displaying...")
                idx = data['fields']['topics'].index(topic)
                string_length = 6
                color = topic['fields']['mood']['fields']['color']
                for i in range(6):
                    led = idx * string_length + i
                    current_color = array.array('B', color[1:7].decode("hex"))
                    pixel_output[led * PIXEL_SIZE:] = filter_pixel(current_color, 0.9)
                if args.simulate != True:
                    write_stream(pixel_output)
                    spidev.flush()  

            MAX_VOLUME = 0.95
            MIN_VOLUME = 0.25
            maxm = max(moods.values())
            minm = min(moods.values())
            logger.debug("Freq: Max %d Min %d" % (maxm, minm))
            scale = 1.0 - (maxm - minm) / (MAX_VOLUME - MIN_VOLUME)
            translate = maxm - MAX_VOLUME
            logger.debug("Scale: %f Translate: %f" % (scale, translate))
            for mood in moods:
                moods[mood] = moods[mood] / float(maxm)
                logger.debug("Setting %s to volume %f" % (mood, moods[mood]))
            for emotion, track in EMOTIONS.items():
                track.set_volume(0.0)
                if emotion in moods:
                    track.set_volume(moods[mood])
                else:
                    logger.debug("Leaving sounds another round.")
예제 #29
0
def handler(signum=None, frame=None):
    lcd = Adafruit_CharLCDPlate()
    lcd.clear()
    lcd.stop()
    sys.exit(0)
예제 #30
0
파일: fppLCD.py 프로젝트: darylc/fpp
class fppLCD():

  def __init__(self,directory):
    self.THIS_DIRECTORY = directory

    self.BACK_COLOR = 0
    self.PLAYLIST_DIRECTORY = "/home/pi/media/playlists/"
    self.SETTINGS_FILE = "/home/pi/media/settings"

    self.DIRECTION_LEFT = 0
    self.DIRECTION_RIGHT = 1
    self.MAX_CHARS = 16
    self.MAX_STATUS_TIMEOUT = 120
    self.NORMAL_STATUS_TIMEOUT = 3
    self.FPPD_PLAYER_MODE = "2"
    self.FPPD_BRIDGE_MODE = "1"
    self.maxStatusUpdateCount = 5
    self.statusUpdateCounter= 5
    self.FPPD_STATUS_STOPPED = -1
    self.FPPD_STATUS_RUNNING = 1
    self.FPPDstatus = 0
    self.FPPDplayerStatus = 0;
    # Status Constants
    self.STATUS_IDLE = "0"
    self.STATUS_PLAYING = "1"
    self.STATUS_STOPPING_GRACEFULLY = "2"
    
    self.STATUS_INX_PLAYER_MODE = 0
    self.STATUS_INX_STATUS = 1
    self.STATUS_INX_NEXT_PLAY_LIST = 3
    self.STATUS_INX_CURRENT_PLAY_LIST = 3
    self.STATUS_INX_NEXT_TIME = 4
    self.STATUS_INX_PL_TYPE = 4
    self.STATUS_INX_SEQ_NAME = 5
    self.STATUS_INX_SONG_NAME = 6
    self.STATUS_INX_SECS_ELASPED = 9
    self.STATUS_INX_SECS_REMAINING = 10
    
    
    # Text to display
    self.line1=""
    self.line2=""
    # Rotation Variables
    self.rotateEnable = 0
    self.tempLine1=""
    self.tempLine2=""
    self.rotatePositon1=0
    self.rotatePositon2=0
    self.rotateSpeed=0
    self.rotateCount=0
    self.rotateMaxCount=3
    self.fixedLocation1=0
    self.fixedLocation2=0

    self.lcd = Adafruit_CharLCDPlate()
    #self.lcd = VirtualLCD()

    self.lcd.noBlink()
    self.lcd.noCursor()
    self.lcd.clear()
    
    self.sequenceCount=0;
    self.sequences = ()
    
    self.playlists = ()
    self.selectedPlaylistIndex = 0
    self.MenuIndex=0;
    self.SubmenuIndex=0;

    self.MENU_INX_STATUS = 0
    self.MENU_INX_STOP_SEQUENCE = 1
    self.MENU_INX_PLAYLISTS = 2
    self.MENU_INX_PLAYLIST_ENTRIES = 3
    self.MENU_INX_SHUTDOWN_REBOOT = 4
    self.MENU_INX_BACKGROUND = 5
    self.MENU_INX_BACKCOLOR = 6
    self.MENU_INX_BACKCOLOR_TIMEOUT = 7

    self.COLOR_WHITE = 6

    self.TimeMode=0;
    self.TIMEMODE_ELASPED = 0
    self.TIMEMODE_REMAINING = 1
    
        
    self.BACKGROUND_ALWAYS_ON = 0
    self.BACKGROUND_TIMEOUT_ENABLED = 1
    self.BACKGROUND_TIMEOUT_MAX_COUNT = 1500
    self.BackgroundColor = 0
    self.BackgroundTimeout = 1          #self.BACKGROUND_TIMEOUT_ENABLED
    self.BackgroundTimeoutCount=0

    self.MENU_BACKCOLOR_TIMEOUT_COUNT = 2
    self.previousBtn = -1
    
    self.MENU_BACKGROUND_COUNT = 2
    self.menuBackground=("1)Color         ",
                         "2)Mode          ")
    
    self.MENU_COLOR_COUNT = 7
    self.colors=(("Red            ",self.lcd.RED),
                 ("Green          ",self.lcd.GREEN),
                 ("Blue           ",self.lcd.BLUE),
                 ("Yellow         ",self.lcd.YELLOW),
                 ("Teal           ",self.lcd.TEAL),
                 ("Violet         ",self.lcd.VIOLET),
                 ("White          ",self.lcd.WHITE))
    
    self.backgroundModes=("Always On       ",
                          "Timeout         ")

  def Initialize(self):
    strColorIndex = self.readSetting("piLCD_BackColor")
    if strColorIndex.isdigit():
      self.BackgroundColor = int(strColorIndex);
    else:
      self.BackgroundColor = self.COLOR_WHITE
    
    self.SelectColor(self.BackgroundColor);
    
    strTimeout = self.readSetting("piLCD_BackgroundTimeout")
    if strTimeout.isdigit():
      self.BackgroundTimeout = int(strTimeout);
    else:
      self.BackgroundTimeout = 1
    
    strTimeout = self.readSetting("piLCDtimeMode")
    if strTimeout.isdigit():
      self.TimeMode = int(strTimeout);
    else:
      self.TimeMode = 0
    
    version = fpplcd.getFPPversion()
    self.line1 = self.MakeStringWithLength("FPP Version",16,1);
    self.line2 = self.MakeStringWithLength(version,16,1);
    self.UpdateDisplay()
    time.sleep(4) 
    
    
    return 
    
  def SendCommand(self,command):
    count =0;
    max_timeout = 10;
    #buf=""
    # Create a UDS socket
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    sock.bind("/tmp/FPP" + str(os.getpid()))
    sock.settimeout(5)
    # Connect the socket to the port where the server is listening
    server_address = "/tmp/FPPD"
    #print >>sys.stderr, 'connecting to %s' % server_address
    try:
        sock.connect(server_address)
        sock.send(command)
        buf = sock.recv(1024)
        sock.close()
        os.unlink("/tmp/FPP" + str(os.getpid()));
        
    except socket.error, msg:
        #print >>sys.stderr, msg
        sock.close()
        os.unlink("/tmp/FPP" + str(os.getpid()));
        return "false"

    return buf;
예제 #31
0
class DisplayLoop(StreamListener):
    """
    This class is a listener for tweet stream data. It's also callable so it
    can run the main display thread loop to update the display.
    """
    def __init__(self):
        self.lcd = Adafruit_CharLCDPlate()
        self.lcd.backlight(self.lcd.RED)
        self.lcd.clear()
        self.backlight_map = {'clarkson':self.lcd.RED,
                              'pearl':self.lcd.GREEN,
                              'love':self.lcd.BLUE,
                              'hate':self.lcd.YELLOW,
                              'kyle':self.lcd.TEAL,
                              'like':self.lcd.VIOLET}
        self.msglist = []
        self.pos = 0
        self.tweet = 'Nothing yet'
        
    def set_backlight(self):
        words = self.tweet.lower().split(' ')
        use_default = True
        for w in words:
            if w in self.backlight_map:
                self.lcd.backlight(self.backlight_map[w])
                use_default = False
                break    
        if use_default:
            self.lcd.backlight(self.lcd.WHITE)
        
    def on_data(self, data):
        tweet_data = json.loads(data)
        self.tweet = tweet_data['text'].encode('ascii', errors='backslashreplace')
        self.msglist = [x.ljust(16) for x in textwrap.wrap(str(self.tweet),16)]
        self.pos = 0
        self.set_backlight()
        self.scroll_message()
        return True

    def on_error(self, status):
        print status
        
    def write_message(self,msg):
        self.lcd.home()
        self.lcd.message(msg)

    def scroll_message(self):
        "Displays the page of text and updates the scroll position for the next call"
        if len(self.msglist) == 0:
            self.write_message(''.ljust(16)+'\n'+''.ljust(16))
        elif len(self.msglist) == 1:
            self.write_message(self.msglist[0]+'\n'+''.ljust(16))
        elif len(self.msglist) == 2:
            self.write_message(self.msglist[0]+'\n'+self.msglist[1])
        else:
            if self.pos >= len(self.msglist)-1:
                self.pos = 0
            else:
                self.write_message(self.msglist[self.pos]+'\n'+self.msglist[self.pos+1])
                self.pos+=1        
            
    def get_ip_address(self,interface):
        "Returns the IP address for the given interface e.g. eth0"
        try:
            s = subprocess.check_output(["ip","addr","show",interface])
            return s.split('\n')[2].strip().split(' ')[1].split('/')[0]
        except:
            return '?.?.?.?'        
        
    def __call__(self):
        while True:
            if self.lcd.buttonPressed(self.lcd.LEFT):
                self.write_message(self.get_ip_address('eth0').ljust(16)+'\n'+self.get_ip_address('wlan0').ljust(16))
            else:
                self.scroll_message()
            time.sleep(1)
예제 #32
0
class WatchBox():

    # Begin Extended from Adafruit_CharLCDPlate -------------------------------
    # Port expander input pin definitions
    SELECT = 0
    RIGHT = 1
    DOWN = 2
    UP = 3
    LEFT = 4

    btn = (
        (SELECT, 'Select'),
        (LEFT, 'Gauche'),
        (UP, 'Haut'),
        (DOWN, 'Bas'),
        (RIGHT, 'Droite')
    )

    # LED colors
    COLORS = {}
    COLORS['OFF'] = 0x00
    COLORS['RED'] = 0x01
    COLORS['GREEN'] = 0x02
    COLORS['BLUE'] = 0x04
    COLORS['YELLOW'] = 0x01 + 0x02
    COLORS['TEAL'] = 0x02 + 0x04
    COLORS['VIOLET'] = 0x01 + 0x04
    COLORS['WHITE'] = 0x01 + 0x02 + 0x04
    COLORS['ON'] = 0x01 + 0x02 + 0x04
    # END Extended from Adafruit_CharLCDPlate ---------------------------------

    curMenuIndex = 'MAIN' # Level
    previousMenuIndex = ''
    curMenuPosition = 0 # Position dans le menu actuel
    cursorStyle = "=> "
    menuSize = 0

    menuSequence = {} # Contient l'arborescence complète parcouru
    curIndexMenuSequence = 0
    menu = {} # Contient la liste des éléments permettant de générer le menu
    menu['MAIN'] = (
        ( 'Run' , 'START' ),
        ( 'Settings' , 'SETTINGS' ),
        ( 'About' , 'ABOUT' ),
        ( 'Quit' , 'QUIT' )
    )
    menu['SETTINGS'] = (
        ( 'Color' , 'COLORS' ),
        ( 'Back' , 'BACK' )
    )
    menu['COLORS'] = (
        ( 'Red' , 'RED' ),
        ( 'Green' , 'GREEN' ),
        ( 'Blue' , 'BLUE' ),
        ( 'Yellow' , 'YELLOW' ),
        ( 'Teal' , 'TEAL' ),
        ( 'Violet' , 'VIOLET' ),
        ( 'White' , 'WHITE' ),
        ( 'Back' , 'BACK' )
    )

    isStarted = False

    lcd = ''
    config = ''

    ''' Redéfinition des méthodes de la classe Adafruit pour gagner du temps dans l'écriture '''
    def backlight(self , backlight):
        _backlight = self.COLORS[backlight]
        self.lcd.backlight( _backlight )
    def clear(self):
        self.lcd.clear()
    def message(self,msg):
        self.lcd.message(msg)
    def buttonPressed(self,btn):
        return self.lcd.buttonPressed(btn)
    def scrollDisplayLeft(self):
        self.lcd.scrollDisplayLeft()
    def numlines(self):
        return self.lcd.numlines

    '''
        Fonctions servant pour la gestion du Menu
    '''

    ''' Fonction permettant d'initialiser la gestion du menu '''
    def InitMenu(self):
        self.lcd = Adafruit_CharLCDPlate()
        self.lcd.begin(16, 2)
        self.isStarted = True
        # Initialisation du Menu
        self.menuSequence[self.curIndexMenuSequence] = 'MAIN'
        self.initMenuSize()
        self.readConfigFile()

    ''' Fonction permettant d'initialiser le rétro éclairage de l'écran'''
    def initBacklight(self):
        backlight = self.config.get('Main','backlight')
        self.backlight( backlight )

    ''' Fonction permettant d'initialiser le nombre d'éléments dans le menu courant '''
    def initMenuSize(self):
        self.menuSize = len(self.menu[self.menuSequence[self.curIndexMenuSequence]])

    ''' Fonction permettant d'afficher les éléments du menu / de gérer les actions '''
    def getItems( self , btn ):
        curIndex = self.curMenuPosition # On récupère la position actuelle dans le menu

        # Gestion du bouton
        if btn == self.lcd.SELECT: # Le bouton "select" est appuyé
            curMenuIndex = self.menuSequence[self.curIndexMenuSequence]

            # Il faut effectuer l'action demandée associée au menu courant
            if self.menu[curMenuIndex][curIndex][1] == 'QUIT' :
                self.ActionQuit()
                return True
            if self.menu[curMenuIndex][curIndex][1] == 'ABOUT' :
                self.ActionAbout()
                return True
            if self.menu[curMenuIndex][curIndex][1] == 'BACK' :
                if self.menuSequence[self.curIndexMenuSequence] != 'MAIN':
                    self.curIndexMenuSequence-=1
                    self.initMenuSize()
                    self.getItems( -1 )
                return True
            if curMenuIndex == 'COLORS' : # Demande de changement de couleur du rétro éclairage
                color = self.menu[curMenuIndex][curIndex][1]
                self.writeConfigFile('Main','backlight',color)
                self.backlight( color )
                self.getItems( -1 )
                return True
            if self.menu[self.menu[curMenuIndex][curIndex][1]] : # On regarde si l'action est associée à un sous menu
                CurrentmenuNameIndexed = self.menuSequence[self.curIndexMenuSequence]
                NextmenuNameIndexed = self.menu[curMenuIndex][curIndex][1]
                print("Current Index :"+CurrentmenuNameIndexed)
                print("Next Index : "+NextmenuNameIndexed)
                self.menuSequence[self.curIndexMenuSequence] = CurrentmenuNameIndexed # On stocke l'id du menu actuel
                self.curIndexMenuSequence+=1 # On déplace le pointer vers la droite
                self.menuSequence[self.curIndexMenuSequence] = NextmenuNameIndexed # On stocke l'id du nouveau menu
                self.initMenuSize() # On recalcule le nombre d'éléments dans le menu
                self.curMenuPosition = 0 # On se place au premier élément du nouveau menu
                self.getItems( -1 ) # On affiche le menu
                return True

        else:
            self.lcd.clear()
            if btn == self.lcd.DOWN:
                curIndex+=1
            if btn == self.lcd.UP:
                curIndex-=1

            # Cas des sortie du menu (haut / bas)
            if curIndex < 0:
                curIndex = self.menuSize-1
            if curIndex >= self.menuSize:
                curIndex = 0

            # Génération du texte à afficher
            print(self.menu[self.menuSequence[self.curIndexMenuSequence]][curIndex][0])
            msg = self.cursorStyle + self.menu[self.menuSequence[self.curIndexMenuSequence]][curIndex][0]+"\n"
            if (curIndex+1) != self.menuSize:
                msg+= self.menu[self.menuSequence[self.curIndexMenuSequence]][(curIndex+1)][0]

            # Mise à jours de la position courante du curseur dans menu
            self.curMenuPosition = curIndex

            # On affiche le texte sur l'afficheur
            print(msg)
            self.clear()
            self.message(msg)



    ''' Action permettant de quitter l'application '''
    def ActionQuit(self):
        self.isStarted = False
        self.message("Bye...")
        print("Ending application...")

    ''' Action permettant d'afficher le About '''
    def ActionAbout(self):
        msg = ( 'Test Application Adafruit' , 'Damien Broqua < *****@*****.**>' )
        stringSize = len(msg[0])
        if len(msg[1]) > stringSize:
            stringSize = len(msg[1])

        loop = True
        maxloop = stringSize - self.numlines() + 1
        counterScroll = 0
        self.lcd.clear()
        wait = True
        while loop == True:
            self.message( msg[0]+"\n"+msg[1])
            if stringSize > self.numlines():
                sleep(0.5)
                self.scrollDisplayLeft()
                counterScroll+=1
            else:
                sleep(4)
                loop = False

            if counterScroll > maxloop:
                loop = False

            if self.buttonPressed(self.lcd.LEFT): # L'utilisateur appuie sur le bouton de gauche pour revenir au menu précédent
                wait = False
                loop = False

        if wait == True: # L'utilisateur n'a pas appuyé sur le bouton de gauche, on lui ré affiche pendant 2 secondes le message initial
            sleep(2) # Petite pause pour revoir le message initial

        self.curMenuIndex = 'MAIN' # On se repositionne sur le menu principal
        self.getItems(-1) # On affiche le menu principal


    def readConfigFile(self):
        try:
            with open('config.cfg'):
                self.config = ConfigParser.RawConfigParser()
                self.config.read('config.cfg')
        except IOError:
            self.createConfigFile()

    def createConfigFile(self):
        # Initialisation des variables sauvegardées
        self.config = ConfigParser.RawConfigParser()
        self.config.add_section('Main')
        self.config.set('Main', 'backlight', 'RED')

        # Writing our configuration file to 'example.cfg'
        with open('config.cfg', 'wb') as configfile:
            self.config.write(configfile)

    def writeConfigFile(self , section , col , value ):
        self.config.set(section,col,value)
        with open('config.cfg', 'wb') as configfile:
            self.config.write(configfile)
예제 #33
0
파일: monitor.py 프로젝트: sudoer/doorman
if not os.path.exists(tmpdir):
    os.makedirs(tmpdir)
tmpdir = os.path.dirname(preferences.get('longTriggerFile'))
if not os.path.exists(tmpdir):
    os.makedirs(tmpdir)

cmd = [ '/bin/bash', '-c', 'ip addr show dev wlan0 | grep -o "inet [0-9.]*" | sed -e "s/inet //g"' ]
(rc,stdout,stderr) = shell_capture(cmd)
ipAddr = stdout.rstrip('\n')
log_info("IP address = '"+ipAddr+"'")

while True:
    try:
        monitor()
    except KeyboardInterrupt:
        g_lcd.clear()
        g_lcd.message('OUT OF SERVICE')
        g_lcd.backlight(g_lcd.OFF)
        print ""
        print "GAME OVER"
        break
    except:
        print "Unexpected error:", sys.exc_info()[0]
        print 'traceback:'
        print traceback.format_exc()
    time.sleep(10)

#END

#-----------------------------------------------------------
예제 #34
0
class TestBot(irc.bot.SingleServerIRCBot):
    def __init__(self, channel, nickname, server, port=6667,password=None):
        irc.bot.SingleServerIRCBot.__init__(self, [irc.bot.ServerSpec(server,port,password)], nickname, nickname)
        self.channel = channel
        # Create a mutex to handle our calls to the LCD
        self.lcdmutex = threading.RLock()
        # And initialize the various properties.
        with self.lcdmutex:
            self.lcd = Adafruit_CharLCDPlate()
            self.lcd.clear()
            self.lcd.backlight(self.lcd.ON)
            self.line1 = "INFO: INIT"
            self.line2 = "IRC Spy v1.0"
            self.lcd.message("{0:<16}\n{1:<16}".format(self.line1,self.line2))

            self.startpause = 3 # This causes the message to pause 3 extra ticks at the start. Write to it to change this delay.
            self.endpause = 3 # This causes the message to pause 3 extra ticks at the end. Write to it to change this delay.
            self.line1offset = -self.startpause
            self.line2offset = -self.startpause
        self.manifold.execute_every(.2,self._do_lcd)

    def _set_line1(self,text):
        with self.lcdmutex:
            self.line1 = text
            self.line1offset = -self.startpause

    def _set_line2(self,text):
        with self.lcdmutex:
            self.line2 = text
            self.line2offset = -self.startpause

    def _do_lcd(self):
        # Important to know: The offsets are deliberately run off the ends, both forward and backwards, to allow for some delay at the beginning
        # and end of the scroll. The cached values have the actual offsets that will be used to access the arrays and are properly monitored to
        # ensure that they're correctly in bounds.
        # The offset of an 18 character line will follow the following path:
        #  offset: -3 -2 -1  0  1  2  3  4  5 -3 -2 -1  0  1 etc...
        # loffset:  0  0  0  0  1  2  2  2  2  0  0  0  0  1 etc...
       
        with self.lcdmutex:
            # Cache the two offsets
            l1offset = self.line1offset
            l2offset = self.line2offset
            # Order is important here, the first one can make vastly negative numbers for short messages. The second will truncate that to 0.
            # Start by making sure we don't go off the end.
            if l1offset > len(self.line1)-16:
                l1offset = len(self.line1)-16
            if l2offset > len(self.line2)-16:
                l2offset = len(self.line2)-16
            # Then check to make sure we aren't off the beginning as well.
            if l1offset < 0:
                l1offset = 0
            if l2offset < 0:
                l2offset = 0
            
            # Build up a message string with exactly 16 characters for each line. This will purge things without the flicker
            # of a clear() command since it causes an overwrite.
            msg = "{0:<16}\n{1:<16}".format(self.line1[l1offset:l1offset+16],self.line2[l2offset:l2offset+16])
            # Move the write cursor to the beginning and write out the message
            self.lcd.home()
            self.lcd.message(msg)

            # If we should be scrolling, move the offset ahead by one.
            if len(self.line1) > 16:
                self.line1offset = self.line1offset + 1
            if len(self.line2) > 16:
                self.line2offset = self.line2offset + 1
            # If we've gone off the end, plus some for the end of line delay, the reset back with enough for the start of line delay.
            if self.line1offset > len(self.line1)-16+self.endpause:
                self.line1offset = -self.startpause
            if self.line2offset > len(self.line2)-16+self.endpause:
                self.line2offset = -self.startpause
    def _dehost_nick(self, nick):
        return nick.split("!")[0]        

    def on_action(self,c,e):
        self.lcd.clear()
        self._set_line1("*ACTION>" +e.target)
        self._set_line2(self._dehost_nick(e.source) + " " + e.arguments[0])
        return 

    def on_disconnect(self,c,e):
        print "Disconnected!"
        self._set_line1("ERROR:")
        self._set_line2("Disconnected")

    def on_passwdmismatch(self,c,e):
        print "Password rejected!"
        self._set_line1("ERROR:")
        self._set_line2("Bad Password")
        
    def on_nicknameinuse(self, c, e):
        c.nick(c.get_nickname() + "_")

    def on_welcome(self, c, e):
        print "Connected. Joining channel " + self.channel + "..."
	self._set_line1("INFO: CONNECT")
        self._set_line2("Joining...")
        c.join(self.channel)

    def on_join(self, c, e):
        print self._dehost_nick(e.source) + " joined " + e.target;
        self._set_line1("INFO: JOIN")
        self._set_line2(self._dehost_nick(e.source) + ">" + e.target);
    
    def on_part(self, c, e):
        print self._dehost_nick(e.source) + " left " + e.target;
        self._set_line1("INFO: PART")
        self._set_line2(self._dehost_nick(e.source) + ">" + e.target);

    def on_quit(self, c, e):
        print self._dehost_nick(e.source) + " quit.";
        self._set_line1("INFO: QUIT")
        self._set_line2(self._dehost_nick(e.source) + ">" + e.arguments[0]);

    def on_privmsg(self, c, e):
        self._set_line1(self._dehost_nick(e.source) + ">" + self._dehost_nick(e.target))
        self._set_line2(e.arguments[0])
        return 

    def on_pubmsg(self, c, e):
        self._set_line1(self._dehost_nick(e.source) + ">" + e.target)
        self._set_line2(e.arguments[0])
        return 
예제 #35
0
파일: PiLCD.py 프로젝트: CymaSpace/python
#!/usr/bin/python

from time import sleep
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate

import subprocess, glob, os, commands

# Initialize the LCD plate.  Should auto-detect correct I2C bus.  If not,
# pass '0' for early 256 MB Model B boards or '1' for all later versions
lcd = Adafruit_CharLCDPlate()
lcd.backlight(lcd.ON)
# Clear display and show greeting, pause 1 sec
lcd.clear()
lcd.message("HELLO!\nMAKE SELECTION")

# Poll buttons, display message & set backlight accordingly
btn = ((lcd.LEFT  , '' ),
       (lcd.UP    , '' ),
       (lcd.DOWN  , '' ),
       (lcd.RIGHT , '' ),
       (lcd.SELECT, '' ))

def mySleep(amt=0.5):
  sleep(amt)

LOCK_OFFSET = 0
SCROLL_LOCK = False
IS_FLASHING = False
BOX_IP = commands.getoutput("/home/pi/myip.sh")

def myScrollDisplayLeft():
예제 #36
0
class DisplayIPAddressDaemon:
	# initialize the LCD plate
	#   use busnum = 0 for raspi version 1 (256MB)
	#   and busnum = 1 for raspi version 2 (512MB)
	LCD = ""
#	lcd = ""

	# Define a queue to communicate with worker thread
	LCD_QUEUE = ""

	# Globals
	astring = ""
	setscroll = ""

	# Buttons
	NONE           = 0x00
	SELECT         = 0x01
	RIGHT          = 0x02
	DOWN           = 0x04
	UP             = 0x08
	LEFT           = 0x10
	UP_AND_DOWN    = 0x0C
	LEFT_AND_RIGHT = 0x12

	def __init__(self):
		self.LCD = Adafruit_CharLCDPlate(busnum = 0)
#		self.lcd = Adafruit_CharLCDPlate()
		self.LCD_QUEUE = Queue()
		
		self.stdin_path = '/dev/null'
		self.stdout_path = '/dev/tty'
		self.stderr_path = '/dev/tty'
		self.pidfile_path =  '/var/run/testdaemon.pid'
		self.pidfile_timeout = 5

	# ----------------------------
	# WORKER THREAD
	# ----------------------------

	# Define a function to run in the worker thread
	def update_lcd(self,q):
   
	   while True:
	      msg = q.get()
	      # if we're falling behind, skip some LCD updates
	      while not q.empty():
	        q.task_done()
	        msg = q.get()
	      self.LCD.setCursor(0,0)
	      self.LCD.message(msg)
	      q.task_done()
	   return



	# ----------------------------
	# MAIN LOOP
	# ----------------------------

	def run(self):

	   global astring, setscroll

	   # Setup AdaFruit LCD Plate
	   self.LCD.begin(16,2)
	   self.LCD.clear()
	   self.LCD.backlight(self.LCD.ON)

	   # Create the worker thread and make it a daemon
	   worker = Thread(target=self.update_lcd, args=(self.LCD_QUEUE,))
	   worker.setDaemon(True)
	   worker.start()
	
	   self.display_ipaddr()

	def delay_milliseconds(self, milliseconds):
	   seconds = milliseconds / float(1000)   # divide milliseconds by 1000 for seconds
	   sleep(seconds)

	# ----------------------------
	# DISPLAY TIME AND IP ADDRESS
	# ----------------------------

	def display_ipaddr(self):
	   show_eth0 = "ip addr show eth0  | cut -d/ -f1 | awk '/inet/ {printf \"e%15.15s\", $2}'"
	   ipaddr = self.run_cmd(show_eth0)

	   self.LCD.backlight(self.LCD.ON)
	   i = 29
	   muting = False
	   keep_looping = True
	   while (keep_looping):

	      # Every 1/2 second, update the time display
	      i += 1
	      #if(i % 10 == 0):
	      if(i % 5 == 0):
	         self.LCD_QUEUE.put(datetime.now().strftime('%b %d  %H:%M:%S\n')+ ipaddr, True)

	      # Every 3 seconds, update ethernet or wi-fi IP address
	      if(i == 60):
	         ipaddr = self.run_cmd(show_eth0)
	         i = 0

	      self.delay_milliseconds(99)

	# ----------------------------

	def run_cmd(self,cmd):
	   p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
	   output = p.communicate()[0]
	   return output