Beispiel #1
0
def main():
    print 'Put Wiimote in discoverable mode now (press 1+2)...'
    global wiimote
    if len(sys.argv) > 1:
        wiimote = cwiid.Wiimote(sys.argv[1])
    else:
        wiimote = cwiid.Wiimote()

    wiimote.rpt_mode = cwiid.RPT_BALANCE | cwiid.RPT_BTN
    wiimote.request_status()

    balance_calibration = wiimote.get_balance_cal()
    named_calibration = {
        'right_top': balance_calibration[0],
        'right_bottom': balance_calibration[1],
        'left_top': balance_calibration[2],
        'left_bottom': balance_calibration[3],
    }

    exit = False
    while not exit:
        print "Type q to quit, or anything else to report your weight"
        c = sys.stdin.read(1)
        if c == 'q':
            exit = True
            break
        wiimote.request_status()
        weight = (calcweight(wiimote.state['balance'], named_calibration))
        logweight(weight)

    return 0
Beispiel #2
0
def main():
    #Connect to address given on command-line, if present
    print 'Put Wiimote in discoverable mode now (press 1+2)...'
    global wiimote
    if len(sys.argv) > 1:
        wiimote = cwiid.Wiimote(sys.argv[1])
    else:
        wiimote = cwiid.Wiimote()

    wiimote.rpt_mode = cwiid.RPT_BALANCE | cwiid.RPT_BTN
    wiimote.request_status()

    balance_calibration = wiimote.get_balance_cal()
    named_calibration = {
        'right_top': balance_calibration[0],
        'right_bottom': balance_calibration[1],
        'left_top': balance_calibration[2],
        'left_bottom': balance_calibration[3],
    }
    while True:
        #print "Type q to quit, or anything else to report your weight"
        #c = sys.stdin.read(1)
        #if c == 'q':
        #	exit = True
        wiimote.request_status()
        print "%.2fkg" % (
            calcweight(wiimote.state['balance'], named_calibration) / 100.0, )
        time.sleep(1)
    return 0
def main():
    #Connect to address given on command-line, if present
    print 'Put Wiimote in discoverable mode now (press red button)...'
    global wiimote
    if len(sys.argv) > 1:
        wiimote = cwiid.Wiimote(sys.argv[1])
    else:
        wiimote = cwiid.Wiimote()

    wiimote.rpt_mode = cwiid.RPT_BALANCE | cwiid.RPT_BTN
    wiimote.request_status()

    if wiimote.state['ext_type'] != cwiid.EXT_BALANCE:
        print 'This program only supports the Wii Balance Board'
        wiimote.close()
        return -1

    balance_calibration = wiimote.get_balance_cal()
    named_calibration = {
        'right_top': balance_calibration[0],
        'right_bottom': balance_calibration[1],
        'left_top': balance_calibration[2],
        'left_bottom': balance_calibration[3],
    }

    exit = False
    print "Type q to quit, or anything else to report your weight"
    while not exit:
        c = None
        c = sys.stdin.readline()
        c = c.strip('\n')
        c = c.strip('\t')
        c = c.strip(' ')
        if c.startswith('q'):
            exit = True
        wiimote.request_status()
        weight = "%.2f" % (
            calcweight(wiimote.state['balance'], named_calibration) / 100.0, )
        weight = float(weight)
        weightlbs = (weight * 2.2) + 2
        weight_dict = {}
        weight_dict['hid'] = wii_balance_hid
        weight_dict['wt_value'] = str("%.2f" % (weight))
        weight_dict['wt_units'] = "l"
        weight_dict['ttype'] = "omhe"
        weight_dict['texti'] = str("wt=%.2f" % (weight))
        weight_dict['subj'] = "%s" % (c)
        d = datetime.utcnow()
        weight_dict['evdt'] = d.strftime("%d%m%y:%H%M%Sz")
        weight_dict['evtz'] = timezone_offset
        jsonstr = json.dumps(
            weight_dict,
            indent=4,
        )
        print jsonstr
        file = open(weight_output_file, 'w')
        file.write(jsonstr)
        file.close()

    return 0
