Esempio n. 1
0
def api_message():
    # get the appliance info
    appliance = db.session.query(Appliance).first()

    # build the response
    response = {"response": "", "result": {}}

    # check apitoken matches
    apitoken = request.args.get('apitoken', '')
    if apitoken == appliance.apitoken:
        message = request.args.get('text', 'no message')
        status = request.args.get('status', 'success')
        reloader = request.args.get('reload', 'false')
        if reloader == 'true' or reloader == '1':
            reloader = True
        else:
            reloader = False

        response['response'] = status
        response['result'] = {"message": message, "reload": reloader}
        socketio.emit('message', {"data": response}, namespace='/utterio')
        return jsonify(response)
    else:
        response['response'] = "error"
        response['result'] = "apitoken is invalid"
        return jsonify(response), 401
Esempio n. 2
0
def api_message():
	# get the appliance info
	appliance = db.session.query(Appliance).first()

	# build the response
	response = {"response": "", "result": {}}

	# check apitoken matches
	apitoken = request.args.get('apitoken', '')
	if apitoken == appliance.apitoken:
		message = request.args.get('text', 'no message')
		status = request.args.get('status', 'success')
		reloader = request.args.get('reload', 'false')
		if reloader == 'true' or reloader == '1':
			reloader = True
		else:
			reloader = False
		
		response['response'] = status
		response['result'] = {"message": message, "reload": reloader}
		socketio.emit('message', {"data": response}, namespace='/utterio')
		return jsonify(response)
	else:
		response['response'] = "error"
		response['result'] = "apitoken is invalid"
		return jsonify(response), 401
Esempio n. 3
0
    def post_create(cls, result, *args, **kwargs):
        if type(result) is dict:
            feedback_id = result.get('id')
            feedback = cls.query.filter_by(id=feedback_id).first()
            result['render'] = feedback.answer.render()
            result['render_own_question'] = feedback.answer.render_own_question()
        else:
            feedback = result
        result_emit = {
            'id': feedback.answer_id,
            'render': feedback.answer.render()
        }
        socketio.emit('feedbacks', result_emit)

        # Modify reputation
        user = feedback.answer.user
        delta = 1 if feedback.value is True else -1
        user.reputation += delta
        db.session.add(user)
        # Create notification
        notification = Notification(user_id=feedback.answer.user_id,
                                    url='/questions/%s' % feedback.answer.question_id,
                                    notification_type=Constants.NOTIFICATION_ANSWER_FEEDBACK,
                                    msg_context=json.dumps({
                                        'user_name': feedback.user.name if feedback.user.name else 'User %s' % feedback.user_id,
                                        'question_id': feedback.answer.question.id,
                                        'question_body': feedback.answer.question.body,
                                        'answer_id': feedback.answer.id,
                                        'answer_body': feedback.answer.body,
                                        'feedback_value': feedback.value,
                                        'user_action': string_templates.USER_ACTION_LIKED if feedback.value else string_templates.USER_ACTION_DISLIKED}))
        db.session.add(notification)
        db.session.commit()
        Notification.post_create(notification)
Esempio n. 4
0
def change_temperature_sp(way):
    if way == 'increase':
        Flow.increase_temperature_setpoint(0.5)
    elif way == 'decrease':
        Flow.decrease_temperature_setpoint(0.5)
    else:
        return ('Invalid way of temperature change', 400)
    new_temp_sp_val = Flow.new_temperature_setpoint
    print('new_temp_sp_val: ', new_temp_sp_val)
    socketio.emit('new_temp_sp_val', {'new_temp_sp_val': new_temp_sp_val})
Esempio n. 5
0
def notify_clients_on_message(message):
    for user in models.User.query.filter(models.User.id != current_user.id).all():
        distance = calculate_distance_between_users(current_user, user)
        if distance < Constants.DEFAULT_MESSAGE_DISTANCE:
            socketio.emit(
                "message",
                {
                    "user": {"id": message.user.id},
                    "message": {"body": message.body, "render": message.render()},
                    "distance": distance,
                },
            )
            send_gcm_notification(user, message)
Esempio n. 6
0
    def post_create(cls, result, *args, **kwargs):
        from util.common import send_gcm_notification

        if type(result) is dict:
            notification_id = result.get('id')
            notification = Notification.query.filter_by(id=notification_id).first()
        else:
            notification = result
        result_emit = {
            'render': notification.render(),
            'unread': notification.user.unread_notifications()
        }
        socketio.emit('notify', result_emit, room='user-%s' % notification.user_id)
        send_gcm_notification(notification)
