Пример #1
0
 def connectBot(self):
     self.ble = BLE()
     if botName != "":
         self.myBot = self.ble.findNearest()
     else:
         self.myBot = self.ble.findByName(botName)
     self.joypadClient = SimpleJoypadClient(self.myBot)
Пример #2
0
    def bleInit(self):
        if sys.platform == 'darwin':
            return

        self.bleManager = BLE_Manager("hci0")
        self.ble = BLE(bleManager=self.bleManager)

        self.bleManager.startScanning()
        gattOpts = "-j " + sys.argv[2]
        self.ble1 = self.ble.findByAddress(sys.argv[1], gattOpts)

        self.bleManager.stopScanning()
Пример #3
0
class Joypad:
    """ Joypad """
    def __init__(self):
        """ init """
        self.x = 120
        self.y = 120
        self.z = 240 - 64
        self.b = 0
        self.lastUpdateTime = time.time()
        self.running = True
        self.display = Display()
        self.screen = self.display.screen

        self.loadImages()
        self.connectBot()
        self.clock = pygame.time.Clock()

    def loadImages(self):
        self.logo = pygame.image.load(
            basedir + "/images/cannybots_logo_small.png").convert_alpha()
        self.joystick = pygame.image.load(
            basedir + "/images/joystick.png").convert_alpha()
        self.knob = pygame.image.load(basedir +
                                      "/images/knob.png").convert_alpha()
        self.button = pygame.image.load(basedir +
                                        "/images/button.png").convert_alpha()

    def connectBot(self):
        self.ble = BLE()
        if botName != "":
            self.myBot = self.ble.findNearest()
        else:
            self.myBot = self.ble.findByName(botName)
        self.joypadClient = SimpleJoypadClient(self.myBot)

    def updateJoypad(self, (newX, newY), force):
        if (newX > 320 - 64) and newY < 240 - 32 and newY > 32:
            self.z = newY - 32

        if newX < 240:
            self.x = newX
            self.y = newY

        if force:
            self.z = 240 - 64

        if force or (time.time() - self.lastUpdateTime) > 0.05:
            x = arduino_map(self.x - 120, -120, 120, -255, 255)
            y = arduino_map(self.y - 120, -120, 120, -255, 255)
            z = arduino_map(240 - 64 - self.z, 0, 240 - 32, 0, -255)
            self.joypadClient.updateJoypadWithZ(x, y, z * zMultiplier, self.b)
            self.lastUpdateTime = time.time()
Пример #4
0
class Joypad:
    """ Joypad """
    
    def __init__ (self):
        """ init """
        self.x  = 120
        self.y  = 120
        self.z  = 240-64
        self.b  = 0
        self.lastUpdateTime = time.time()
        self.running = True  
        self.display = Display()
        self.screen  = self.display.screen
        
        self.loadImages()
        self.connectBot()
        self.clock = pygame.time.Clock()
    
    
    def loadImages(self):
        self.logo        = pygame.image.load(basedir+"/images/cannybots_logo_small.png").convert_alpha()
        self.joystick    = pygame.image.load(basedir+"/images/joystick.png").convert_alpha()
        self.knob        = pygame.image.load(basedir+"/images/knob.png").convert_alpha()
        self.button      = pygame.image.load(basedir+"/images/button.png").convert_alpha()
    
    
    def connectBot(self):
        self.ble   = BLE() 
        if botName != "":
            self.myBot = self.ble.findNearest()   
        else:
            self.myBot = self.ble.findByName(botName)   
        self.joypadClient = SimpleJoypadClient(self.myBot)

    def updateJoypad(self, (newX,newY), force):   
        if (newX>320-64) and newY<240-32 and newY>32:
            self.z=newY-32 
   
        if newX<240:
            self.x = newX
            self.y = newY 			
            
        if force:
			self.z=240-64;
	

        if force or (time.time() - self.lastUpdateTime) > 0.05:
			x = arduino_map(self.x-120, -120, 120, -255,255)
			y = arduino_map(self.y-120, -120, 120, -255,255)    
			z = arduino_map(240-64-self.z, 0, 240-32, 0, -255)    
			self.joypadClient.updateJoypadWithZ(x, y, z*zMultiplier,self.b) 
			self.lastUpdateTime = time.time()