Beispiel #4
0
def main():
	#Connect to address given on command-line, if present
	print 'Put Wiimote in discoverable mode now (press 1+2)...'
	global wiimote
	if len(sys.argv) > 1:
		wiimote = cwiid.Wiimote(sys.argv[1])
	else:
		wiimote = cwiid.Wiimote()

	wiimote.rpt_mode = cwiid.RPT_BALANCE | cwiid.RPT_BTN
	wiimote.request_status()

#	if wiimote.state['ext_type'] != cwiid.EXT_BALANCE:
#		print 'This program only supports the Wii Balance Board'
#		wiimote.close()
#		return -1

	balance_calibration = wiimote.get_balance_cal()
	named_calibration = { 'right_top': balance_calibration[0],
						  'right_bottom': balance_calibration[1],
						  'left_top': balance_calibration[2],
						  'left_bottom': balance_calibration[3],
						}

	exit = False
	while not exit:
		print "Type q to quit, or anything else to report your weight"
		c = sys.stdin.read(1)
		if c == 'q':
			exit = True
		wiimote.request_status()
		print "%.2fkg" % (calcweight(wiimote.state['balance'], named_calibration) / 100.0, )

	return 0
Beispiel #5
0
def winit(address=None, num_of_tries=3):
    """init with address obtaining with hcitool scan
    is quicker and enables more wiimotes!!! 

    my current wiimotes: 
    white: 00:24:1E:A7:C4:90
    black: 00:26:59:F6:A0:75 (Honza Vancl)
    """
    print "na wii ovladaci zmacknout tlacitka 1 a 2 !!!"
    print "press 1 and 2 button on a wiimote!!!"
    wm = None
    ok = False
    iinit = 0
    while not ok and iinit < num_of_tries:
        # print iinit
        try:
            if address is None:
                wm = cwiid.Wiimote()
            else:
                wm = cwiid.Wiimote(address)
            wm.rumble = 1
            time.sleep(0.2)
            wm.rumble = 0
            wm.rpt_mode = cwiid.RPT_IR | cwiid.RPT_BTN
            ok = True
        except:
            ok = False
            iinit += 1
    ok = False
    return wm
Beispiel #6
0
 def __init__(self, macaddr=None):
     if macaddr is None:
         self.__wiimote = cwiid.Wiimote()
     else:
         self.__wiimote = cwiid.Wiimote(macaddr)
     self.__wiimote.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_IR
     # for get_rel's history
     self.rel_old_pos = (0, 0) 
     # for getl_pos's history, when no LED is seen
     self.pos_old_pos = (0, 0, False) 
     self.__thread = None
Beispiel #7
0
    def get_wiimote(self):
        if not self._wiimote:
            if self._bdaddr:
                self._wiimote = cwiid.Wiimote(bdaddr=self._bdaddr)
            else:
                self._wiimote = cwiid.Wiimote()

            self._wiimote.enable(cwiid.FLAG_MOTIONPLUS)
            self._wiimote.rpt_mode = cwiid.RPT_ACC | cwiid.RPT_BTN | cwiid.RPT_MOTIONPLUS

            self.logger.info('WiiMote connected')
            self._last_btn_event_time = time.time()
            self.bus.post(WiimoteConnectionEvent())

        return self._wiimote
Beispiel #8
0
def connect():
    global wii
    # Connecting to the wiimote, lights to show status!
    while True:
        try:
            #print "Trying connection"
            mcpwriteb(2 + 2**6)
            wii = cwiid.Wiimote()
        except RuntimeError:
            #print "Error opening wiimote connection"
            mcpwriteb(1 + 2**7)
            time.sleep(0.25)
            mcpwriteb(0)
            time.sleep(0.25)
            mcpwriteb(1 + 2**7)
            time.sleep(0.25)
            mcpwriteb(0)
            continue
        else:
            #print "Connection made"
            mcpwriteb(2**2 + 2**5)
            time.sleep(0.25)
            mcpwriteb(0)
            time.sleep(0.25)
            mcpwriteb(2**2 + 2**5)
            time.sleep(0.25)
            mcpwriteb(0)
            return
