Example #1
0
    def __init__(self, leds, switches, countdown, game_time, score_increment):
        self.LEDS = leds
        self.SWITCHES = switches
        self.COUNTDOWN = countdown
        self.GAME_TIME = game_time
        self.SCORE_INCREMENT = score_increment

        self.gpio = Gpio
        self.lcd = Lcd()
        self.db = TinyDB('data/database.json')

        if len(self.LEDS) != len(self.SWITCHES):
            print(
                "[Game][error] There isn't the same number of LEDS as SWITCHES"
            )
            exit()

        try:
            self.gpio.setmode(self.gpio.BCM)

            for switch in self.SWITCHES:
                self.gpio.setup(switch, self.gpio.IN)
                self.gpio.add_event_detect(switch,
                                           self.gpio.RISING,
                                           bouncetime=300)
                self.gpio.add_event_callback(switch, self.__button_press)

            for led in self.LEDS:
                self.gpio.setup(led, self.gpio.OUT)
                self.gpio.output(led, False)
        except AttributeError:
            print("[Game][error] An error occurred initialising game")
Example #2
0
    def __init__(self):
        """ constructeur """
        print('Démarrage jeux ... ')
        self.lcd = Lcd()  # affichage LCD du jeux
        self.lcd.write_char('robot_ok', pos=(0, 0))
        self.lcd.msg_centre('SinS', 'Initialisation')
        self.lcd.write_char('robot_ok', pos=(15, 0))
        self.buzzer = Buzz()  # buzzer du jeux
        self.rackleds = RackLeds()  # rack de leds
        self.rackbuttons = RackButtons(self.rackleds,
                                       self.buzzer)  # rack de boutons
        self.color = ['V', 'B', 'J', 'R']  # couleur du jeux
        self.dic_color = {'V': 0, 'B': 1, 'J': 2, 'R': 3}
        self.file_scores = '/flash/scores.txt'  # fichier des records
        self.scores = self.read_scores()  # dictionnaire des record
        self.total_keys = 10  # nb_clés à trouver

        #mode de difficulté du jeux
        self.dic_mode = {
            'V': ['Vert', 'Facile'],
            'B': ['Bleu', 'Moyen'],
            'J': ['Jaune', 'Difficile'],
            'R': ['Rouge', 'Expert'],
        }
        self.mode = 'V'

        self.nb_portes = 3  # nb de portes par niveau à ouvrir
        self.niveau = self.nb_portes  # nb de leds dans la séquence en cours
        self.init_seq()  # initialise séquences
Example #3
0
    def __init__(self, config, core):
        super(TestFrontend, self).__init__()
        self.core = core

        self._now_playing_track = None
        self.lcd = Lcd()
        self.radioMenu = RadioMenu(self.lcd, self)

        logger.info("My plugin has loaded!")

        # set up fallback image
        self.plugin_dir = os.path.dirname(os.path.realpath(__file__))
        self.fallback_image = self.plugin_dir + "/images/on_the_air.jpg"

        self.radioMenu.loading()
Example #4
0
File: car.py Project: berickson/car
 def __init__(self, online = True):
   self.config_path = 'car.ini'
   self.read_configuration()
   self.online = online
   self.reset_odometry()
   self.listener = None
   self.last_verified_velocity = 0.0
   self.lcd = None
   self.usb_error_count = 0
   self.input_recording_file = None
   self.commands_recording_file = None
   
   if self.online:
     from lcd import Lcd
   
     self.lcd = Lcd()
     self.quit = False
     self.write_command('td+') # first command normally fails, so write a blank command
     self.write_command('td+')
     self.output_thread = threading.Thread(target=self._monitor_output, args = ())
     self.output_thread.daemon = True
     self.output_thread.start()
     while self.dynamics.reading_count == 0:
       time.sleep(0.01) 