Пример #5
0
 def connectBot(self):
     self.ble   = BLE() 
     if botName != "":
         self.myBot = self.ble.findNearest()   
     else:
         self.myBot = self.ble.findByName(botName)   
     self.joypadClient = SimpleJoypadClient(self.myBot)
Пример #6
0
    def bleInit(self):
        if sys.platform == 'darwin':
            return

        self.bleManager = BLE_Manager("hci0")
        self.ble = BLE(bleManager=self.bleManager)

        self.bleManager.startScanning()

        self.ble1 = self.ble.findByName(sys.argv[1], gattOpts="-j 1")
        self.ble2 = self.ble.findByName(sys.argv[2], gattOpts="-j 2")

        self.bleManager.stopScanning()

        self.ble1.addListener(self.bleRacer1ReceviedData)
        self.ble2.addListener(self.bleRacer2ReceviedData)
Пример #7
0
class Joypad():
    """ RaceController """

    def __init__(self):
        self.bleInit()
        self.running = True


    def run(self):
        while self.running:
			time.sleep(1)


    def bleInit(self):
        if sys.platform == 'darwin':
            return

        self.bleManager =  BLE_Manager("hci0")
        self.ble        =  BLE(bleManager=self.bleManager)

        self.bleManager.startScanning()
        gattOpts="-j "+sys.argv[2]
        self.ble1 = self.ble.findByAddress(sys.argv[1], gattOpts)

        self.bleManager.stopScanning()
Пример #8
0
def main():
    xAxis = 0
    yAxis = 0
    lastUpdateTime = time.time()
    joysticks = []
    clock = pygame.time.Clock()
    keepPlaying = True
    ble = BLE()
    myBot = ble.findNearest()
    joypadClient = SimpleJoypadClient(myBot)

    # for al the connected joysticks
    for i in range(0, pygame.joystick.get_count()):
        # create an Joystick object in our list
        joysticks.append(pygame.joystick.Joystick(i))
        # initialize them all (-1 means loop forever)
        joysticks[-1].init()
        # print a statement telling what the name of the controller is
        print "Detected joystick '", joysticks[-1].get_name(), "'"
    while keepPlaying:
        if (time.time() - lastUpdateTime) > 0.05:
            joypadClient.updateJoypadWithZ(int(xAxis * 255), int(yAxis * 255),
                                           0, 0)
            lastUpdateTime = time.time()
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print "Received event 'Quit', exiting."
                keepPlaying = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                print "Escape key pressed, exiting."
                keepPlaying = False
            elif event.type == pygame.JOYAXISMOTION:
                #print "Joystick '",joysticks[event.joy].get_name(),"' axis",event.axis,"motion."
                if event.axis == 0:
                    xAxis = joysticks[-1].get_axis(0)
                if event.axis == 1:
                    yAxis = joysticks[-1].get_axis(1)
            elif event.type == pygame.JOYBUTTONDOWN:
                print "Joystick '", joysticks[
                    event.joy].get_name(), "' button", event.button, "down."
            elif event.type == pygame.JOYBUTTONUP:
                print "Joystick '", joysticks[
                    event.joy].get_name(), "' button", event.button, "up."
            elif event.type == pygame.JOYHATMOTION:
                print "Joystick '", joysticks[
                    event.joy].get_name(), "' hat", event.hat, " moved."