Beispiel #9
0
def detect(m):
    flag=1
    count=0
    #Connect to the wii remote
    print 'Put Wiimote in discoverable mode now (press 1+2)...'
    w = cwiid.Wiimote()
    # Request nunchuk to be active.
    w.rpt_mode = cwiid.RPT_IR
   # Turn on LED1 so we know we're connected.
    w.led = 1
    while 1:
        try:
            x= w.state['ir_src'][0]['pos'][0]
            y= w.state['ir_src'][0]['pos'][1]
            flag=1
            m.ptsArry.append([(1024-x),(768-y)])
            draw(m) 
            time.sleep(0.01)
        except Exception, e:
            x=0
            y=0
            if flag==1:
                flag=-1
                m.ARRAY.append(m.ptsArry)
                m.ptsArry=[]
Beispiel #10
0
 def connect(self):
     '''
   try to establish bluetooth communication with wii controller
   once connected, set LED to indicate distance
   set to button mode or it won't work at all
   if no connection, count and then return
   
   funciton returns 
      True when it connects
      False after 10 timeouts
   
   '''
     i = 2
     while not self.wm:
         try:
             self.wm = cwiid.Wiimote()
             self.wiiPendantConnected = True
             self.wm.led = self.L[self.LED_ON]
             self.wm.rpt_mode = cwiid.RPT_BTN
             return (True)
         except RuntimeError:
             if (i > 5):
                 return (False)
             #print ("Error opening wiimote connection" )
             time.sleep(5)
             print("attempt " + str(i))
             i += 1
Beispiel #11
0
def main():
    print 'Press button 1 + 2 on your Wii Remote...'
    time.sleep(1)

    wm = cwiid.Wiimote()
    print 'Wii Remote connected...'
    print '\nPress the PLUS button to disconnect the Wii and end the application'
    time.sleep(1)

    Rumble = False
    ####				ONLY NEED RPT_CLASSIC
    wm.rpt_mode = cwiid.RPT_CLASSIC
    position = 50
    print 'starting position: ', position
    b = 0
    while True:

        a = wm.state['classic']
        #		a = a['buttons']
        #		b = wm.state['buttons']
        if b == a:
            continue

        print(a)
        b = a
        #		print(bin(b))
        #		print(wm.state)
        time.sleep(.01)
Beispiel #12
0
def wiimote():
    pixel_output = bytearray(args.num_leds * PIXEL_SIZE + 3)
    print 'Put Wiimote in discoverable mode now (press 1+2)...'
    global wiimote
    global wii_movetimeout
    global wii_movedir
    global wii_color 
    wii_color = bytearray(PIXEL_SIZE)
    wiimote = cwiid.Wiimote()
    wiimote.mesg_callback = callback
    print "Displaying..."
    pixel_index = 0
    wiimote.rpt_mode = cwiid.RPT_ACC
    move_timeout = 0;
    while True:
	if move_timeout >= wii_movetime:
            move_timeout = 0
            if wii_movedir == 1:
                pixel_index = (pixel_index + 1)%args.num_leds
            else:
                pixel_index = pixel_index - 1
		if pixel_index == -1:
                    pixel_index = args.num_leds
        move_timeout = move_timeout + 1

#is this needed; poling?
	wiimote.request_status()

	pixel_output[((pixel_index)*PIXEL_SIZE):] = filter_pixel(wii_color[:], 1)
	pixel_output += '\x00'* ((args.num_leds+1-pixel_index)*PIXEL_SIZE)
	write_stream(pixel_output)
	spidev.flush()
	time.sleep(wii_move_timeout)
Beispiel #13
0
def main():
    global wiimote
    global rpt_mode
    global connected
    global rumble
    global b_val
    print("Press 1+2 to connect Wii")
    while not connected:
        try:
            wiimote = cwiid.Wiimote()
            print("Connected!")
            connected = True
            rumble ^= 1
            wiimote.rumble = rumble
            time.sleep(2)
            rumble ^= 1
            wiimote.rumble = rumble
        except:
            print("Trying Again, please press 1+2")
            time.sleep(2)


# Now setup Wii Callback, Buttons, and Accelerometer
    wiimote.mesg_callback = callback
    # For Thing we enable ACC and Button
    rpt_mode ^= cwiid.RPT_BTN

    # Enable the messages in callback
    wiimote.enable(cwiid.FLAG_MESG_IFC)
    wiimote.rpt_mode = rpt_mode

    while True:
        time.sleep(1)