Esempio n. 7
0
 def post_create(cls, result, *args, **kwargs):
     if type(result) is dict:
         question_id = result.get('id')
         question = Question.query.filter_by(id=question_id).first()
     else:
         question = result
     result_emit = {
         'channel_id': question.channel_id,
         'render': question.render()
     }
     socketio.emit('asks', result_emit)
     # create notification to register if first question and not registered
     user = question.user
     if not user.email and len(user.questions.all()) == 1:
         notification = Notification(message=string_templates.NOTIFICATION_REGISTER,
                             url=url_for('client.read_notification', next='/register'), user=user)
         db.session.add(notification)
         db.session.commit()
Esempio n. 8
0
def remove_ghost_sessions():
    cur_age = sys.maxsize
    ghost_start_time = time.time() - SERVER_START_TIME
    while cur_age > TIMEOUT_AGE and not lobby_clients.empty():
        client_entered_time, client = lobby_clients.get()

        client_age = ghost_start_time - client_entered_time

        if client_age <= TIMEOUT_AGE:
            # If hasn't been waiting long, put it back and break
            lobby_clients.put((client_entered_time, client))
        else:
            lobby_clients_active[client.sid] = False

            socketio.emit('reset', room=client.sid)
            logger.debug('marked inactive client ' + str(client) + '; waited for ' + str(client_age) + ' s')
            db.write_connection_event(client.sid, "Removed Ghost Session")

        cur_age = client_age
def background_thread():
    serial = Arduino('/dev/ttyACM0', 9600)

    temp = DataType.get_or_create('Temperatura', 'float')
    hume = DataType.get_or_create('Humedad', 'int')
    pre = DataType.get_or_create('Presion', 'int')

    while True:
        data = serial.readline().strip()
        tm = datetime.now()
        if (data and data != 'fail'):
            data = data.split(',')
            captura = {'time': tm, 'temperatura': data[0], 'humedad': data[1],
                            'presion': data[2]}
            socketio.emit('EMA data', captura, namespace='/test')

            temp.data.append(Data(timestamp=tm, value=data[0]))
            hume.data.append(Data(timestamp=tm, value=data[1]))
            pre.data.append(Data(timestamp=tm, value=data[2]))
            temp.save()
            hume.save()
            pre.save()

        time.sleep(2)
Esempio n. 10
0
    def post_create(cls, result, *args, **kwargs):
        from util.common import get_user
        user = get_user()

        if type(result) is dict:
            answer_id = result.get('id')
            answer = cls.query.filter_by(id=answer_id).first()
        else:
            answer = result
        result_emit = {
            'user_id': answer.user_id,
            'question_id': answer.question_id,
            'render': answer.render(),
            'render_own_question': answer.render_own_question()
        }
        socketio.emit('answers', result_emit)

        #Subscribe to a question
        if not user == answer.question.user:
            existing_subscription = QuestionSubscription.query.filter_by(user=user,question=answer.question).all()
            if not existing_subscription:
                qs = QuestionSubscription(user=user, question=answer.question)
                db.session.add(qs)
                db.session.commit()
        # Create notification
        if (len(answer.question.body) > 50):
            question = answer.question.body[:50] + "..."
        else:
            question = answer.question.body
        if not answer.user == answer.question.user:
            notification = Notification(user_id=answer.question.user_id,
                                        url='/questions/%s' % answer.question_id,
                                        notification_type=Constants.NOTIFICATION_QUESTION_ANSWER,
                                        msg_context=json.dumps({
                                            'user_id': answer.user.id,
                                            'user_name': answer.user.name or answer.user.id,
                                            'question_id': answer.question.id,
                                            'question_body': question,
                                            'answer_id': answer.id,
                                            'answer_body': answer.body
                                        }))
            db.session.add(notification)
            db.session.commit()
            Notification.post_create(notification)
        else:
            #Notify users who have subscribed to question
            for qs in answer.question.question_subscriptions:
                notification = Notification(user_id=qs.user.id,
                                        url='/questions/%s' % answer.question_id,
                                        notification_type=Constants.NOTIFICATION_QUESTION_ANSWER_BY_OP,
                                        msg_context=json.dumps({
                                            'user_id': answer.user.id,
                                            'user_name': answer.user.name or answer.user.id,
                                            'question_id': answer.question.id,
                                            'question_body': question,
                                            'answer_id': answer.id,
                                            'answer_body': answer.body
                                        }))
                db.session.add(notification)
                db.session.commit()
                Notification.post_create(notification)
Esempio n. 11
0
def temp_humidity2_change(temperature, humidity):
    # if temperature is not None and humidity is not None:
    socketio.emit('temp_humidity2_change', {
        'temperature2': temperature,
        "humidity2": humidity
    })
Esempio n. 12
0
def rain_change(rain):
    socketio.emit('rain_change', {'rain': rain})