Example #5
0
class Jeux_sins():
    """ classe gestion du jeux  """
    def __init__(self):
        """ constructeur """
        print('Démarrage jeux ... ')
        self.lcd = Lcd()  # affichage LCD du jeux
        self.lcd.write_char('robot_ok', pos=(0, 0))
        self.lcd.msg_centre('SinS', 'Initialisation')
        self.lcd.write_char('robot_ok', pos=(15, 0))
        self.buzzer = Buzz()  # buzzer du jeux
        self.rackleds = RackLeds()  # rack de leds
        self.rackbuttons = RackButtons(self.rackleds,
                                       self.buzzer)  # rack de boutons
        self.color = ['V', 'B', 'J', 'R']  # couleur du jeux
        self.dic_color = {'V': 0, 'B': 1, 'J': 2, 'R': 3}
        self.file_scores = '/flash/scores.txt'  # fichier des records
        self.scores = self.read_scores()  # dictionnaire des record
        self.total_keys = 10  # nb_clés à trouver

        #mode de difficulté du jeux
        self.dic_mode = {
            'V': ['Vert', 'Facile'],
            'B': ['Bleu', 'Moyen'],
            'J': ['Jaune', 'Difficile'],
            'R': ['Rouge', 'Expert'],
        }
        self.mode = 'V'

        self.nb_portes = 3  # nb de portes par niveau à ouvrir
        self.niveau = self.nb_portes  # nb de leds dans la séquence en cours
        self.init_seq()  # initialise séquences

    def init_seq(self):
        """ réinitialise les séquences à vide"""
        self.seq_led_droid = []
        self.seq_led_joueur = []
        #seed(randint(0,32000))  #initialize random number generator
        t = utime.localtime()  #format (y,m,d,h,m,s,ss,sss)
        s = t[3] * 3600 + t[4] * 60 + t[5]  # conversion hh:mn:ss en secondes
        seed(s % 2048)  # initialise table random non reproductibles

    def add_seq(self):
        """ ajoute une séquence de nb_portes aléatoires au jeux"""
        for _ in range(self.nb_portes):
            self.seq_led_droid.append(self.color[randint(0, 3)])

    def nouvelle_seq(self):
        """ détermine la nouvelle séquence de couleurs à trouver"""
        self.seq_led_joueur = []  # remise à zéro de la séquence du joueur
        if self.mode in ['J', 'R']:  # séquences aléatoires depuis le début
            self.seq_led_droid = []
            for n in range(self.niveau // self.nb_portes):
                self.add_seq()
        else:  # sinon on ajoute nb_portes couleurs au hasard
            self.add_seq()

    def add_sequence_joueur(self, color):
        """ ajoute la couleur jouée par le joueur"""
        self.seq_led_joueur.append(color)

    def read_scores(self):
        """ retourne le dictionaires des records à battre par mode V,B,J,R"""
        dic_scores = {'V': 0, 'B': 0, 'J': 0, 'R': 0}  #scores par niveaux
        try:
            with open(self.file_scores, 'r') as f:
                for line in f.readlines():
                    l = line.strip()
                    mode, score = l[0], int(l[2:])
                    dic_scores[mode] = score
        except:  #création du fichier score.txt s'il n'existe pas
            print('création fichier des scores')
            self.write_scores(dic_scores)
        print('record à battre par mode:', dic_scores)
        return dic_scores

    def write_scores(self, scores):
        """ sauvegarde des record à battre"""
        with open(self.file_scores, 'w') as f:
            f.write('V:' + str(scores['V']) + '\n')
            f.write('B:' + str(scores['B']) + '\n')
            f.write('J:' + str(scores['J']) + '\n')
            f.write('R:' + str(scores['R']) + '\n')

    def loop(self):
        """ boucle principale du jeux"""
        while True:
            #initialisations
            self.init_seq()
            self.niveau = self.nb_portes
            self.lcd.clear()
            self.rackbuttons.desactivate_buzzer()
            self.lcd.msg_centre('Choix du mode', 'Quelle couleur ?')

            # choix du mode de jeux
            self.rackbuttons.pressed = False
            while not (self.rackbuttons.pressed
                       ):  #attente appui sur un bouton du rack
                time.sleep(0.2)
            self.mode = self.rackbuttons.button_pressed
            self.lcd.clear()
            self.lcd.msg_centre('Tu as choisi',
                                'mode: ' + self.dic_mode[self.mode][1])
            if self.mode in ['V', 'J']:
                self.rackbuttons.activate_buzzer(
                )  #buzzer activé uniquement pour les modes V et J
            time.sleep(2)
            self.lcd.clear()

            #boucle de jeux tant que le joueur trouve la bonne séquence
            continuer = True
            while (continuer):
                #création d'une nouvelle séquence à trouver
                self.nouvelle_seq()
                #self.lcd.msg('Niveau:'+str(self.niveau), 'Record:'+ str(self.scores[self.mode]))
                self.lcd.msg('Niveau:', 'Record:')
                self.lcd.write_key(self.niveau // self.nb_portes, 0)  # niveau
                self.lcd.write_key(self.scores[self.mode],
                                   1)  # record du mode joué
                time.sleep(1)

                #affichage de la séquence à trouver
                for rang, color in enumerate(self.seq_led_droid):
                    self.rackleds.get_led(color).smooth_on()  # led allumée
                    if self.mode in ['V', 'J']:
                        self.buzzer.buzzId(
                            color
                        )  # son correspondant à la couleur uniquement pour les modes V et J
                    time.sleep(0.5)  # temps d'attente en 2 leds
                    self.buzzer.mute()  # buzzer mute
                    self.rackleds.get_led(color).smooth_off()  # led éteinte
                    time.sleep(0.5)  # temps d'attente
                    if (
                            rang + 1
                    ) % self.nb_portes == 0:  # attente supplémentaires entre 2 séries de nb_portes
                        time.sleep(0.3)

                #mémorisation séquence du joueur
                #print('à toi de jouer')
                self.rackbuttons.pressed = False
                for n in range(self.niveau):
                    #attente qu'un bouton du rack de boutons soit pressée
                    while not (self.rackbuttons.pressed):
                        time.sleep(0.2)
                    self.add_sequence_joueur(self.rackbuttons.button_pressed)
                    self.rackbuttons.pressed = False
                #print('Voici ton jeu: ', self.jeux.seq_led_joueur)
                #comparaison des listes
                self.rackbuttons.pressed = True  #empêche la saisie sur une touche
                time.sleep(1)
                if (self.seq_led_joueur == self.seq_led_droid):
                    #print('Bien joué! niveau suivant')
                    self.rackleds.win()  #animation gagné
                    if (self.scores[self.mode] < self.niveau //
                            self.nb_portes):  # le record du mode est battu
                        self.scores[
                            self.
                            mode] = self.niveau // self.nb_portes  # maj du dictionnaire des records
                        self.write_scores(
                            self.scores)  # enregistrement des records
                    if self.niveau == self.total_keys * self.nb_portes:
                        # toutes les clés sont trouvées
                        self.buzzer.welcome_sound()
                        self.lcd.clear()
                        self.lcd.msg_centre('BRAVO!')
                        self.lcd.write_char('robot_ok', pos=(0, 0))
                        self.lcd.write_char('robot_ok', pos=(15, 0))
                        for n in range(10):
                            self.lcd.write_char('key', pos=(3 + n, 1))
                            time.sleep(0.3)
                        time.sleep(2)
                        continuer = False
                    else:
                        self.niveau += self.nb_portes
                else:
                    #print('Perdu!')
                    self.lcd.clear()
                    self.lcd.msg_centre('Et non!')
                    for l in range(6, 9):
                        self.lcd.write_char('robot_ko', pos=(l, 1))
                    self.buzzer.loose_sound()
                    self.rackleds.loose()  # animation perdu
                    time.sleep(1)
                    continuer = False
Example #6
0
import ubinascii
import time
import machine
import json
from connect import Connect
from led_pwm import LedPwm
from lcd import Lcd
from temperature_dht11 import TemperatureSensor as Dht
from mqtt import Mqtt
dht = Dht(4)
led = LedPwm(2)
lcd = Lcd(spi=1, cs=2, dc=15, rst=0, bl=12)
config = json.loads(open('config.json').read())
client_id = ubinascii.hexlify(machine.unique_id())
try:
    mqtt = Mqtt(client_id, config['broker_ip'])
except:
    mqtt = False
while True:
    # Connect to wifi
    Connect.check_and_reconnect()
    try:
        data = {
            'temperature': dht.read_temp_and_hum()[0],
            'humidity': dht.read_temp_and_hum()[1]
        }
        print(str(time.localtime()) + ' ' + str(data))
        if not mqtt:
            try:
                mqtt = Mqtt(client_id, config['broker_ip'])
Example #7
0
#!/usr/bin/python
import RPi.GPIO as GPIO
import os
import time
from lcd import Lcd
from temperatureSensor import TemperatureSensor
from log import Logger

def get_immediate_subdirectories(a_dir):
    return [name for name in os.listdir(a_dir)
            if os.path.isdir(os.path.join(a_dir, name))]

if __name__ == "__main__":
    #Initialize lcd and test screen 
    lcd = Lcd()
    #Init Logger
    logger = Logger("PF3I0333ITSWQ97W")

    #Get all sensor name 
    subdir = get_immediate_subdirectories("/sys/bus/w1/devices")
    temperatureSensor = []
    for dir in subdir:
        if(dir != "w1_bus_master1"):
            temperatureSensor.append(TemperatureSensor(dir))
    while(1):
        #display sensor temperature 
        lcd.lcd_string(temperatureSensor[0].read(),1)
        lcd.lcd_string(temperatureSensor[1].read(),2)
        #Update push data in api for each sensor
        #We have to push to thingspeek and local database
        logger.write(temperatureSensor[0].read(),"field1")
Example #8
0
#!/usr/bin/env python

import time
import grovepi
from pir import *
from lcd import Lcd
from stats import GoalCounter
from anhem import Anhem

class Logger:
  def notify(self, event):
    print "GOAL!"

logger = Logger()
lcd = Lcd()
kogut = DigitalPrinter(8)
anhem = Anhem(4)

leftGoals = GoalCounter()
rightGoals = GoalCounter()

leftPir = Pir(5, [logger, leftGoals, kogut, anhem])
rightPir = Pir(6, [logger, rightGoals, kogut, anhem])

leftPir.start()
rightPir.start()

while True:
  time.sleep(1)
  lcd.notify(str(leftGoals.goals()) + " - " + str(rightGoals.goals()))
Example #9
0
        player.previous()
    elif buttons == Lcd.BUTTON_RIGHT:
        player.next()
    elif buttons == Lcd.BUTTON_UP:
        if player.getStatus() == "playing":
            player.pause()
        else:
            player.play()

logging.basicConfig(filename=LOG_FILE, format=LOG_FORMAT, level=LOG_LEVEL)
logging.info("Starting BluePlayer")

#gobject.threads_init()
#dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

lcd = Lcd()
lcd.begin(16, 2, handler=navHandler)
lcd.backlight(Lcd.TEAL)
lcd.clear()
lcd.writeLn("Starting", 0)
lcd.writeLn("BluePlayer", 1)
time.sleep(2)

player = None
try:
    player = BluePlayer(lcd)
    player.start()
except KeyboardInterrupt as ex:
    logging.info("BluePlayer cancelled by user")
except Exception as ex:
    logging.error("How embarrassing. The following error occurred {}".format(ex))
Example #10
0
    def __init__(self):

        # Inicialização de logging
        self.logger = logging.getLogger('Apontamento')
        self.logger.setLevel('DEBUG')
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler = TimedRotatingFileHandler(
            'apontamento.log', when='d', interval=1, backupCount=30)
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

        self.lcd = Lcd()
        self.cp = configparser.ConfigParser()

        try:
            self.cp.read('config.ini')
        except Exception as e:
            self.logger.error('Erro ao recuperar informações de configuração')
            self.lcd.write_line('Erro', 0, 1, 1)
            sys.exit()

        self.logger.info('Inicializando')

        server = self.cp.get('sistema', 'server')
        database = self.cp.get('sistema', 'database')
        user = self.cp.get('sistema', 'user')
        pwd = self.cp.get('sistema', 'password')

        self.logger.info('Incialização da base de dados')

        self.db = Database(server, database, user, pwd)

        self.logger.info('Carregando dados de apontamento')

        self.codemp = int(self.cp.get('apontamento', 'codemp'))
        self.codfil = int(self.cp.get('apontamento', 'codfil'))
        self.codope = int(self.cp.get('apontamento', 'codope'))
        self.codori = self.cp.get('apontamento', 'codori')
        self.numorp = int(self.cp.get('apontamento', 'numorp'))
        self.qtdprv = int(self.cp.get('apontamento', 'qtdprv'))
        self.qtdfrd = int(self.cp.get('apontamento', 'qtdfrd'))
        self.numfrd = int(self.cp.get('apontamento', 'numfrd'))

        self.last_codbar = 0
        self.logger.info('Início da leitura do código de barras')

        try:
            while True:
                self.status()
                codbar: str = input()
                self.logger.info('Cod. Barras lido: {0}'.format(codbar))
                if (7 <= len(codbar) <= 11) and codbar[4].__eq__('-'):
                    if self.last_codbar == codbar:
                        self.lcd.write_line('Apontado', 0, 1, 1)
                        continue
                    try:
                        op, contcel = codbar.split('-')
                        cont, cel = int(
                            contcel[0:(len(contcel)-1)]), int(contcel[-1])
                        op = int(op)
                    except:
                        self.logger.info('Código invalido lido')
                        self.lcd.write_line('Nao reconhecido', 0, 1, 1)
                        continue
                        
                    if self.numorp == op:
                        result = self.db.insert_entry(self.codemp,
                                                      self.codfil,
                                                      self.codope,
                                                      self.codori,
                                                      self.numorp,
                                                      codbar,
                                                      cont,
                                                      cel)
                        if result == 0:
                            self.lcd.write_line('Ja apontado', 0, 1, 2)
                        if result == 1:
                            self.last_codbar = codbar
                            self.lcd.write_line(
                                'Apontado: {0}'.format(codbar), 0, 1, 1)
                            self.logger.info('Apontado: {0}'.format(codbar))
                            if self.numfrd == self.qtdfrd:
                                self.numfrd = 1
                            else:
                                self.numfrd = self.numfrd + 1
                            self.config_update(
                                'apontamento', 'numfrd', self.numfrd)
                    else:
                        self.logger.warning(
                            'Tentativa de fazer apontamento com OP errada: ' + str(codbar))
                        self.lcd.write_line('OP nao confere', 0, 1, 2)
                elif len(codbar) == 24 and codbar[0:2].__eq__('04'):
                    nova_op = int(codbar[2:11])
                    if self.numorp != 0 and nova_op != self.numorp:
                        self.logger.warning(
                            'Não é possível iniciar nova OP sem finalizar a última')
                        self.lcd.write_line('OP nao fechada', 0, 1, 2)
                    elif self.numorp != 0 and nova_op == self.numorp:
                        self.logger.info('OP fechada: {0}'.format(self.numorp))
                        self.lcd.write_line('OP fechada', 0, 1, 2)
                        self.numorp = 0
                        self.qtdprv = 0
                        self.qtdfrd = 0
                        self.config_update(
                            'apontamento', 'numorp', self.numorp)
                        self.config_update(
                            'apontamento', 'qtdprv', self.qtdprv)
                        self.config_update(
                            'apontamento', 'qtdfrd', self.qtdfrd)
                    else:
                        op, qtdprv, fardo = self.db.get_newop(nova_op)
                        if op:
                            self.numorp = op
                            self.qtdfrd = fardo
                            self.qtdprv = qtdprv
                            self.numfrd = 0
                            self.logger.info('Dados de OP atualizados: OP - {0}, Qtde prev. - {1}, Qtde fardo - {2}'
                                        .format(op, fardo, qtdprv))
                            self.config_update('apontamento', 'numorp', op)
                            self.config_update('apontamento', 'qtdfrd', fardo)
                            self.config_update('apontamento', 'qtdprv', qtdprv)
                            self.config_update(
                                'apontamento', 'numfrd', self.numfrd)
                            self.lcd.write_line('Nova OP: ' + str(op), 0, 1, 2)
                        else:
                            self.lcd.write_line('Erro OP', 0, 1, 2)
                else:
                    self.lcd.write_line('Nao reconhecido', 0, 1, 2)
                self.status()
        except Exception as e:
            self.logger.exception('Erro fatal')

        self.lcd.write_line("Fim", 0, 0, 0)
        self.logger.error("Programa passou do While, verificar")
Example #11
0
# pin config
IO.pinMode(REDPIN, IO.OUTPUT)
IO.pinMode(YELPIN, IO.OUTPUT)
IO.pinMode(GRNPIN, IO.OUTPUT)
IO.pinMode(SRNPIN, IO.OUTPUT)
IO.pinMode(BTNPIN, IO.INPUT)

# audio, maps to existing pwm channel for line out audio jack
IO.pinMode(AUDIOPIN, IO.PWM_OUTPUT)

# Set PWM range to 100 (duty cycle can be 0-100)
wiringpi.softPwmCreate(REDPIN, 0, 100)
wiringpi.softPwmCreate(YELPIN, 0, 100)
wiringpi.softPwmCreate(GRNPIN, 0, 100)

LCD = Lcd(LCD_ROWS, LCD_CHARS, LCD_BITS, PIN_LCD_RS, PIN_LCD_E, PINS_LCD_DB)
SPEECH = Speech()

# Siren state machine functions
def siren_on (fsm):
    """Turn on Siren"""
    IO.digitalWrite(SRNPIN, IO.HIGH)
    time.sleep(1.7)

def siren_off (fsm):
    """Turn off Siren"""
    IO.digitalWrite(SRNPIN, IO.LOW)
    time.sleep(0.5)

# Button state machine functions
def button_up (fsm):
Example #12
0
ap = argparse.ArgumentParser(description='AUV LCD Daemon')
ap.add_argument('--virtual',
                action='store_const',
                const=True,
                help='Enable virtual testing mode (gtk LCD display)')
args = ap.parse_args()

if args.virtual:
    # Use GTK lcd screen window instead of hardware LCD
    from virtual_lcd import VirtualLcd
    screen = VirtualLcd()
else:
    # Connect to the hardware LCD
    from lcd import Lcd
    screen = Lcd()

screen.init()

dispatch = ScreenDispatcher()


def interrupt_handler(signal, frame):
    print "\nExiting"
    dispatch.stop_all()
    surface, cr = screen.new_surface()
    exitscreen = ExitScreen()
    exitscreen.draw(cr)
    screen.write_surface(surface)
    sys.exit(0)
Example #13
0
File: car.py Project: berickson/car
class Car:
  def __init__(self, online = True):
    self.config_path = 'car.ini'
    self.read_configuration()
    self.online = online
    self.reset_odometry()
    self.listener = None
    self.last_verified_velocity = 0.0
    self.lcd = None
    self.usb_error_count = 0
    self.input_recording_file = None
    self.commands_recording_file = None
    
    if self.online:
      from lcd import Lcd
    
      self.lcd = Lcd()
      self.quit = False
      self.write_command('td+') # first command normally fails, so write a blank command
      self.write_command('td+')
      self.output_thread = threading.Thread(target=self._monitor_output, args = ())
      self.output_thread.daemon = True
      self.output_thread.start()
      while self.dynamics.reading_count == 0:
        time.sleep(0.01) 

  def display_text(self, s):
    if self.lcd is not None:
      self.lcd.display_text(s)
  
  # records all input from the pi
  def begin_recording_input(self, recording_file_path):
    if self.input_recording_file is not None:
      self.end_recording_input()
    self.input_recording_file = open(recording_file_path,'w')
  
  def end_recording_input(self):
    if self.input_recording_file is not None:
      self.input_recording_file.close()
      self.input_recording_file = None
    
  # records all commands to the pi
  def begin_recording_commands(self, commands_recording_file_path):
    if self.commands_recording_file is not None:
      self.end_recording_commands()
    self.commands_recording_file = open(commands_recording_file_path,'w')
  
  def end_recording_commands(self):
    if self.commands_recording_file is not None:
      self.commands_recording_file.close()
      self.commands_recording_file = None
    
    

  def reset_odometry(self):
    self.reading_count = 0
    self.dynamics = Dynamics()
    self.velocity = 0.0
    self.last_velocity = 0.0
    self.heading_adjustment = 0.
    self.odometer_start = 0
    self.odometer_front_left_start = 0
    self.odometer_front_right_start = 0
    self.odometer_back_left_start = 0
    self.odometer_back_right_start = 0
    self.ackerman = Ackerman(
      front_wheelbase_width = self.front_wheelbase_width_in_meters, 
      wheelbase_length = self.wheelbase_length_in_meters)

  def read_configuration(self):
  
    # odometry
    self.meters_per_odometer_tick = float(self.get_option('calibration','meters_per_odometer_tick'))
    self.gyro_adjustment_factor = float(self.get_option('calibration','gyro_adjustment_factor'))
    
    # esc and steering
    self.center_steering_us = int(self.get_option('calibration','center_steering_us'))
    self.min_forward_esc = int(self.get_option('calibration','min_forward_esc'))
    self.min_reverse_esc = int(self.get_option('calibration','min_reverse_esc'))
    self.reverse_center_steering_us = int(self.get_option('calibration','reverse_center_steering_us'))
    
    # car dimensions
    self.front_wheelbase_width_in_meters = float(self.get_option('calibration','front_wheelbase_width_in_meters'))
    self.rear_wheelbase_width_in_meters = float(self.get_option('calibration','rear_wheelbase_width_in_meters'))
    self.wheelbase_length_in_meters = float(self.get_option('calibration','wheelbase_length_in_meters'))
    
    # infer general dimensions
    # todo: put these in config to get complete shape of car
    self.length = self.wheelbase_length_in_meters
    self.width = self.front_wheelbase_width_in_meters

  def add_listener(self, listener):
    if self.listener is not None:
      raise Exception("only one listener allowed")
      
    self.listener = listener    

  def remove_listener(self, listener):
    if self.listener is not listener:
     raise Exception("Unknown listener")
     
    self.listener = None

  def __exit__(self, type_unused, value_unused, traceback_unused):
    self.quit = True
    if self.online:
      self.output_thread.join()

  def get_option(self,section,option):
    config = ConfigParser.ConfigParser()
    with open(self.config_path, 'rwb+') as configfile:
      config.readfp(configfile)
    return config.get(section, option)
        
  def set_option(self,section,option,value):
    config = ConfigParser.ConfigParser()
    with open(self.config_path, 'rwb+') as configfile:
        config.readfp(configfile)
        
    config.set(section,option,value)

    with open(self.config_path, 'rwb+') as configfile:
        config.write(configfile)
        
   
  def write_command(self, s):
    if not self.online:
      raise Exception("must be online")
    
    l = "{0}\n".format(s)
    with open('/dev/car','w') as command:
      command.write(l)
    if self.commands_recording_file is not None:
      self.commands_recording_file.write(l)
    
  def _monitor_output(self):
    self.output = open('/var/log/car','r')
    self.output.seek(0,2) # go to end of file
    line_start = None
    while not self.quit:
      s = self.output.readline()
      if s:
        if line_start is not None:
          s = line_start + s
          line_start = None
        if not s.endswith('\n'):
          line_start = s
          continue
          
        self.process_line_from_log(s)              
      else:
        time.sleep(0.001)

  def process_line_from_log(self, s):
    # sanity check.  Only process valid TRACE_DYNAMICS log lines
    fields = s.split(',')
    if fields == None:
      return
    if len(fields) < 10:
      return
    if fields[1] != 'TD':
      return
    if len(fields) != 39:
      self.usb_error_count = self.usb_error_count + 1
      #print 'invalid TD packet with {} fields: {}'.format(len(fields),s)
      return
    
    if self.input_recording_file is not None:
      self.input_recording_file.write(s)
      
    # todo, handle contention with different threads
    # for now, make changeover quick and don't mess
    # with existing structures, maybe by keeping a big list
    current = Dynamics()
    try:
      current.set_from_log(fields)
    except:
      return
    previous = self.dynamics
    self.dynamics = current
    self.reading_count += 1
    if self.reading_count > 1:
      self.apply_dynamics(current, previous)
    else:
      self.original_dynamics = current
      
    if self.listener != None:
      self.listener.put(current)
  
  def get_usb_error_count(self):
    return self.usb_error_count
    
  # returns ping distance in meters
  def ping_inches(self):
    return self.ping_meters()/0.0254

  def ping_distance(self):
    return self.ping_meters()

  def ping_meters(self):
    return self.dynamics.ping_millimeters / 1000.
  
  
  def battery_voltage(self):
    return self.dynamics.battery_voltage
  
  def apply_dynamics(self, current, previous):
    # correct heading with adjustment factor
    self.heading_adjustment += (1. - self.gyro_adjustment_factor) * standardized_degrees(current.heading - previous.heading)
   
    # if wheels have moved, update ackerman
    wheel_distance_meters = (current.odometer_ticks-previous.odometer_ticks)  * self.meters_per_odometer_tick
    if abs(wheel_distance_meters) > 0.:
      outside_wheel_angle = radians(self.angle_for_steering(previous.str))
      self.ackerman.move_left_wheel(outside_wheel_angle, wheel_distance_meters, self.heading_radians())
      
    # update velocity
    if current.odometer_last_us != previous.odometer_last_us:
      elapsed_seconds = (current.odometer_last_us - previous.odometer_last_us) / 1000000.
      self.velocity = wheel_distance_meters / elapsed_seconds
      self.last_verified_velocity = self.velocity
    else:
      # no tick this time, how long has it been?
      seconds_since_tick = ( current.us - current.odometer_last_us ) / 1000000.
      if seconds_since_tick > 0.1:
        # it's been a long time, let's call velocity zero
        self.velocity = 0.0
      else:
        # we've had a tick recently, fastest possible speed is when a tick is about to happen
        # let's use smaller of that and previously certain velocity
        max_possible = self.meters_per_odometer_tick / seconds_since_tick
        if max_possible > abs(self.last_verified_velocity):
          self.velocity = self.last_verified_velocity
        else:
          if self.last_verified_velocity > 0:
            self.velocity = max_possible
          else:
            self.velocity = -max_possible

    #print("x:{:.2f} y:{:.2f} heading:{:.2f}".format(self.ackerman.x, self.ackerman.y, relative_heading))
  
  # returns the velocity in meters/sec
  # if the car is reversing, velocity will be negative
  def get_velocity_meters_per_second(self):
    return self.velocity;
  
  # returns position of rear of car (between two rear wheels), this starts at -wheelbase_length_in_meters,0
  def rear_position(self):
    return (self.ackerman.x - self.wheelbase_length_in_meters, self.ackerman.y)
  
  # returns position of front of car (between two front wheels), this starts at 0,0
  def front_position(self):
    h = radians(self.heading_degrees());
    l = self.wheelbase_length_in_meters
    return (self.ackerman.x + l * cos(h) - l , self.ackerman.y + l * sin(h))
    
  def heading_degrees(self):
    return standardized_degrees(self.dynamics.heading - self.original_dynamics.heading + self.heading_adjustment)
    
  def heading_radians(self):  
    return radians(self.heading_degrees())
    
  
  def set_rc_mode(self):
    self.write_command('rc')

  def set_manual_mode(self):
    self.write_command('m')
  
  def wheels_angle(self):
    return self.angle_for_steering(self.dynamics.str) 
    
  
  def esc_for_velocity(self, v):
    data = [
      (-2., 1200), # made up numbers for negative v: todo: find empirically
      (-1., 1250),
      (0.0,  1500),
      (0.1, 1645),
      (0.34, 1659),
      (0.85, 1679),
      (1.2, 1699),
      (1.71, 1719),
      (1.88, 1739),
      (2.22, 1759),
      (2.6, 1779),
      (3.0, 1799),
      (14.0, 2000)
      ]
    return table_lookup(data, v)
      
  def angle_for_steering(self, str):
    data = [
      (30,1000),
      (25,1104),
      (20,1189),
      (15,1235),
      (10,1268),
      (5, 1390),
      (0, 1450),
      (-5, 1528),
      (-10, 1607),
      (-15,1688),
      (-20, 1723),
      (-25, 1768),
      (-30, 1858)]
    last = len(data)-1
    if str <= data[0][1]:
      return data[0][0]
    if str >= data[last][1]:
      return data[last][0]
    for i in range(0,last):
      if str <= data[i+1][1]:
        return interpolate(
          str, data[i][1], data[i][0], data[i+1][1], data[i+1][0])
  
  # returns the steering pulse for give steering angle
  # of the outside wheel
  def steering_for_angle(self, theta):
    data = [
      (30,1000),
      (25,1104),
      (20,1189),
      (15,1235),
      (10,1268),
      (5, 1390),
      (0, 1450),
      (-5, 1528),
      (-10, 1607),
      (-15,1688),
      (-20, 1723),
      (-25, 1768),
      (-30, 1858)]
    last = len(data)-1
    if theta >= data[0][0]:
      return data[0][1]
    if theta <= data[last][0]:
      return data[last][1]
    for i in range(0,last):
      if theta >= data[i+1][0]:
        return interpolate(
          theta, data[i][0], data[i][1], data[i+1][0], data[i+1][1])
     
    
  def set_esc_and_str(self, speed, steering):
     self.write_command('pse {0},{1}'.format(int(steering), int(speed)))
  
  def zero_odometer(self):
    self.odometer_start = self.dynamics.odometer_ticks
    self.odometer_front_left_start = self.dynamics.odometer_front_left
    self.odometer_front_right_start = self.dynamics.odometer_front_right
    self.odometer_back_left_start = self.dynamics.odometer_back_left
    self.odometer_back_right_start = self.dynamics.odometer_back_right
    

  def odometer_meters(self):
    return (self.dynamics.odometer_ticks - self.odometer_start) * self.meters_per_odometer_tick
  
  def odometer_front_left(self):
    return self.dynamics.odometer_front_left - self.odometer_front_left_start
  def odometer_front_right(self):
    return self.dynamics.odometer_front_right - self.odometer_front_right_start
  def odometer_back_left(self):
    return self.dynamics.odometer_back_left - self.odometer_back_left_start
  def odometer_back_right(self):
    return self.dynamics.odometer_back_right - self.odometer_back_right_start
 
  # returns where you should steer to if you wish to go to goal_heading
  def steering_for_goal_heading_degrees(self, goal_heading, reverse = False):
    direction = -1 if reverse else 1
    heading_error = degrees_diff(goal_heading, self.heading_degrees())
    steering = self.steering_for_angle(-direction * heading_error)
    return steering
  
  def is_drifting(self):
    return self.ackerman.is_drifting()

  def forward(self, meters, goal_heading = None, fixed_steering_us = None, max_speed = 2.0):
    ticks = int(meters/self.meters_per_odometer_tick)
    if fixed_steering_us != None:
      steering = fixed_steering_us
    
    if goal_heading == None:
      goal_heading = self.dynamics.heading
    
    #use a direction of 1 / -1 to help with the math for forward / reverse
    if ticks > 0:
      direction = 1
      min_esc = 1500
      max_esc = self.esc_for_velocity(max_speed)
    else:
      direction = -1
      min_esc = 1500
      max_esc = self.esc_for_velocity(-max_speed) 
    
    goal_odometer = self.dynamics.odometer_ticks + ticks

    self.set_rc_mode()
    while self.dynamics.odometer_ticks * direction < goal_odometer * direction:
      esc = max_esc
    
      # adjust steering if fixed steering wasn't selected
      if fixed_steering_us == None:
        heading_error = degrees_diff(goal_heading, self.dynamics.heading)
        steering = self.steering_for_angle(-direction * heading_error)
   
      # adjust speed
      if abs(self.get_velocity_meters_per_second()) > max_speed:
        esc = min_esc
             
      self.set_esc_and_str(esc, steering)
      time.sleep(.02)
    self.set_esc_and_str(1500,steering)
    slowdown_start = time.time()
    while (time.time()-slowdown_start < 3):
      if fixed_steering_us == None:
        heading_error = degrees_diff(goal_heading, self.dynamics.heading)
        steering = self.steering_for_angle(-direction * heading_error * 1.5)
      time.sleep(0.01)
Example #14
0
# pin config
IO.pinMode(REDPIN, IO.OUTPUT)
IO.pinMode(YELPIN, IO.OUTPUT)
IO.pinMode(GRNPIN, IO.OUTPUT)
IO.pinMode(SRNPIN, IO.OUTPUT)
IO.pinMode(BTNPIN, IO.INPUT)

# audio, maps to existing pwm channel for line out audio jack
IO.pinMode(AUDIOPIN, IO.PWM_OUTPUT)

# Set PWM range to 100 (duty cycle can be 0-100)
wiringpi.softPwmCreate(REDPIN, 0, 100)
wiringpi.softPwmCreate(YELPIN, 0, 100)
wiringpi.softPwmCreate(GRNPIN, 0, 100)

LCD = Lcd(LCD_ROWS, LCD_CHARS, LCD_BITS, PIN_LCD_RS, PIN_LCD_E, PINS_LCD_DB)
SPEECH = Speech()


# Siren state machine functions
def siren_on(fsm):
    """Turn on Siren"""
    IO.digitalWrite(SRNPIN, IO.HIGH)
    time.sleep(1.7)


def siren_off(fsm):
    """Turn off Siren"""
    IO.digitalWrite(SRNPIN, IO.LOW)
    time.sleep(0.5)
Example #15
0
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal, frame):
    global continue_reading
    print "Ctrl+C captured, ending read."
    continue_reading = False
    GPIO.cleanup()
    sys.exit()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# Create an object of the class Lcd
lcd = Lcd()

### KEYPAD ###
keypad = Keypad()

def getCourses():
    lcd.lcd_clear()
    r = requests.get(BASE_URL + 'courses')
    courses = r.json()

    lcd.lcd_string("", lcd.LCD_LINE_2)

    for index, course in enumerate(courses):
        if index == 0:
            lcd.lcd_string(course['code'], lcd.LCD_LINE_1)
        elif index == 1:
Example #16
0
class TestFrontend(pykka.ThreadingActor, core.CoreListener):

    def __init__(self, config, core):
        super(TestFrontend, self).__init__()
        self.core = core

        self._now_playing_track = None
        self.lcd = Lcd()
        self.radioMenu = RadioMenu(self.lcd, self)

        logger.info("My plugin has loaded!")

        # set up fallback image
        self.plugin_dir = os.path.dirname(os.path.realpath(__file__))
        self.fallback_image = self.plugin_dir + "/images/on_the_air.jpg"

        self.radioMenu.loading()

    def volume_up(self):
        logger.info("COMMAND: Volume Up")

        current_volume = self.core.mixer.get_volume().get()
        logger.info("Current volume: " + str(current_volume))

        current_volume += 5

        if current_volume > 100:
            current_volume = 100

        self.core.mixer.set_volume(current_volume)
        logger.info("New volume: " + str(current_volume))

    def volume_down(self):
        logger.info("COMMAND: Volume Down")

        current_volume = self.core.mixer.get_volume().get()
        logger.info("Current volume: " + str(current_volume))

        current_volume -= 5

        if current_volume < 0:
            current_volume = 0

        self.core.mixer.set_volume(current_volume)
        logger.info("New volume: " + str(current_volume))

    def toggle_play(self):
        logger.info("COMMAND: Toggling Play State")

        current_state = self.core.playback.get_state().get()

        logger.info("state is: " + current_state)

        if current_state == core.PlaybackState.STOPPED:

            current_state = self.core.playback.get_state().get()
            logger.info("state is: " + current_state)

            logger.info("Playing")

            self.core.playback.play()

        else:
            if current_state == core.PlaybackState.PAUSED:
                self.core.playback.resume()
            else:
                if current_state == core.PlaybackState.PLAYING:
                    self.core.playback.pause()

        logger.info("new state is: " + self.core.playback.get_state().get())

    def playlists_loaded(self):
        logger.info("Playlists Loaded - navigating to default screen")
        self.radioMenu.close()

    def menu_load_playlists(self, uri=None):
        '''Returns the list of playlists'''

        if uri:
            logger.info("Loading menu level: " + uri)
        else:
            logger.info("Loading root menu level")

        root_level = self.core.library.browse(uri).get()

        print root_level

        items = []

        for entry in root_level:
            if entry.type == "directory":
                items.append(DynamicMenuItem(entry.name, self.menu_load_playlists, entry.uri))
            elif entry.type == "track":
                items.append(Command(entry.name, self.load_track_and_play, entry.uri))
            elif entry.type == "playlist":
                items.append(Command(entry.name, self.load_playlist_and_play, entry.uri))

        return items


    def load_playlist(self, uri):
        """
        Loads the items of the play list to the track list
        """
        logger.info("Playing playlist")
        logger.info("Loading playlist: " + uri)

        pl = self.core.playlists.lookup(uri).get()
        logger.info(pl)

        self.core.tracklist.clear()
        self.core.tracklist.add(pl.tracks)

        self.core.tracklist.set_random(True)

    def load_playlist_and_play(self, uri):

        # close out of the menu
        self.radioMenu.close()

        self.lcd.message("Loading playlist...")

        self.load_playlist(uri)
        self.core.playback.play()

    def load_track_and_play(self, uri):

        logger.info("Playing track")
        logger.info(uri)

        # close out of the menu
        self.radioMenu.close()

        self.lcd.message("Playing...")

        self.core.tracklist.clear()
        self.core.tracklist.add(uris=[uri])

        self.core.playback.play()


    def load_default_playlist_and_play(self):

        if self.core.tracklist.get_length().get() == 0:
            self.load_playlist("spotify:user:1230911936:playlist:04OMIJJH2YSLkeVl5jhXjl")

        self.toggle_play()

    def show_now_playing(self, track):

        # store for later
        self._now_playing_track = track

        logger.info(track)

        name = track.name
        artists = ', '.join([a.name for a in track.artists])

        track_image_uri = self.fallback_image

        if len(track.album.images) > 0:
            logger.info("Has an image...")

            track_image_uri = iter(track.album.images).next()
            logger.info("Image: %s",  track_image_uri)

        else:
            logger.info("Checking for image...")
            image_result = self.core.library.get_images({track.uri}).get()

            logger.info(image_result[track.uri])

            for image in image_result[track.uri]:
                if image.width >= 640:
                    logger.info("Found image: " + image.uri)
                    track_image_uri = image.uri

        logger.info("Playback started: %s - %s",  name, artists)
        logger.info("Name: %s", name)
        logger.info("Artists: %s",  artists)
        logger.info("Image: %s",  track_image_uri or "None")

        track_image_path = self.fallback_image
        if track_image_uri is not None:
            try:
                logger.info("Downloading image..." + track_image_uri)

                import tempfile
                temp_dir = tempfile.gettempdir()

                import urllib
                testfile = urllib.URLopener()

                track_image_path = temp_dir + "/art.jpg"
                logger.info("Saving to " + track_image_path)
                testfile.retrieve(track_image_uri, track_image_path)

                logger.info(image)

            except Exception as ex:
                logger.error("Error downloading image ...")
                logger.error(ex)
                track_image_path = self.fallback_image

        logger.info("Updating LCD")
        self.lcd.now_playing(track_image_path, name.encode("utf8","ignore") or "", artists.encode("utf8","ignore") or "")


    def track_playback_started(self, tl_track):
        logger.info("STARTED")
        self.show_now_playing(tl_track.track)
        #self.lcd.message("Playing")

    def track_playback_paused(self, tl_track, time_position):
        logger.info("PAUSED")
        self.lcd.message("Paused")

    def track_playback_resumed(self, tl_track, time_position):
        logger.info("RESUMED")
        self.show_now_playing(tl_track.track)
        #self.lcd.message("Playing")

    def track_playback_ended(self, tl_track, time_position):
        logger.info("ENDED")
        # self.lcd.message("Stopped (Finished)")

    def volume_changed(self, volume):
        #self.lcd.message("Volume: " + str(volume))
        pass

    def stream_title_changed(self, title):
        pass
    time()
    jmp = Button(21)
    btn_power = Button(26, hold_time=2)
    btn_channel = Button(13, hold_time=2)
    btn_start = Button(6)

    channel = 11
    power = 8
    current_mode = ''

    input_queue = queue.Queue()
    output_queue = queue.Queue()

    sp = SerialProcess()
    lcd = Lcd()
    buzzer = Buzzer()

    buzzer.start()

    if is_tx():
        print("Tx Mode")
    else:
        print("Rx mode")

    while True:
        while not sp.is_open():
            sp = SerialProcess()
            print('port is open')

        try:
Example #18
0
import _thread
import time
import json
from pyb import Timer
import os

from adc import Adc
from lcd import Lcd
from scan import Scan
from outctl import Outctl
from networks import Network

adc = Adc()
lcd = Lcd()
scan = Scan()
outctl = Outctl()
network = Network()

up_state_cnt = 0  #上位机状态计数器
file_flag = 0  #是否写入文件
adc_freq = 1000  #adc采样频率
voltage_b = 0
current_b = 0
warnvalue = 10
warntime = 20
stopvalue = 20
stoptime = 20
time_now = ''


def up_state(tt):
Example #19
0
class Game:
    LEDS = None

    SWITCHES = None

    COUNTDOWN = None

    GAME_TIME = None

    FINISH_TIME = 0

    RAND = -1
    RANDS = []

    BUTTONS_STATE = False
    BUTTONS_PRESSED = []

    GAMEOVER = False

    BUTTON_ACTION_ALL = 'all'
    BUTTON_ACTION_SNAKE = 'snake'

    LEVEL = 1

    SCORE_INCREMENT = None

    gpio = None
    lcd = None
    db = None

    def __init__(self, leds, switches, countdown, game_time, score_increment):
        self.LEDS = leds
        self.SWITCHES = switches
        self.COUNTDOWN = countdown
        self.GAME_TIME = game_time
        self.SCORE_INCREMENT = score_increment

        self.gpio = Gpio
        self.lcd = Lcd()
        self.db = TinyDB('data/database.json')

        if len(self.LEDS) != len(self.SWITCHES):
            print(
                "[Game][error] There isn't the same number of LEDS as SWITCHES"
            )
            exit()

        try:
            self.gpio.setmode(self.gpio.BCM)

            for switch in self.SWITCHES:
                self.gpio.setup(switch, self.gpio.IN)
                self.gpio.add_event_detect(switch,
                                           self.gpio.RISING,
                                           bouncetime=300)
                self.gpio.add_event_callback(switch, self.__button_press)

            for led in self.LEDS:
                self.gpio.setup(led, self.gpio.OUT)
                self.gpio.output(led, False)
        except AttributeError:
            print("[Game][error] An error occurred initialising game")

    def start(self, run_once=False):
        print("[Game][info] Starting game")

        self.lcd.print("Press lit button", self.lcd.LINE_1)
        self.lcd.print("to start", self.lcd.LINE_2)

        try:
            self.gpio.output(self.LEDS[2], True)

            while self.gpio.input(self.SWITCHES[2]) == self.gpio.LOW:
                time.sleep(0.01)

            for led in self.LEDS:
                self.gpio.output(led, True)
        except AttributeError:
            print("[Game][error] An error occurred starting game")

        self.__countdown()
        self.__loop()
        self.finish()

        if run_once is not True:
            self.start()

    def __countdown(self):
        print("[Game][info] Starting game countdown")

        try:
            self.lcd.clear()

            for i in range(self.COUNTDOWN, -1, -1):
                if i == 0:
                    self.lcd.print("Go Go Go!", self.lcd.LINE_1)
                elif i == self.COUNTDOWN:
                    self.lcd.print("Starting in %d!" % i, self.lcd.LINE_1)
                else:
                    self.lcd.print("%d!" % i, self.lcd.LINE_1)

                time.sleep(1)

                self.gpio.output(self.LEDS[(i - 1)], False)

            self.lcd.clear()
        except AttributeError:
            print("[Game][error] An error occurred starting game countdown")

    def __loop(self):
        print("[Game][info] Starting game loop")

        self.FINISH_TIME = time.time() + (self.GAME_TIME + 1)

        try:
            while time.time() < self.FINISH_TIME and self.GAMEOVER is not True:
                print("[Game][info] Game loop iteration")

                self.BUTTONS_STATE = False
                self.BUTTONS_PRESSED = []

                for i in range(self.LEVEL):
                    self.print_information("Repeat following")

                    if len(self.RANDS) >= (i + 1):
                        self.RAND = self.SWITCHES.index(self.RANDS[i])
                    else:
                        self.RAND = random.randint(0, (len(self.LEDS) - 1))
                        self.RANDS.append(self.SWITCHES[self.RAND])

                    print("[Game][info] Activating button: %s" %
                          (self.SWITCHES[self.RAND]))

                    self.gpio.output(self.LEDS[self.RAND], True)
                    time.sleep(0.5)
                    self.gpio.output(self.LEDS[self.RAND], False)

                start = time.time()

                print("[Game][info] Waiting for button press")

                while len(self.BUTTONS_PRESSED) < self.LEVEL:
                    self.print_information()

                    if time.time() >= self.FINISH_TIME:
                        break

                end = time.time()
                time_taken = end - start

                time.sleep(0.5)

                print("[Game][info] Button presses time taken: %f" %
                      time_taken)

                if time.time() < self.FINISH_TIME:
                    if self.BUTTONS_STATE is True:
                        print("[Game][info] Level increased by %d" % 1)

                        self.LEVEL += 1
                    else:
                        self.GAMEOVER = True
        except AttributeError:
            print("[Game][error] An error occurred during game loop")

    def __button_press(self, channel):
        print("[Game][info] Button pressed: %d" % channel)

        if len(self.RANDS) == 0:
            return

        self.BUTTONS_PRESSED.append(channel)

        if len(self.BUTTONS_PRESSED) <= len(
                self.RANDS) and channel == self.RANDS[(
                    len(self.BUTTONS_PRESSED) - 1)]:
            self.BUTTONS_STATE = True
        else:
            self.BUTTONS_STATE = False

    def get_score(self):
        print("[Game][info] Calculating score")

        level = self.LEVEL - 1

        if level < 1:
            return 0

        return (level * (level + 1) / level) * self.SCORE_INCREMENT

    def print_information(self, message=None):
        print("[Game][info] Printing information")

        score = self.get_score()
        remaining = int(self.FINISH_TIME - time.time())

        try:
            self.lcd.print("Remaining: %ds" % remaining, self.lcd.LINE_1)

            if message is None:
                self.lcd.print("Score: %d" % score, self.lcd.LINE_2)
            else:
                self.lcd.print(message, self.lcd.LINE_2)
        except AttributeError:
            print("[Game][error] An error occurred printing information")

    def print_score(self, high_score=False):
        print("[Game][info] Printing score")

        score = self.get_score()

        try:
            if high_score:
                self.lcd.print("High score: %d!" % self.get_score(),
                               self.lcd.LINE_1)
                self.flash_buttons(self.BUTTON_ACTION_ALL)
                time.sleep(3)
            else:
                self.lcd.print("Your score: %d" % score, self.lcd.LINE_1)
                time.sleep(3)
        except AttributeError:
            print("[Game][error] An error occurred printing score")

    def flash_buttons(self, action):
        print("[Game][info] Flashing buttons '%s'" % action)

        try:
            if action == self.BUTTON_ACTION_SNAKE:
                for x in range(0, 4):
                    for y in range(0, len(self.LEDS)):
                        self.gpio.output(self.LEDS[y], True)
                        time.sleep(0.2)
                        self.gpio.output(self.LEDS[y], False)
            elif action == self.BUTTON_ACTION_ALL:
                for x in range(0, 4):
                    for y in range(0, len(self.LEDS)):
                        self.gpio.output(self.LEDS[y], True)

                    time.sleep(0.2)

                    for y in range(0, len(self.LEDS)):
                        self.gpio.output(self.LEDS[y], False)

                    time.sleep(0.2)
        except AttributeError:
            print("[Game][error] An error occurred flashing buttons")

    def finish(self):
        print("[Game][info] Finishing game")

        score = self.get_score()

        self.lcd.clear()

        if self.db.contains(Query().score >= score):
            self.print_score()
        else:
            self.print_score(True)

        self.db.insert({'score': score})
        self.reset()

    def reset(self):
        print("[Game][info] Resetting game")

        self.GAMEOVER = False
        self.RAND = -1
        self.RANDS = []
        self.LEVEL = 1
        self.FINISH_TIME = 0
        self.BUTTONS_STATE = False
        self.BUTTONS_PRESSED = []
        self.flash_buttons(self.BUTTON_ACTION_SNAKE)
        self.lcd.clear()

    def cleanup(self):
        print("[Lcd][info] Game clean up")

        try:
            self.gpio.cleanup()
            self.lcd.cleanup()
        except AttributeError:
            print("[Game][error] An error occurred cleaning up")

    def __exit__(self):
        print("[Game][info] Game exit")

        self.cleanup()
Example #20
0
def write_to_lcd_and_lock_failure(lcd, message, led_buzzer):
    led_buzzer.trigger_failure()
    write_to_lcd_and_lock(lcd, message)

def display_date_time(lcd, lcd_lock):
    while True:
        lcd_lock.wait_empty()
        write_to_lcd(lcd, get_current_date_time().strftime("%Y-%m-%d %H:%M:%S").split(' '))
        sys_time.sleep(0.5)

if __name__ == "__main__":
    logging.info("nfc main func started")

    nfc_reader_output_queue = queue.Queue()
    keypad = Keypad()
    lcd = Lcd(LCD_RS_PIN, LCD_E_PIN, LCD_DATA_PINS)
    led_buzzer = LedBuzzer(GREEN_LED_AND_BUZZER_PIN, RED_LED_PIN)
    system_state = SystemState()
    lcd_lock = LcdLock()

    threads = []
    threads.append(threading.Thread(target=start_nfc_poll_producer, \
        args=(nfc_reader_output_queue,)))
    threads.append(threading.Thread(target=start_nfc_poll_consumer, \
        args=(nfc_reader_output_queue,keypad,lcd,led_buzzer,system_state,lcd_lock)))
    threads.append(threading.Thread(target=display_date_time, args=(lcd, lcd_lock)))
    
    for func in [lambda t: t.start(), lambda t: t.join()]:
        for thread in threads:
            func(thread)
Example #21
0
# pin config
IO.pinMode(REDPIN, IO.OUTPUT)
IO.pinMode(YELPIN, IO.OUTPUT)
IO.pinMode(GRNPIN, IO.OUTPUT)
IO.pinMode(SRNPIN, IO.OUTPUT)
IO.pinMode(BTNPIN, IO.INPUT)

# audio, maps to existing pwm channel for line out audio jack
IO.pinMode(AUDIOPIN, IO.PWM_OUTPUT)

# Set PWM range to 100 (duty cycle can be 0-100)
wiringpi.softPwmCreate(REDPIN, 0, 100)
wiringpi.softPwmCreate(YELPIN, 0, 100)
wiringpi.softPwmCreate(GRNPIN, 0, 100)

LCD = Lcd(LCD_ROWS, LCD_CHARS, LCD_BITS, PIN_LCD_RS, PIN_LCD_E, PINS_LCD_DB)

# Siren state machine functions
def siren_on (fsm):
    """Turn on Siren"""
    IO.digitalWrite(SRNPIN, IO.HIGH)
    time.sleep(1.7)

def siren_off (fsm):
    """Turn off Siren"""
    IO.digitalWrite(SRNPIN, IO.LOW)
    time.sleep(0.5)

# Button state machine functions
def button_up (fsm):
    """Button is not pressed/ up"""