Beispiel #14
0
def main():

    # Connect wiimote
    print 'Put Wiimote in discoverable mode now (press 1+2)'
    
    global wiimote 
    wiimote = cwiid.Wiimote()
    wiimote.mesg_callback = wiimote_callback
    # Activate button reporting
    wiimote.rpt_mode = cwiid.RPT_BTN
    wiimote.enable(cwiid.FLAG_MESG_IFC);
    
    # Speed indicator
    set_leds()
    
    print('Ready to go.  "x" to exit.')
    exit = False
    
    # Demonstrate that motors are working
    quarter_speed = int(MAX_SPEED/4)
    motors.setSpeeds(quarter_speed, quarter_speed)
    time.sleep(0.25)
    motors.setSpeeds(-quarter_speed, -quarter_speed)
    time.sleep(0.25)
    motors.setSpeeds(0,0)

    # Infinite loop / press x to quit
    while not exit:
        c = sys.stdin.read(1)
        if c == 'x':
            exit = True
            
    wiimote.close()
Beispiel #15
0
    def __init__(self, n):
        self.btn1 = False
        self.btn2 = False
        self.btnA = False
        self.btnB = False
        self.btnC = False
        self.btnZ = False
        self.btnUp = False
        self.btnDown = False
        self.btnLeft = False
        self.btnRight = False
        self.id = id
        self.active = True
        self.wm = None
        self.stickH = 0
        self.stickV = 0

        # Connection à la manette Wii
        print "Simultaneously press Wii remote buttons 1 and 2 now"
        i = 1
        while not self.wm:
            try:
                self.wm = cwiid.Wiimote()
            except RuntimeError:
                if i > 10:
                    quit()
                    break
                print "Failed to connect to Wii remote"
                print "Tentative " + str(i)
                i += 1
        print "Wii remote successfully connected"
        self.wm.led = n
        self.wm.rumble = True
        time.sleep(.2)
        self.wm.rumble = False
Beispiel #16
0
 def get_wiimote(self):
     while not rospy.is_shutdown():
         try:
             return cwiid.Wiimote()
         except:
             pass
         rospy.sleep(1)
Beispiel #17
0
 def connect(self):
     self.instruct = "Connecting to Wiimote, please press 1 + 2..."
     if not self.wm:
         attempt_number = 1
         while attempt_number:
             try:
                 start = time()
                 self.wm = cwiid.Wiimote()
             except Exception:
                 if time() - start < 1:
                     # Bluetooth error is faster, no other way to check
                     WiimoteUI.bluetoothExists = False
                     self.instruct = "Please install Bluetooth or turn it on."
                     return
                 attempt_number += 1
                 if attempt_number > 2:
                     self.instruct = "Connection failed, retrying with attempt #{}... (continue to press 1 + 2)".format(
                         attempt_number)
             else:
                 attempt_number = 0
     self.instruct = "Connected successfully!"
     self.status = "Status: uncalibrated"
     self.connection = "Connection: connected"
     confirm_connected(self.wm)
     self.battery = "Battery: {}%".format(round(get_battery(self.wm) * 100))
Beispiel #18
0
	def __init__(self):
		print('Press 1+2 on the wiimote now')
		sleep(1)
		self.wm = cwiid.Wiimote()
		print('Connected!')
		self.wm.led = 0b0011
		self.wm.rpt_mode = cwiid.RPT_BTN
Beispiel #19
0
def main():

    #Connect to address given on command-line, if present
    print 'Put Wiimote in discoverable mode now (press 1+2)...'
    global wiimote

    global connected
    connected = False
    print("Trying Connection")
    print("Press 1+2")
    while not connected:
        try:
            wiimote = cwiid.Wiimote()
            print("Connected!")
            connected = True
        except:
            print("Trying Again, please press 1+2")
            time.sleep(1)

    wiimote.mesg_callback = callback

    print("For Thing we enable ACC and Button")
    w = handle_input(wiimote, 'b')
    i = handle_input(wiimote, 'a')
    print menu
    exit = 0
    while not exit:
        c = sys.stdin.read(1)
        exit = handle_input(wiimote, c)
    wiimote.close()