Пример #9
0
def main(): 
    xAxis=0
    yAxis=0
    lastUpdateTime = time.time()
    joysticks = []
    clock = pygame.time.Clock()
    keepPlaying = True
    ble   = BLE()
    myBot = ble.findNearest()
    joypadClient = SimpleJoypadClient(myBot)
 
    # for al the connected joysticks
    for i in range(0, pygame.joystick.get_count()):
        # create an Joystick object in our list
        joysticks.append(pygame.joystick.Joystick(i))
        # initialize them all (-1 means loop forever)
        joysticks[-1].init()
        # print a statement telling what the name of the controller is
        print "Detected joystick '",joysticks[-1].get_name(),"'"
    while keepPlaying:
        if (time.time() - lastUpdateTime) > 0.05:
                joypadClient.updateJoypadWithZ(int(xAxis*255), int(yAxis*255), 0,0) 
		lastUpdateTime=time.time() 
        clock.tick(60)
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    print "Received event 'Quit', exiting."
                    keepPlaying = False
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    print "Escape key pressed, exiting."
                    keepPlaying = False
                elif event.type == pygame.JOYAXISMOTION:
                    #print "Joystick '",joysticks[event.joy].get_name(),"' axis",event.axis,"motion."
                    if event.axis==0:
                        xAxis=joysticks[-1].get_axis(0)
                    if event.axis==1:
                        yAxis=joysticks[-1].get_axis(1)
                elif event.type == pygame.JOYBUTTONDOWN:
                    print "Joystick '",joysticks[event.joy].get_name(),"' button",event.button,"down."
                elif event.type == pygame.JOYBUTTONUP:
                    print "Joystick '",joysticks[event.joy].get_name(),"' button",event.button,"up."
                elif event.type == pygame.JOYHATMOTION:
                    print "Joystick '",joysticks[event.joy].get_name(),"' hat",event.hat," moved."
Пример #10
0
    def bleInit(self):
        if sys.platform == 'darwin':
            return

        self.bleManager =  BLE_Manager("hci0")
        self.ble        =  BLE(bleManager=self.bleManager)

        self.bleManager.startScanning()
        gattOpts="-j "+sys.argv[2]
        self.ble1 = self.ble.findByAddress(sys.argv[1], gattOpts)

        self.bleManager.stopScanning()
Пример #11
0
    def bleInit(self):
        if sys.platform == 'darwin':
            return

        self.bleManager =  BLE_Manager("hci0")
        self.ble        =  BLE(bleManager=self.bleManager)

        self.bleManager.startScanning()

        self.ble1 = self.ble.findByName(sys.argv[1], gattOpts="-j 1")
        self.ble2 = self.ble.findByName(sys.argv[2], gattOpts="-j 2")

        self.bleManager.stopScanning()

        self.ble1.addListener(self.bleRacer1ReceviedData)
        self.ble2.addListener(self.bleRacer2ReceviedData)
Пример #12
0
class Joypad():
    """ RaceController """
    def __init__(self):
        self.bleInit()
        self.running = True

    def run(self):
        while self.running:
            time.sleep(1)

    def bleInit(self):
        if sys.platform == 'darwin':
            return

        self.bleManager = BLE_Manager("hci0")
        self.ble = BLE(bleManager=self.bleManager)

        self.bleManager.startScanning()
        gattOpts = "-j " + sys.argv[2]
        self.ble1 = self.ble.findByAddress(sys.argv[1], gattOpts)

        self.bleManager.stopScanning()
Пример #13
0
#!/usr/bin/python

import sys

sys.path.insert(0, "../../modules")

import time
from cannybots.radio import BLE


def myRecvFunc(bleuart, message):
    print message


def myOnDisconnectFunc(ble, message):
    print message


ble = BLE()

myBot = ble.findByName('Lotus')
myBot.addListener(myRecvFunc)
myBot.onDisconnect(myOnDisconnectFunc)

while True:
    time.sleep(3)
    #msg = format(1, '02X') + format(2, '02X') + format(3, '02X') + format(4, '02X')
    #print "sending: " + msg
    #myBot.sendHexString(msg)

Пример #14
0
#!/usr/bin/python

from time import sleep
from cannybots.radio import BLE
from cannybots.clients.joypad import SimpleJoypadClient

ble = BLE()
myBot = ble.findNearest()
joypadClient = SimpleJoypadClient(myBot)

joypadClient.updateJoypad(255, 255, 0)
sleep(1)

joypadClient.updateJoypad(-255, -255, 0)
sleep(1)