Esempio n. 13
0
def battery_change(battery_p, battery_v):
    socketio.emit('battery_change', {
        'battery_p': battery_p,
        'battery_v': battery_v
    })
Esempio n. 14
0
def heater_change(heater):
    socketio.emit('heater_change', {'heater': heater})
Esempio n. 15
0
def uvb_change(uvb):
    socketio.emit('uvb_change', {'uvb': uvb})
Esempio n. 16
0
def lamp_change(lamp):
    socketio.emit('lamp_change', {'lamp': lamp})
Esempio n. 17
0
def match_human_players():
    if lobby_clients.qsize() >= 2:
        try:
            client_1 = lobby_clients.get()
        except queue.Empty as e:
            logger.debug("Couldn't get client 1 in human-human match, " + str(e))
            return

        try:
            client_2 = lobby_clients.get()
        except queue.Empty as e:
            logger.debug("Couldn't get client 2 in human-human match, " + str(e))
            lobby_clients.put(client_1)
            return

        # If one of them isn't there anymore, remove (put the other one back)
        if not (lobby_clients_active[client_1[1].sid] and lobby_clients_active[client_2[1].sid]):
            logger.debug("Pair between " + client_1[1].sid + " and " + client_2[1].sid +
                         " didn't work; removing one or both of them")
            if lobby_clients_active[client_1[1].sid]:
                lobby_clients.put(client_1)
            elif lobby_clients_active[client_2[1].sid]:
                lobby_clients.put(client_2)
            return

        if client_1[1].sid == client_2[1].sid:
            # It is possible they can match with themselves in the case
            # that they time out and restart from the same page. Avoid this
            # by removing a client if it has the same sid.

            # This only happens because the player joins the lobby twice from the
            # same sid (we don't make them reload the page to return to the
            # lobby). lobby_clients_active is updated to True for the second
            # time they join the lobby, so for both clients in the lobby, they
            # are considered active (the only thing different between the two
            # clients is the time they entered, which we don't want to require
            # for lookups in lobby_clients_active). Return the one to the
            # queue that has waited shorter (i.e., the one that just joined).
            lobby_clients.put(client_2)
            return

        client_1_waittime = time.time() - client_1[0] - SERVER_START_TIME
        client_2_waittime = time.time() - client_2[0] - SERVER_START_TIME

        client_1 = client_1[1]
        client_2 = client_2[1]

        lobby_clients_active[client_1.sid] = False
        lobby_clients_active[client_2.sid] = False

        db.write_connection_event(client_1.sid, "Matched With Partner")
        db.write_connection_event(client_2.sid, "Matched With Partner")

        # pair them up
        # guaranteed to be free of collisions and we don't need ordering on
        # game IDs so just use uuid
        game_id = str(uuid.uuid4().hex)
        game_seed = random.randint(0, pow(2, 30))
        print('game seed: ' + str(game_seed))
        logger.debug('game seed: ' + str(game_seed))

        num_cards = 21

        character_1 = "Human" if game_seed % 2 == 0 else "Agent"
        character_2 = "Agent" if character_1 == "Human" else "Human"
        if character_1 == "Human":
            game = GameData(game_seed,
                            game_id,
                            num_cards,
                            human=client_1,
                            agent=client_2,
                            using_agent=False)
        else:
            game = GameData(game_seed,
                            game_id,
                            num_cards,
                            human=client_2,
                            agent=client_1,
                            using_agent=False)
        live_games[game_id] = game
        logger.debug("starting game #" + str(game_id) + " with seed " + str(game_seed) + " and worker ids "
                     + client_1.worker_id + " / " + client_2.worker_id)
        logger.debug("client 1 (" + str(client_1) + " waited for " + str(client_1_waittime) + " s")
        logger.debug("client 2 (" + str(client_2) + " waited for " + str(client_2_waittime) + " s")

        # Initialize the game for both players, and also say that the lobby
        # is ready (players matched) -- this will play the audio reminder

        # For now, each player is in a room corresponding to their sid.
        # But later they will go into a room corresponding to the game, so
        # movement communication is easier.
        socketio.emit('initGame',
                      {'character': character_1,
                       'gameId': game_id,
                       'seed': game_seed,
                       'num_cards': num_cards},
                      room=client_1.sid)
        socketio.emit('lobbyReady',
                      room=client_1.sid)

        socketio.emit('initGame',
                      {'character': character_2,
                       'gameId': game_id,
                       'seed': game_seed,
                       'num_cards': num_cards},
                      room=client_2.sid)
        socketio.emit('lobbyReady',
                      room=client_2.sid)

        db.write_game_start(game)

        # Switch the mode
        if MATCH_MODE == MatchMode.HUMAN_AND_AGENT:
            CURRENT_MATCH_MODE.use_human = False
            logger.debug('Switching to matching with human: ' + str(CURRENT_MATCH_MODE.use_human))