def main():

    print 'Press button 1 + 2 on your Wii Remote...'
    time.sleep(1)
    wm=cwiid.Wiimote()
	print 'Wii Remote connected...'
	print '\nPress the PLUS button to disconnect the Wii and end the application'
Beispiel #21
0
    def pair(self):

        thread.start_new_thread(self.pairSignal, (
            "signalblink",
            self.writeLevel,
        ))

        if (self.enableBlueTooth):

            print 'Press 1+2 on your Wiimote now...'

            attempts = 1

            while not self.wm:

                try:

                    self.wm = cwiid.Wiimote()

                except RuntimeError:

                    print "Error opening wiimote connection"
                    print "attempt " + str(attempts)

                attempts += 1

            self.isPaired = True
            self.wm.led = 1
            self.wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC
            print 'PAIRED'
            GPIO.setup(self.signalLight, True)

            time.sleep(3)
Beispiel #22
0
def main():

    # Connect wiimote
    print 'Put Wiimote in discoverable mode now (press 1+2)'
    
    global wiimote 
    wiimote = cwiid.Wiimote()
    wiimote.mesg_callback = wiimote_callback
    # Activate button reporting
    wiimote.rpt_mode = cwiid.RPT_BTN
    wiimote.enable(cwiid.FLAG_MESG_IFC);
    
    # Speed indicator
    set_leds()
    
    print('Ready to go.  "x" to exit.')
    exit = False
    
    # Demonstrate that motors are working
    left_motor.go()
    right_motor.go()
    time.sleep(0.25)
    left_motor.go(forward=False)
    right_motor.go(forward=False)
    time.sleep(0.25)
    left_motor.stop()
    right_motor.stop()

    # Infinite loop / press x to quit
    while not exit:
        c = sys.stdin.read(1)
        if c == 'x':
            exit = True
            
    wiimote.close()
Beispiel #23
0
def get_wiimote(require_nunchuk=False):
    print("Press 1+2 on your Wiimote to connect...")
    wm = None
    while (wm == None):
        try:
            wm = cwiid.Wiimote()

        except RuntimeError as e:
            print(e)
            print("Trying again...")

    print("Connected!")
    wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC | cwiid.RPT_EXT
    wm.rumble = True
    time.sleep(0.25)
    wm.rumble = False

    if require_nunchuk and 'nunchuk' not in wm.state:
        print("Please connect a Nunchuk.", end=" ")
        led = 0
        while 'nunchuk' not in wm.state:
            time.sleep(0.25)

        print("OK")

    time.sleep(0.25)
    wm.led = 1

    return wm
Beispiel #24
0
    def __init__(self, max_tries=5, joystick_range=None):
        self.joystick_range = joystick_range if joystick_range else [50, 200]
        self.wm = None
        attempts = 0

        logging.info("Press 1+2 on your Wiimote now...")

        # Attempt to get a connection to the wiimote
        # try a few times, as it can take a few attempts
        while not self.wm:
            try:
                self.wm = cwiid.Wiimote()
            except RuntimeError:
                if attempts == max_tries:
                    logging.error("cannot create connection")
                    raise WiimoteException(
                        "Could not create connection within {0} tries".format(
                            max_tries))
                logging.error("Error opening wiimote connection")
                logging.error("attempt {0}".format(attempts))
                attempts += 1

        # set wiimote to report button presses and accelerometer state
        self.wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC | cwiid.RPT_EXT

        # Set led state
        self.wm.led = 1