joypadClient.updateJoypad(0, 0, 0)
sleep(2)
Пример #15
0
class RaceController():
    """ RaceController """

    def __init__(self):
        self.player1Stats = 0
        self.player2Stats = 0
        self.mainScoreBoard = 0

        self.bleInit()
        self.lastUpdateTime = time.time()
        self.running = True
        self.display = Display(windowed=1, windowWidth=1280, windowHeight=800)
        self.screen = self.display.screen
        self.clock = pygame.time.Clock()

        self.appInit()


    def appInit(self):
        self.app = gui.App()
        c = gui.Container(align=0, valign=0)
        self.table = self.setupTable()
        c.add(self.table, 0, 0)
        self.app.init(c)

    def decreasePlayerSpeed(self, player):
        print "decreasePlayerSpeed:%d" % player

    def increasePlayerSpeed(self, player):
        print "increasePlayerSpeed:%d" % player
        if player == 1:
            self.mainScoreBoard.newTime("One", self.player1Stats.currentLapTime, )
        else:
            self.mainScoreBoard.newTime("Two",self.player2Stats.currentLapTime)

    def resetBoard(self, value):
        self.mainScoreBoard.reset()
        self.player1Stats.reset()
        self.player2Stats.reset()


    def createIcon(self, imageFile, text, callback, value):
        e = Obj()
        e.image = pygame.image.load(imageFile)
        e.rect = pygame.Rect(0, 0, e.image.get_width(), e.image.get_height())
        e.align = 0
        btn = gui.Icon(text, style={'font': roboticaSmallFont, 'image': e.image})
        btn.connect(gui.CLICK, callback, value)
        return btn

    def createImage(self, imageFile):
        e = Obj()
        e.image = pygame.image.load(imageFile)
        e.rect = pygame.Rect(0, 0, e.image.get_width(), e.image.get_height())
        e.align = 0
        e.style = {}
        print repr(e.style)
        return e


    def setupTable(self):

        fg = (0, 0, 0)

        self.player1Stats = PlayerTimes(1)
        self.player2Stats = PlayerTimes(2)
        self.mainScoreBoard = LapTimeScoreBoard()

        p1SlowBtn = self.createIcon(basedir+"/images/button.png", "slower", self.decreasePlayerSpeed, 1)
        p1FastBtn = self.createIcon(basedir+"/images/button.png", "faster", self.increasePlayerSpeed, 1)
        p2SlowBtn = self.createIcon(basedir+"/images/button.png", "slower", self.decreasePlayerSpeed, 2)
        p2FastBtn = self.createIcon(basedir+"/images/button.png", "faster", self.increasePlayerSpeed, 2)
        resetBtn = self.createIcon(basedir+"/images/button.png", "reset", self.resetBoard, 1)


        # Create the Table cells

        table = gui.Table(width=self.screen.get_width(), height=self.screen.get_height())

        table.tr()
        table.td(gui.Label(""))
        table.td(gui.Label(""))
        table.td(gui.Image(basedir + "/images/cannybots_logo.png"), colspan=1, rowspan=1, align=0, valign=0)
        table.td(gui.Label(""))
        table.td(gui.Label(""))

        table.tr()
        table.td(gui.Label("Racer One", color=fg, style={'font': roboticaMediumFont}), colspan=2, rowspan=1, align=1,
                 valign=-1)
        table.td(self.mainScoreBoard, colspan=1, rowspan=2)
        table.td(gui.Label("Racer Two", color=fg, style={'font': roboticaMediumFont}), colspan=2, rowspan=1, align=-1,
                 valign=-1)

        table.tr()
        table.td(self.player1Stats, colspan=2, valign=-1)
        table.td(gui.Label(""))
        table.td(self.player2Stats, colspan=2, valign=-1)

        table.tr()
        table.td(p1SlowBtn, rowspan=1, align=-1)
        table.td(p1FastBtn, rowspan=1, align=1)
        table.td(resetBtn)
        table.td(p2SlowBtn, rowspan=1, align=-1)
        table.td(p2FastBtn, rowspan=1, align=1)

        table.tr()

        return table

    def handleEvents(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = 0
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                self.running = False
            else:
                self.app.event(event)


    def draw(self):
        self.screen.fill((255, 255, 255))

        # self.screen.set_clip(self.mainScoreBoard.get_abs_rect())
        # self.screen.set_clip()

        self.app.paint()
        pygame.display.flip()

    def update(self):
        pass
        #if self.player1Stats.timerStarted:
        #    self.player1Stats.setCurrentLapTime(time.time() - self.player1Stats.startTime)
        #if self.player2Stats.timerStarted:
        #    self.player2Stats.setCurrentLapTime(time.time() - self.player2Stats.startTime)

    def run(self):
        while self.running:
            self.handleEvents()
            self.update()
            self.draw()
            self.clock.tick(30)
        pygame.quit()

    def bleRacer1ReceviedData(self, bleuart, message):
        print "p1: " + str (message)
        if not self.player1Stats:
            return
        if message.startswith("LAP_START"):
            print "Player1 Lap!"
            if self.player1Stats.timerStarted:
                self.player1Stats.setCurrentLapTime(time.time() - self.player1Stats.startTime)
                self.mainScoreBoard.newTime("One", self.player1Stats.currentLapTime)
            self.player1Stats.currentLapTime = 0
            self.player1Stats.timerStarted=True
            self.player1Stats.startTime=time.time()

    def bleRacer2ReceviedData(self, bleuart, message):
        print "p2: " + str (message)
        if not self.player2Stats:
            return
        if message.startswith("LAP_START"):
            print "Player2 Lap Start!"
            if self.player2Stats.timerStarted:
                self.player2Stats.setCurrentLapTime(time.time() - self.player2Stats.startTime)
                self.mainScoreBoard.newTime("Two", self.player2Stats.currentLapTime)
            self.player2Stats.currentLapTime = 0
            self.player2Stats.timerStarted=True
            self.player2Stats.startTime=time.time()

    def bleInit(self):
        if sys.platform == 'darwin':
            return

        self.bleManager =  BLE_Manager("hci0")
        self.ble        =  BLE(bleManager=self.bleManager)

        self.bleManager.startScanning()

        self.ble1 = self.ble.findByName(sys.argv[1])
        self.ble2 = self.ble.findByName(sys.argv[2])

        self.bleManager.stopScanning()

        self.ble1.addListener(self.bleRacer1ReceviedData)
        self.ble2.addListener(self.bleRacer2ReceviedData)
Пример #16
0
#!/usr/bin/python
#
# Cannybots Scratch integration
# By Wayne Keenan 02/12/2014
# www.cannybots.com 

from scratra import *

from time import sleep
from cannybots.radio import BLE
from cannybots.clients.joypad  import SimpleJoypadClient

ble   = BLE() 
myBot = ble.findNearest()   
joypadClient = SimpleJoypadClient(myBot)


motorASpeed = 0
motorBSpeed = 0



@start
def whenstart(scratch):
  print 'Scratch connection started.'

@end
def whenend(scratch):
  print 'Scratch connection ended'

Пример #17
0
class LapTimer():

    def __init__(self):
        self.player1Stats = 0
        self.player2Stats = 0
        self.mainScoreBoard = 0

        self.bleInit()
        self.lastUpdateTime = time.time()
        self.running = True
        #self.display = Display(windowed=1, windowWidth=1776, windowHeight=952)
        self.display = Display(windowed=0, windowWidth=1920, windowHeight=1080)  #HDMIPI: 1920x1080

        #self.display = Display(windowed=1, windowWidth=1280, windowHeight=800)
        self.screen = self.display.screen
        self.clock = pygame.time.Clock()

        self.player1Stats = PlayerTimes(1, width=self.display.screen.get_width()/2)
        self.player2Stats = PlayerTimes(2, width=self.display.screen.get_width()/2)

        self.appInit()


    def appInit(self):
        self.app = gui.App()
        c = gui.Container(align=0, valign=0)
        self.table = self.setupTable()
        c.add(self.table, 0, 0)
        self.app.init(c)

    def decreasePlayerSpeed(self, playerStats, playerBle):
        print "decreasePlayerSpeed:%d" % playerStats.playerNum
        playerStats.currentSpeed = playerStats.currentSpeed - SPEED_DELTA
        playerBle.sendBytes([0x00, 0x00, 0x00, playerStats.currentSpeed])

    def increasePlayerSpeed(self, playerStats, playerBle):
        print "increasePlayerSpeed:%d" % playerStats.playerNum
        playerStats.currentSpeed = playerStats.currentSpeed + SPEED_DELTA
        playerBle.sendBytes([0x00, 0x00, 0x00, playerStats.currentSpeed])

    def resetBoard(self, playerStats):
        playerStats.reset()


    def setupTable(self):

        fg = (0, 0, 0)

        reset1Btn = gui.Button("Reset", style={'font': roboticaSmallFont})
        reset1Btn.connect(gui.CLICK,  self.resetBoard, self.player1Stats)

        reset2Btn = gui.Button("Reset", style={'font': roboticaSmallFont})
        reset2Btn.connect(gui.CLICK,  self.resetBoard, self.player2Stats)

        table = gui.Table(width=self.screen.get_width(), height=self.screen.get_height())

        table.tr()
        table.td(gui.Image(basedir + "/images/cannybots_logo.png"), colspan=2, rowspan=1, align=0, valign=0)
        table.td(gui.Label(""))

        table.tr()
        table.td(gui.Label("Racer One", color=fg, style={'font': roboticaTitleFont}), align=0, valign=0)
        table.td(gui.Label("Racer Two", color=fg, style={'font': roboticaTitleFont}), align=0, valign=0)

        table.tr()
        table.td(self.player1Stats, valign=0)
        table.td(self.player2Stats, valign=0)

        table.tr()
        table.td(reset1Btn)
        table.td(reset2Btn)

        return table

    def handleEvents(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = 0
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.running = False
                elif event.key == pygame.K_z:
                    self.decreasePlayerSpeed(self.player1Stats, self.ble1)
                elif event.key == pygame.K_x:
                    self.increasePlayerSpeed(self.player1Stats, self.ble1)
                elif event.key == pygame.K_n:
                    self.decreasePlayerSpeed(self.player2Stats, self.ble2)
                elif event.key == pygame.K_m:
                    self.increasePlayerSpeed(self.player2Stats, self.ble2)
                elif event.key == pygame.K_r:
                    self.player1Stats.reset()
                    self.player2Stats.reset()
                elif event.key == pygame.K_1:
                    self.bleRacer1ReceviedData(0, "LAP_START")
                elif event.key == pygame.K_2:
                    self.bleRacer2ReceviedData(0, "LAP_START")
                elif event.key == pygame.K_t:
                    pygame.display.toggle_fullscreen()

            else:
                self.app.event(event)


    def draw(self):
        self.screen.fill((255, 255, 255))
        self.app.paint()
        pygame.display.flip()

    def run(self):
        while self.running:
            self.handleEvents()
            self.draw()
            self.clock.tick(30)
        pygame.quit()



    def bleRacer1ReceviedData(self, bleuart, message):
        print "p1: " + str (message)
        if message.startswith("LAP_START") and self.player1Stats:
            self.player1Stats.lapEvent()


    def bleRacer2ReceviedData(self, bleuart, message):
        print "p2: " + str (message)
        if message.startswith("LAP_START") and self.player2Stats:
            self.player2Stats.lapEvent()

    def bleInit(self):
        if sys.platform == 'darwin':
            return

        self.bleManager =  BLE_Manager("hci0")
        self.ble        =  BLE(bleManager=self.bleManager)

        self.bleManager.startScanning()

        self.ble1 = self.ble.findByName(sys.argv[1], gattOpts="-j 1")
        self.ble2 = self.ble.findByName(sys.argv[2], gattOpts="-j 2")

        self.bleManager.stopScanning()

        self.ble1.addListener(self.bleRacer1ReceviedData)
        self.ble2.addListener(self.bleRacer2ReceviedData)
Пример #18
0
class LapTimer():
    def __init__(self):
        self.player1Stats = 0
        self.player2Stats = 0
        self.mainScoreBoard = 0

        self.bleInit()
        self.lastUpdateTime = time.time()
        self.running = True
        #self.display = Display(windowed=1, windowWidth=1776, windowHeight=952)
        self.display = Display(windowed=0, windowWidth=1920,
                               windowHeight=1080)  #HDMIPI: 1920x1080

        #self.display = Display(windowed=1, windowWidth=1280, windowHeight=800)
        self.screen = self.display.screen
        self.clock = pygame.time.Clock()

        self.player1Stats = PlayerTimes(1,
                                        width=self.display.screen.get_width() /
                                        2)
        self.player2Stats = PlayerTimes(2,
                                        width=self.display.screen.get_width() /
                                        2)

        self.appInit()

    def appInit(self):
        self.app = gui.App()
        c = gui.Container(align=0, valign=0)
        self.table = self.setupTable()
        c.add(self.table, 0, 0)
        self.app.init(c)

    def decreasePlayerSpeed(self, playerStats, playerBle):
        print "decreasePlayerSpeed:%d" % playerStats.playerNum
        playerStats.currentSpeed = playerStats.currentSpeed - SPEED_DELTA
        playerBle.sendBytes([0x00, 0x00, 0x00, playerStats.currentSpeed])

    def increasePlayerSpeed(self, playerStats, playerBle):
        print "increasePlayerSpeed:%d" % playerStats.playerNum
        playerStats.currentSpeed = playerStats.currentSpeed + SPEED_DELTA
        playerBle.sendBytes([0x00, 0x00, 0x00, playerStats.currentSpeed])

    def resetBoard(self, playerStats):
        playerStats.reset()

    def setupTable(self):

        fg = (0, 0, 0)

        reset1Btn = gui.Button("Reset", style={'font': roboticaSmallFont})
        reset1Btn.connect(gui.CLICK, self.resetBoard, self.player1Stats)

        reset2Btn = gui.Button("Reset", style={'font': roboticaSmallFont})
        reset2Btn.connect(gui.CLICK, self.resetBoard, self.player2Stats)

        table = gui.Table(width=self.screen.get_width(),
                          height=self.screen.get_height())

        table.tr()
        table.td(gui.Image(basedir + "/images/cannybots_logo.png"),
                 colspan=2,
                 rowspan=1,
                 align=0,
                 valign=0)
        table.td(gui.Label(""))

        table.tr()
        table.td(gui.Label("Racer One",
                           color=fg,
                           style={'font': roboticaTitleFont}),
                 align=0,
                 valign=0)
        table.td(gui.Label("Racer Two",
                           color=fg,
                           style={'font': roboticaTitleFont}),
                 align=0,
                 valign=0)

        table.tr()
        table.td(self.player1Stats, valign=0)
        table.td(self.player2Stats, valign=0)

        table.tr()
        table.td(reset1Btn)
        table.td(reset2Btn)

        return table

    def handleEvents(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = 0
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.running = False
                elif event.key == pygame.K_z:
                    self.decreasePlayerSpeed(self.player1Stats, self.ble1)
                elif event.key == pygame.K_x:
                    self.increasePlayerSpeed(self.player1Stats, self.ble1)
                elif event.key == pygame.K_n:
                    self.decreasePlayerSpeed(self.player2Stats, self.ble2)
                elif event.key == pygame.K_m:
                    self.increasePlayerSpeed(self.player2Stats, self.ble2)
                elif event.key == pygame.K_r:
                    self.player1Stats.reset()
                    self.player2Stats.reset()
                elif event.key == pygame.K_1:
                    self.bleRacer1ReceviedData(0, "LAP_START")
                elif event.key == pygame.K_2:
                    self.bleRacer2ReceviedData(0, "LAP_START")
                elif event.key == pygame.K_t:
                    pygame.display.toggle_fullscreen()

            else:
                self.app.event(event)

    def draw(self):
        self.screen.fill((255, 255, 255))
        self.app.paint()
        pygame.display.flip()

    def run(self):
        while self.running:
            self.handleEvents()
            self.draw()
            self.clock.tick(30)
        pygame.quit()

    def bleRacer1ReceviedData(self, bleuart, message):
        print "p1: " + str(message)
        if message.startswith("LAP_START") and self.player1Stats:
            self.player1Stats.lapEvent()

    def bleRacer2ReceviedData(self, bleuart, message):
        print "p2: " + str(message)
        if message.startswith("LAP_START") and self.player2Stats:
            self.player2Stats.lapEvent()

    def bleInit(self):
        if sys.platform == 'darwin':
            return

        self.bleManager = BLE_Manager("hci0")
        self.ble = BLE(bleManager=self.bleManager)

        self.bleManager.startScanning()

        self.ble1 = self.ble.findByName(sys.argv[1], gattOpts="-j 1")
        self.ble2 = self.ble.findByName(sys.argv[2], gattOpts="-j 2")

        self.bleManager.stopScanning()

        self.ble1.addListener(self.bleRacer1ReceviedData)
        self.ble2.addListener(self.bleRacer2ReceviedData)