Esempio n. 18
0
def notify_clients_on_location_change():
    for user in models.User.query.filter(models.User.id != current_user.id).all():
        distance = calculate_distance_between_users(current_user, user)
        if distance < Constants.DEFAULT_MESSAGE_DISTANCE:
            socketio.emit("DST", {"user": {"id": user.id}, "distance": distance}, room="user-%s" % user.id)
Esempio n. 19
0
def door_change(door):
    socketio.emit('door_change', {'door': door})
Esempio n. 20
0
def match_human_with_agent():
    # Don't allow more than N concurrent games
    if len(live_games) >= 30:
        if lobby_clients.qsize() > LOGGED_OVER_CAPACITY.num_connected:
            logger.debug("New maximum connections reached: %r" % lobby_clients.qsize())
            LOGGED_OVER_CAPACITY.num_connected = lobby_clients.qsize()
        elif lobby_clients.qsize() < LOGGED_OVER_CAPACITY.num_connected:
            logger.debug("Number of connections lowered: %r" % lobby_clients.qsize())
            LOGGED_OVER_CAPACITY.num_connected = lobby_clients.qsize()

        return

    if lobby_clients.qsize() >= 1 and agent_clients.qsize() >= 1:
        try:
            human_client = lobby_clients.get()
        except queue.Empty as e:
            logger.debug("Couldn't get human in human-agent match, " + str(e))
            return

        try:
            agent_client = agent_clients.get()
        except queue.Empty as e:
            logger.debug("Couldn't get agent in human-agent match, " + str(e))
            lobby_clients.put(human_client)
            return

        # If one of them isn't there anymore, remove (put the other one back)
        if not (lobby_clients_active[human_client[1].sid] and agent_clients_active[agent_client[1].sid]):
            logger.debug("Pair between " + human_client[1].sid + " and " + agent_client[1].sid +
                         " didn't work; removing one or both of them")
            if lobby_clients_active[human_client[1].sid]:
                lobby_clients.put(human_client)
            elif agent_clients_active[agent_client[1].sid]:
                agent_clients.put(agent_client)
            return

        if human_client[1].sid == agent_client[1].sid:
            raise ValueError('Agent and human client sid should never be the same!' + str(human_client[1].sid))

        client_1_waittime = time.time() - human_client[0] - SERVER_START_TIME
        client_2_waittime = time.time() - agent_client[0] - SERVER_START_TIME

        human_client = human_client[1]
        agent_client = agent_client[1]

        lobby_clients_active[human_client.sid] = False
        agent_clients_active[agent_client.sid] = False

        db.write_connection_event(human_client.sid, "Matched With Partner")
        db.write_connection_event(agent_client.sid, "Matched With Partner")

        # pair them up
        # guaranteed to be free of collisions and we don't need ordering on
        # game IDs so just use uuid
        game_id = str(uuid.uuid4().hex)
        game_seed = random.randint(0, pow(2, 30))
        num_cards = 21

        game = GameData(game_seed,
                        game_id,
                        num_cards,
                        human=human_client,
                        agent=agent_client,
                        using_agent=True)
        live_games[game_id] = game
        logger.debug("starting game #" + str(game_id) + " with seed " + str(game_seed) + " and worker ids "
                     + human_client.worker_id + " / " + agent_client.worker_id)
        logger.debug("client 1 (" + str(human_client) + " waited for " + str(client_1_waittime) + " s")
        logger.debug("client 2 (" + str(agent_client) + " waited for " + str(client_2_waittime) + " s")

        # Initialize the game for both players, and also say that the lobby
        # is ready (players matched) -- this will play the audio reminder

        # For now, each player is in a room corresponding to their sid.
        # But later they will go into a room corresponding to the game, so
        # movement communication is easier.
        socketio.emit('initGame',
                      {'character': 'Human',
                       'gameId': game_id,
                       'seed': game_seed,
                       'num_cards': num_cards},
                      room=human_client.sid)
        socketio.emit('lobbyReady',
                      room=human_client.sid)

        socketio.emit('initGame',
                      {'character': 'Agent',
                       'gameId': game_id,
                       'seed': game_seed,
                       'num_cards': num_cards},
                      room=agent_client.sid)
        socketio.emit('lobbyReady',
                      room=agent_client.sid)

        db.write_game_start(game)

        # Switch the mode
        if MATCH_MODE == MatchMode.HUMAN_AND_AGENT:
            CURRENT_MATCH_MODE.use_human = True
            logger.debug('Switching to matching with human: ' + str(CURRENT_MATCH_MODE.use_human))