Beispiel #25
0
def setup():

    # Try to connect Wii Mote
    print ("Press 1 + 2 button on Wii Remote")
    time.sleep(1)

    try:
        wii = cwiid.Wiimote()
    except RuntimeError:
        print ("Failed to connect Wii Remote")
        quit()

    print ("Success to connect Wii Remote")
    print ("Press PLUS + MINUS to terminate")

    # Set areas for Wii Mote to process
    remote = wii.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC
    nunchuk = wii.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_NUNCHUK

    print (remote, nunchuk)

    wii.led = setLedNum()
    wii.rumble = True
    time.sleep(0.1)
    wii.rumble = False

    stateDict = wii.state
    stateList = list(stateDict)

    return wii
 def run(self):
     if self.status:
         self.status.pop(self.sc)
         self.status.push(self.sc,
                          "Please press 1+2 on your Wiimote...")
     
     try:
         self.wiiMote = cwiid.Wiimote(self.wiiAddress)
         self.connected = True
         self.wiiMote.enable(cwiid.FLAG_MESG_IFC)
         self.wiiMote.rpt_mode = cwiid.RPT_ACC
         self.acc_cal = self.wiiMote.get_acc_cal(cwiid.EXT_NONE)
         
         if self.status:
             self.status.pop(self.sc)
             self.status.push(self.sc,
                              "Wiimote connected.")
     except:
         self.timed_out = True
         if self.status:
             self.status.pop(self.sc)
             self.status.push(self.sc,
                              "Connection failed. Please try again.")
     finally:
         if self.callback:
             self.callback(self)
Beispiel #27
0
    def __init__(self,
                 world,
                 balls,
                 sprite,
                 control='Mouse',
                 color=(0, 0, 255),
                 mouseOffset=(0, 0)):

        Player.playerCount += 1
        self.playerNum = Player.playerCount
        self.control = control
        self.color = color
        self.sprite = sprite

        self.world = world
        self.balls = balls

        self.ball = None
        self.points = 0

        self.active = False
        self.hud = None

        self.mouseOffset = mouseOffset

        if self.control == "Wiimote":
            # Setup Wiimotes
            print 'Press 1+2 on your Wiimote now'
            # TODO try catch
            self.wm = cwiid.Wiimote()
            self.wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC
            self.wmstate = self.wm.state
Beispiel #28
0
def receive_translations(list):
 print('Connect Wiimote to recieve messages:')
 print ('Please press buttons 1 + 2 on your Wiimote now ...')
 time.sleep(1)
 try:
  wii=wii=cwiid.Wiimote()
 except RuntimeError:
   print ("Cannot connect to your Wiimote.Please try again!")
   quit()
 letter=[]
 word=[]
 for letters in list:
  for chr in letters:
   if (chr==("dash")):
    wii.rumble=1
    time.sleep(1)
    wii.rumble=0
    time.sleep(1)
    letter.append('-')
   if (chr==("dot")):
    time.sleep(2)
    letter.append('0')
  print("",letter)
  letter=[]
  wii.led = 15
  time.sleep(1)
  wii.led = 0
Beispiel #29
0
    def __init__(self):
        self.limit_rp = False
        self.limit_thrust = False
        self.limit_yaw = False

        print("Press 1 + 2 to connect wii")
        time.sleep(1)
        self.wm = cwiid.Wiimote()
        self.wm.rpt_mode = cwiid.RPT_BTN
        logger.info("FOUND WIIMOTE")
        self.data = {
            "roll": 0.0,
            "pitch": 0.0,
            "yaw": 0.0,
            "thrust": -1.0,
            "estop": False,
            "exit": False,
            "althold": False,
            "alt1": False,
            "alt2": False,
            "pitchNeg": False,
            "rollNeg": False,
            "pitchPos": False,
            "rollPos": False
        }
        self.wii_thread = HandleWiimote(self, self.wm)
        self.wii_thread.start()
Beispiel #30
0
def main():
    print 'Press button 1 + 2 on your Wii Remote...'

    wm = cwiid.Wiimote()
    if not wm:
        print 'Failed to connect with your Wii Remote'
        return

    print 'Connected with your Wii Remote'
    time.sleep(1)

    wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC | cwiid.RPT_IR

    server = socket.socket()
    server.bind(('0.0.0.0', 12357))
    server.listen(1)
    connection, address = server.accept()

    while True:
        s = connection.recv(4)
        if s.startswith('GET'):
            points = []
            for src in wm.state['ir_src']:
                if src:
                    points.append(src['pos'])
            connection.send('%d\n' % len(points))
            for point in points:
                connection.send('%d %d\n' % point)
        elif s.startswith('QUT'):
            connection.close()
            wm.close()
            break