def _run(): child = subprocess.Popen(['./gatttool', '--device=' + device, '--adapter=hci0', '--interactive'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) # enable notifications :) child.stdin.write("connect\n") child.stdin.flush() # wait until the connection is successful time.sleep(2) # enable notifications child.stdin.write("char-write-req 0x004c 0100\n") child.stdin.flush() matcher = re.compile('Notification handle = 0x004b value: ([0-9a-f ]+)') while child.poll() is None: groups = matcher.search(child.stdout.readline()) if groups: b = groups.group(1).replace(' ', '') yaw, pitch, roll, z, y, x = tuple(struct.unpack(">H", b[i:i+2])[0] for i in range(12, len(b), 2)) app.logger.info('{} becomes {}, {}, {}, {}, {}, {}'.format(b, x, y, z, roll, pitch, yaw)) socketio.send(json.dumps([x, y, z, roll, pitch, yaw]), True); time.sleep(0.01)
def joinGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] numPlayers = db.fetchone( 'SELECT COUNT(id) FROM players WHERE gameId=%d AND joined=1; ' % gameId)[0] gameRes = db.fetchone('SELECT gameJSON FROM games WHERE id=%d; ' % gameId) game = json.loads(gameRes[0]) if numPlayers < hanabi.MAX_PLAYERS and not game['hasStarted']: db.execute( "UPDATE players SET joined=1 WHERE gameId=%d AND name='%s'" % (gameId, name)) game = getGame(db, gameId) gameMsg.buildJoinGame() send({ 'event': 'joinGame', 'message': gameMsg.message, 'game': game }, json=True, room=gameId) else: send( {'error': { 'event': 'joinGame', 'reason': 'max players exceeded' }}, json=True)
def on_ready(data): global players username = session['username'] email = session['email'] room = data['room'] send(username + ' is ready.', room=room) ready_to_go = False if players.has_key(room): ready_to_go = True # Set current player ready for i in players[room][0]: if i.email == email: i.ready = True # Query for whether all users are ready. for i in players[room][0]: print i.ready if not i.ready == True: ready_to_go = False break if ready_to_go: print 'readyok' players[room][0][0].is_turn = True emit('ready', room=data['room']) pick_word(data['room']) emit('word', {'user': players[room][0][0].get_id(), 'word': players[room][1]}, room=data['room'])
def joinGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] numPlayers = db.fetchone('SELECT COUNT(id) FROM players WHERE gameId=%d AND joined=1; ' % gameId)[0] gameRes = db.fetchone('SELECT gameJSON FROM games WHERE id=%d; ' % gameId) game = json.loads(gameRes[0]) if numPlayers < hanabi.MAX_PLAYERS and not game['hasStarted']: db.execute("UPDATE players SET joined=1 WHERE gameId=%d AND name='%s'" % (gameId, name)) game = getGame(db, gameId) gameMsg.buildJoinGame() send({ 'event': 'joinGame', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId) else: send({ 'error': { 'event': 'joinGame', 'reason': 'max players exceeded' } }, json=True)
def giveHint(msg, db, gameMsg): gameId = msg['gameId'] hintType = msg['hintType'] name = msg['name'] toName = msg['toName'] hint = int(msg['hint']) if hintType == 'NUMBER' else msg['hint'] gameRes = db.fetchone('SELECT gameJSON FROM games WHERE id=%d; ' % gameId) toPlayerRes = db.fetchone("SELECT name, handJSON FROM players WHERE gameId = %d AND name='%s'" % (gameId, toName)) game = json.loads(gameRes[0]) toPlayer = parsePlayer(toPlayerRes) if hanabi.canHint(game, name): cardsHinted = hanabi.giveHint(game, toPlayer, hintType, hint) db.execute("UPDATE games SET gameJSON='%s' WHERE id=%s" % (json.dumps(game), gameId)) db.execute("UPDATE players SET handJSON='%s' WHERE name='%s'" % (json.dumps(toPlayer['hand']), toPlayer['name'])) game = getGame(db, gameId) gameMsg.buildHint(toName, hintType, hint, cardsHinted) send({ 'event': 'giveHint', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId) else: send({ 'error': { 'event': 'giveHint', 'reason': 'invalid hint' } }, json=True)
def playCard(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] cardIndex = msg['cardIndex'] gameRes = db.fetchone('SELECT gameJSON, deckJSON FROM games WHERE id=%d; ' % gameId) playerRes = db.fetchone("SELECT name, handJSON FROM players WHERE gameId = %d AND name='%s'" % (gameId, name)) game = json.loads(gameRes[0]) deck = json.loads(gameRes[1]) player = parsePlayer(playerRes) playedCard = hanabi.playCard(game, deck, player, cardIndex) hanabi.endTurn(game) queries = [] queries.append("UPDATE games SET gameJSON='%s', deckJSON='%s' WHERE id=%s" % (json.dumps(game), json.dumps(deck), gameId)) queries.append("UPDATE players SET handJSON='%s' WHERE gameId=%d AND name='%s'" % (json.dumps(player['hand']), gameId, player['name'])) db.bulkExecute(queries) game = getGame(db, gameId) gameMsg.buildPlay(playedCard) send({ 'event': 'playCard', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId)
def startGame(msg, db, gameMsg): gameId = msg['gameId'] gameResult = db.fetchone('SELECT gameJSON FROM games WHERE id=%d; ' % gameId) players = db.fetchall('SELECT name, handJSON FROM players WHERE gameId = %d AND joined=1; ' % gameId) game = json.loads(gameResult[0]) players = [parsePlayer(i) for i in players] if (not game['hasStarted']) and len(players) > 1: game['hasStarted'] = True deck = hanabi.startGameAndGetDeck(game, players) queries = [] for player in players: queries.append("UPDATE players SET handJSON='%s' WHERE gameId=%d AND name='%s'" % (json.dumps(player['hand']), gameId, player['name'])) queries.append("UPDATE games SET gameJSON='%s', deckJSON='%s' WHERE id=%s" % (json.dumps(game), json.dumps(deck), gameId)) db.bulkExecute(queries) game = getGame(db, gameId) gameMsg.buildStartGame() send({ 'event': 'startGame', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId) else: send({ 'error': { 'event': 'startGame', 'reason': 'game already started' } }, json=True)
def handle_connect(): print "Client Connected" join_room("notify") # join notify room if use_tokens == True: emit('auth', "Please authenticate with your token.") else: emit('auth', "Please choose a nickname. ") send("User has joined socket", room = "notify")
def sendMessage(msg, db, gameMsg): gameId = msg['gameId'] message = msg['message'] name = msg['name'] gameMsg.buildMsg(message) send({ 'event': 'sendMessage', 'message' : gameMsg.message, 'game': None }, json=True, room=gameId)
def on_leave(data): global players username = session['username'] email = session['email'] room = data['room'] leave_room(room) if players.has_key(room): for i in range(players[room][0].__len__()): print i if players[room][0][i].email == email: check_out_player(players[room][0].pop(i)) send(username + ' has left the room.', room=room)
def sendMessage(msg, db, gameMsg): gameId = msg['gameId'] message = msg['message'] name = msg['name'] gameMsg.buildMsg(message) send({ 'event': 'sendMessage', 'message': gameMsg.message, 'game': None }, json=True, room=gameId)
def handle_auth(message): # Authenticate a user tok = message try: something = session["username"] # is authed already? emit("error", "Already authenticated as "+something) return except: pass if use_tokens == True: try: # Will succeed is user token is valid user = tokens[tok] send("Welcome, {}. You are connected.".format(user)) users[str(user)] = "Online" session["username"] = user # store it in a session send(session['username']+" has come online.", room = "notify") return except: # User token invalid send("Sorry, but we could not establish your identity. \ Try logging in again") emit('skick', "Invalid Token") # tell the client to disconnect disconnect() else: tok = str(tok).translate(None, "!@#$%&*()/\<>~+;'") # filter symbols # no token nonsense try: if users[str(tok)] != "Offline": # If online, deny emit('skick', "Username in use.") disconnect(); return else: # Offline, allow use token = str(uuid4()) # generate a random token tokens[token] = str(tok) rtokens[str(tok)] = token users[str(tok)] = "Online" session["username"] = tok send("You are now known as "+tok) return except: token = str(uuid4()) # generate a random token tokens[token] = str(tok) rtokens[str(tok)] = token users[str(tok)] = "Online" session["username"] = tok send("You are now known as "+tok) return
def endGame(msg, db, gameMsg): gameId = msg['gameId'] gameRes = db.fetchone('SELECT gameJSON, deckJSON FROM games WHERE id=%d; ' % gameId) game = json.loads(gameRes[0]) hanabi.giveUp(game) db.execute("UPDATE games SET gameJSON='%s' WHERE id=%s" % (json.dumps(game), gameId)) gameMsg.buildEndGame() send({ 'event': 'endGame', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId)
def on_user_connected(message): if not current_user.is_anonymous(): send("{0} has connected".format(current_user.name)) join_room(current_user.id) # user's own channel # data on current players emit("players", ujson.dumps([{ "name": p.name, "money": p.money, "cards": len(p.hand) } for p in game.players]), json=True, broadcast=True) if game._started and current_user.in_game: emit("player_hand", ujson.dumps(current_user.hand), json=True, room=current_user.id)
def handle_message(data): dataIN = json.loads(data) if dataIN.iterkeys().next() == "buttonBuilder": send(json.dumps(buttons)) print "button setup sent" if dataIN.iterkeys().next() == "ORDER_DATA": send(json.dumps(confirmReceipt)) print dataIN else: print data print type(data) print dataIN print type(dataIN)
def createGame(msg, db, gameMsg): rainbow = msg['isRainbow'] name = msg['name'] game = hanabi.newGameObject(rainbow) gameId = db.executeWithId("INSERT INTO games (gameJSON) VALUES ('%s') RETURNING id" % json.dumps(game)) db.execute("INSERT INTO players (gameId, name, handJSON, joined) VALUES (%d, '%s', '%s', 0)" % (gameId, name, '[]')) join_room(gameId) game = getGame(db, gameId) gameMsg.buildEnterGame() send({ 'event': 'enterGame', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId)
def handle_jroom(message): tjroom = str(message) channel = tjroom user = session["username"] if tjroom.startswith("#") and "+" not in tjroom: # if channel emit('joinroom', tjroom) # emit a message to make them join # tell the room text = user+" has joined "+tjroom tjson = '{"room": "'+tjroom+'", "text": "'+text+'", "from": "'+"<strong style='color:red'>System</strong>"+'"}' send(tjson, room=channel) # send it :) join_room(tjroom) elif user in invited[tjroom]: # was invited, i.e, PM or otherwise join_room(tjroom)
def leaveGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] leave_room(gameId) gameMsg.buildLeaveGame() send({ 'event': 'leaveGame', 'message' : gameMsg.message, 'game': None # no game returned since it doesn't change the game state }, json=True) send({ 'event': 'leaveGame', 'message' : gameMsg.message, 'game': None # no game returned since it doesn't change the game state }, json=True, room=gameId)
def handle_json(json): json = jsondecode.loads(json) channel = json['room'] text = str(json['text']) if text[0] == "/": handle_command(text) return # it's a command! text = text.translate(None, '}{<>') #antiXSS text = text.replace("'", "\'") text = text.replace('"', '\"') user = session["username"] tjson = '{"room": "'+channel+'", "text": "'+text+'", "from": "'+user+'"}' send(tjson, room=channel) # send it :)
def startGame(msg, db, gameMsg): gameId = msg['gameId'] gameResult = db.fetchone('SELECT gameJSON FROM games WHERE id=%d; ' % gameId) players = db.fetchall( 'SELECT name, handJSON FROM players WHERE gameId = %d AND joined=1; ' % gameId) game = json.loads(gameResult[0]) players = [parsePlayer(i) for i in players] if (not game['hasStarted']) and len(players) > 1: game['hasStarted'] = True deck = hanabi.startGameAndGetDeck(game, players) queries = [] for player in players: queries.append( "UPDATE players SET handJSON='%s' WHERE gameId=%d AND name='%s'" % (json.dumps(player['hand']), gameId, player['name'])) queries.append( "UPDATE games SET gameJSON='%s', deckJSON='%s' WHERE id=%s" % (json.dumps(game), json.dumps(deck), gameId)) db.bulkExecute(queries) game = getGame(db, gameId) gameMsg.buildStartGame() send({ 'event': 'startGame', 'message': gameMsg.message, 'game': game }, json=True, room=gameId) else: send( { 'error': { 'event': 'startGame', 'reason': 'game already started' } }, json=True)
def endGame(msg, db, gameMsg): gameId = msg['gameId'] gameRes = db.fetchone( 'SELECT gameJSON, deckJSON FROM games WHERE id=%d; ' % gameId) game = json.loads(gameRes[0]) hanabi.giveUp(game) db.execute("UPDATE games SET gameJSON='%s' WHERE id=%s" % (json.dumps(game), gameId)) gameMsg.buildEndGame() send({ 'event': 'endGame', 'message': gameMsg.message, 'game': game }, json=True, room=gameId)
def enterGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] sameNameExists = False players = [parsePlayer(i) for i in db.fetchall('SELECT name, handJSON FROM players WHERE gameId = %d; ' % gameId)] for player in players: if player['name'] == name: sameNameExists = True send({ 'error': { 'event': 'enterGame', 'reason': 'same name exists' } }, json=True) break if not sameNameExists: db.execute("INSERT INTO players (gameId, name, handJSON, joined) VALUES (%d, '%s', '%s', 0)" % (gameId, name, '[]')) game = getGame(db, gameId) gameMsg.buildEnterGame() send({ 'event': 'enterGame', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId) join_room(gameId) messages = [parseMessage(i) for i in db.fetchall("SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId)] gameMsg.message['elements']['messages'] = messages send({ 'event': 'enterGame', 'message' : gameMsg.message, 'game': game }, json=True)
def resumeGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] players = db.fetchall("SELECT name FROM players WHERE gameId = %d AND name='%s'" % (gameId, name)) if len(players) != 0: game = getGame(db, gameId) gameMsg.buildResumeGame() send({ 'event': 'resumeGame', 'message' : gameMsg.message, 'game': game }, json=True, room=gameId) join_room(gameId) messages = [parseMessage(i) for i in db.fetchall("SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId)] gameMsg.message['elements']['messages'] = messages send({ 'event': 'resumeGame', 'message' : gameMsg.message, 'game': game }, json=True) else: send({ 'error': { 'event': 'resumeGame', 'reason': 'no player with name exists' } }, json=True)
def on_message(message): if message["data"][0] == "/": command = message["data"][1:] if command == "start": game.run() send("{0} has started the game".format(current_user.name), broadcast=True) # show each player their hands for token in socketio.rooms["/game"].keys(): hand = ujson.dumps(game.get_player(token).hand) emit("player_hand", hand, json=True, room=token) # update player box with current data emit("players", ujson.dumps([{ "name": p.name, "money": p.money, "cards": len(p.hand) } for p in game.players]), json=True, broadcast=True) else: send("{0}: {1}".format(current_user.name, message["data"]), broadcast=True)
def createGame(msg, db, gameMsg): rainbow = msg['isRainbow'] name = msg['name'] game = hanabi.newGameObject(rainbow) gameId = db.executeWithId( "INSERT INTO games (gameJSON) VALUES ('%s') RETURNING id" % json.dumps(game)) db.execute( "INSERT INTO players (gameId, name, handJSON, joined) VALUES (%d, '%s', '%s', 0)" % (gameId, name, '[]')) join_room(gameId) game = getGame(db, gameId) gameMsg.buildEnterGame() send({ 'event': 'enterGame', 'message': gameMsg.message, 'game': game }, json=True, room=gameId)
def giveHint(msg, db, gameMsg): gameId = msg['gameId'] hintType = msg['hintType'] name = msg['name'] toName = msg['toName'] hint = int(msg['hint']) if hintType == 'NUMBER' else msg['hint'] gameRes = db.fetchone('SELECT gameJSON FROM games WHERE id=%d; ' % gameId) toPlayerRes = db.fetchone( "SELECT name, handJSON FROM players WHERE gameId = %d AND name='%s'" % (gameId, toName)) game = json.loads(gameRes[0]) toPlayer = parsePlayer(toPlayerRes) if hanabi.canHint(game, name): cardsHinted = hanabi.giveHint(game, toPlayer, hintType, hint) db.execute("UPDATE games SET gameJSON='%s' WHERE id=%s" % (json.dumps(game), gameId)) db.execute("UPDATE players SET handJSON='%s' WHERE name='%s'" % (json.dumps(toPlayer['hand']), toPlayer['name'])) game = getGame(db, gameId) gameMsg.buildHint(toName, hintType, hint, cardsHinted) send({ 'event': 'giveHint', 'message': gameMsg.message, 'game': game }, json=True, room=gameId) else: send({'error': { 'event': 'giveHint', 'reason': 'invalid hint' }}, json=True)
def leaveGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] leave_room(gameId) gameMsg.buildLeaveGame() send( { 'event': 'leaveGame', 'message': gameMsg.message, 'game': None # no game returned since it doesn't change the game state }, json=True) send( { 'event': 'leaveGame', 'message': gameMsg.message, 'game': None # no game returned since it doesn't change the game state }, json=True, room=gameId)
def playCard(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] cardIndex = msg['cardIndex'] gameRes = db.fetchone( 'SELECT gameJSON, deckJSON FROM games WHERE id=%d; ' % gameId) playerRes = db.fetchone( "SELECT name, handJSON FROM players WHERE gameId = %d AND name='%s'" % (gameId, name)) game = json.loads(gameRes[0]) deck = json.loads(gameRes[1]) player = parsePlayer(playerRes) playedCard = hanabi.playCard(game, deck, player, cardIndex) hanabi.endTurn(game) queries = [] queries.append( "UPDATE games SET gameJSON='%s', deckJSON='%s' WHERE id=%s" % (json.dumps(game), json.dumps(deck), gameId)) queries.append( "UPDATE players SET handJSON='%s' WHERE gameId=%d AND name='%s'" % (json.dumps(player['hand']), gameId, player['name'])) db.bulkExecute(queries) game = getGame(db, gameId) gameMsg.buildPlay(playedCard) send({ 'event': 'playCard', 'message': gameMsg.message, 'game': game }, json=True, room=gameId)
def handle_pmuser(message): # person to PM try: user = session["username"] try: status = users[str(message)] if status == "Online": pass else: emit('error', "User specified is not online.") return except: emit('error', "User specified not found.") return room = "PM:"+str(user)+"+"+str(message) invited[room] = [message] # message = user being PMed # ^ Invite them to the room, so that they can join join_room(room) # notify other client, through notify channel send('{"tojoin": "'+message+'", "joined": "'+user+'"}', room = "notify") # send a push event except: emit('error', "You are not logged in!")
def enterGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] sameNameExists = False players = [ parsePlayer(i) for i in db.fetchall( 'SELECT name, handJSON FROM players WHERE gameId = %d; ' % gameId) ] for player in players: if player['name'] == name: sameNameExists = True send( { 'error': { 'event': 'enterGame', 'reason': 'same name exists' } }, json=True) break if not sameNameExists: db.execute( "INSERT INTO players (gameId, name, handJSON, joined) VALUES (%d, '%s', '%s', 0)" % (gameId, name, '[]')) game = getGame(db, gameId) gameMsg.buildEnterGame() send({ 'event': 'enterGame', 'message': gameMsg.message, 'game': game }, json=True, room=gameId) join_room(gameId) messages = [ parseMessage(i) for i in db.fetchall( "SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId) ] gameMsg.message['elements']['messages'] = messages send({ 'event': 'enterGame', 'message': gameMsg.message, 'game': game }, json=True)
def resumeGame(msg, db, gameMsg): gameId = msg['gameId'] name = msg['name'] players = db.fetchall( "SELECT name FROM players WHERE gameId = %d AND name='%s'" % (gameId, name)) if len(players) != 0: game = getGame(db, gameId) gameMsg.buildResumeGame() send({ 'event': 'resumeGame', 'message': gameMsg.message, 'game': game }, json=True, room=gameId) join_room(gameId) messages = [ parseMessage(i) for i in db.fetchall( "SELECT name, type, messageJSON, time FROM messages WHERE gameId = %d; " % gameId) ] gameMsg.message['elements']['messages'] = messages send({ 'event': 'resumeGame', 'message': gameMsg.message, 'game': game }, json=True) else: send( { 'error': { 'event': 'resumeGame', 'reason': 'no player with name exists' } }, json=True)
def on_connect_test(): send('connected-test')
def on_connect(): send('connected') session['a'] = 'b'
def on_room_namespace_event(data): room = data.pop('room') send('room message', room=room)
def on_json(data): send(data, json=True, broadcast=True)
def on_message(message): send(message)
def on_message_test(message): send(message)
def on_message(message): send(message) if message not in "test noack": return message
def on_message(message): send(message) if message == 'test session': session['a'] = 'b' if message not in "test noack": return message
def on_json(data): send(data, json=True, broadcast=True) if not data.get('noack'): return data
def test_message(message): send('', "Hello, " + message)
def on_connect(): send('connected')
def on_json_test(data): send(data, json=True, namespace='/test')
def on_leave(data): room = data.get('room') user = data.get('user') leave_room(room) emit('status', {'msg': user + ' has left the room.'}, room=room) send(user + ' has left the room.', room=room)
def on_leave(data): room = data['room'] leave_room(room) send(username + ' has left the room.', room=room) print('leave')
def client_connect(): print('Web client connected.') send('client_connect', broadcast=True) emit('event', {'type': 'client_connect'})