def _receive_packet(self): while True: robots_list = db.table('robots').all() for id in range(6): updated_robot = { "info": { "id": id, "name": "Robot {}".format(id) }, "supply": { "batt": random.random() * 100, "voltage": random.random() * 16, "current": random.random() * 5, "power": random.random() }, "com": { "time_since_last_packet": 2 } } if any(robot['info']['name'] == updated_robot['info']['name'] for robot in robots_list): sio.emit('robots_update', updated_robot) with transaction(db.table('robots')) as robots: robots.update( updated_robot, where('info').name == updated_robot['info'] ['name']) else: sio.emit('robots_insert', updated_robot) with transaction(db.table('robots')) as robots: robots.insert(updated_robot) time.sleep(1)
def update_contacts(bx, sid): data = [b.bid for b in Box.query.filter_by(user_id=bx.user_id) if b.bid != bx.bid] data_dict = {} for i in range(len(data)): data_dict['contact{}'.format(i + 1)] = data[i] sio.emit('contact info', data=data_dict, room=sid)
def send_message(message, recipient): usr = current_user.social_id if current_user.is_mentor: convo = Conversation.query.filter_by(mentor=usr, mentee=recipient).first() else: convo = Conversation.query.filter_by(mentee=usr, mentor=recipient).first() if convo is None: print('conversation not found') return timestamp = datetime.now() other_nick = User.query.filter_by(social_id=recipient).first() other_nick = other_nick.social_id print('message sent by {} to {} at {}: {}'.format(current_user.social_id, other_nick, timestamp, message)) message = Message(sent=timestamp, owner=usr, recipient=recipient, contents=message) db.session.add(message) db.session.commit() sio.emit('message', { 'sent': str(timestamp), 'owner': usr, 'recipient': recipient, 'contents': message.contents }, room=recipient)
def online(x): global thread with thread_lock: if thread is None: thread = sio.start_background_task(target=background_thread) user = db['users'].find_one({'token': x['token']}) if user: # Добавление онлайн заданий if not user['online']: db_condition = { 'id': { '$in': user['tasks'] }, } tasks = [ i for i in db['tasks'].find(db_condition, {'_id': False}) if i ] for i in range(len(tasks)): tasks[i]['image'] = get_preview('tasks', tasks[i]['id']) sio.emit('tasks_add', tasks, namespace='/main') # user['online'] = True user['last'] = time.time() db['users'].save(user)
def message(mes): space = db['space'].find_one({'id': mes['space']}) timestamp = time.time() message_id = next_id('space') space['messages'].append({ 'id': message_id, 'user': mes['token'], 'cont': mes['cont'], 'time': timestamp, }) db['space'].save(space) # Отправить сообщение sio.emit('message_get', { 'space': mes['space'], 'id': message_id, 'user': mes['token'], 'cont': mes['cont'], 'time': timestamp, }, namespace='/main')
def send_audio(data): dest = int(data['destID']) if str(data['type']) == 'audio': if dest in list(sid_list.keys()): print('telling client there be data') sio.emit('return message', data=data, room=sid_list[dest]) else: print('aaaaaaa')
def on_step(self, sid, data): member = models.Member.query.filter_by(game_id=data['gameId'], user_id=data['userId']).first() step = models.Step(step_number=data['stepNumber'], x_coordinate=data['x'], y_coordinate=data['y'], value=data['currentSymbol'], member_id=member.id) step.save() response = get_game_result(step, member) sio.emit('step_result', response, namespace='/hot_seat', room=sid)
def emit(self, event, data): """Emit or send message to user via sockets""" if not self.to_emit: return try: message = f" with the message: {data['message']}" if "message" in data else "." logger.debug( f"[{self.context.sid}][Execution] Emitting '{event}'{message}") sio.emit(event, data, room=str(self.context.sid)) except RuntimeError as e: logger.debug( f"[{self.context.sid}][Execution] RuntimeError: {str(e)}") if not str(e).startswith("Working outside of request context."): raise e
def message(data): message = data.get("message") sid = data.get("sid") isUnconstrained = data.get("isUnconstrained") client = socket_clients.get(sid) if client is None or message is None: return voice_or_text = "voice" if data.get("speak", False) else "text" dm = client.dm if isinstance(dm, UserStudyDialogManager) or isinstance( dm, UserStudyAdvancedDialogManager): logger.info( f"[{dm.sid}][{dm.stage},{dm.part}][Message]({voice_or_text}) {message}" ) logger.debug( f"[{dm.sid}][{dm.stage},{dm.part}][State] {dm.context.state}") else: logger.info(f"[{dm.sid}][Message] {message}") logger.debug(f"[{dm.sid}][State] {dm.context.state}") res = dm.handle_message(message, isUnconstrained) if (res): # If there is response message, log and send to client dm.context.add_message(res) state = dm.context.state response = { "message": res, "state": dm.context.state, "speak": data.get("speak", False), "isUnconstrained": data.get("isUnconstrained") } if isinstance(dm, UserStudyDialogManager) or isinstance( dm, UserStudyAdvancedDialogManager): logger.info(f"[{dm.sid}][{dm.stage},{dm.part}][Response] {res}") logger.debug( f"[{dm.sid}][{dm.stage},{dm.part}][State] {dm.context.state}") else: logger.info(f"[{dm.sid}][Response] {res}") logger.debug(f"[{dm.sid}][State] {dm.context.state}") sio.emit("response", response, room=str(sid))
def emit_checked_in(openid, meeting): user = wx.user.get(openid) sio.emit('check-in', user) for user in meeting['attendee']: if user['openid'] != openid: continue checkin_time = dt.datetime.now().timestamp() print('--------') print(checkin_time) print(meeting['timestamp']) if checkin_time > meeting['timestamp']: chidao = (checkin_time - meeting['timestamp']) / 60 p_obj = mongo.db.punishments.find_one({ 'punishment_id': meeting['punishment_id'] }) if p_obj['ptype'] == 1 or p_obj['ptype'] == '1': every, kuai = p_obj['content'] num = floor(chidao / float(every)) * float(kuai) punishment = '%f块钱' % (num) elif p_obj['ptype'] == 2 or p_obj['ptype'] == '2': every, amount, unit = p_obj['content'] num = floor(chidao / float(every)) * float(amount) punishment = '%f%s' % (num, unit) else: print(p_obj['content']) text, = p_obj['content'] punishment = text s = '你已迟到%d分钟, 惩罚是%s' % ( chidao, punishment ) # wx.message.send_text(openid, s) return [checkin_time, s] else: # wx.message.send_text(openid, '签到成功') return [checkin_time, '没有迟到,不用惩罚~']
def runHWCode(): logger.debug("running rfid/servo code") allowed_rfid_ids = [512096389334, 588475052768] sio.emit("card-read", {"locked": servo.locked}) servo.lock() try: while True: read_id = rfid_reader.read_card_id() logger.debug(f"Read id {read_id}, {read_id in allowed_rfid_ids}") if read_id in allowed_rfid_ids: logger.debug("Access allowed!") sio.emit("card-read", {"locked": not servo.locked}) servo.unlock() if servo.locked else servo.lock() else: logger.debug("Access denied!") beep(0.5) sleep(2) except KeyboardInterrupt: logger.debug("CTRL-C: Terminating program.") finally: rfid_reader.clean_pin()
def trends(x): # global thread # with thread_lock: # if thread is None: # thread = sio.start_background_task(target=background_thread) sid = request.sid timestamp = time.time() # Отслеживание req = { 'time': timestamp, 'user': x['token'], 'method': 'trends', 'params': { 'search': x['search'] }, } # print('TREND', '1', x['search']) messages = search_global(x['search'], 100) print('TREND', '2') posts = get_styled(messages) print('TREND', '3') graph = timeline(messages) print('TREND', '4') # Ответ res = { 'posts': posts, 'graph': graph, } sio.emit('trends', res, room=sid, namespace='/main')
def background_thread(): while True: timestamp = time.time() # Вышел из онлайна db_condition = { 'last': { '$lt': timestamp - 10 }, 'online': True, } for user in db['users'].find(db_condition): user['online'] = False db['users'].save(user) # Удаление онлайн заданий db_condition = { 'id': { '$in': user['tasks'] }, } db_filter = { '_id': False, 'id': True, } tasks = [i for i in db['tasks'].find(db_condition, db_filter) if i] sio.emit('tasks_del', tasks, namespace='/main') # time.sleep(5)
def create_or_join(sid, data): sio.enter_room(sid, data) try: connected_particpants[data].append(sid) except KeyError: connected_particpants[data] = [sid] numClients = len(connected_particpants[data]) if numClients == 1: sio.emit('created', data) elif numClients == 2: sio.emit('joined') sio.emit('join') print (sid, data, len(connected_particpants[data]))
def pair_mentor(): if current_user.is_mentor: return jsonify({"error": "Only mentees can request pairing."}) oldCon = Conversation.query.filter_by(mentee=current_user.social_id).first() if oldCon is not None: # trying to get rid of old mentor bad = oldCon.mentor bl = Blacklist(mentee=current_user.social_id, mentor=bad) db.session.add(bl) Conversation.query.filter_by(mentee=current_user.social_id).delete() db.session.commit() sio.emit('reload', room=bad) current_traits = { "agreeableness": current_user.agreeableness, "conscientiousness": current_user.conscientiousness, "emotional_range": current_user.emotional_range, "extraversion": current_user.extraversion, "openness": current_user.openness } bestMentor = None bestScore = 9999999999 blacklisted = set(map(lambda x: x.mentor, Blacklist.query.filter_by(mentee=current_user.social_id).all())) for user in User.query.filter_by(is_mentor=True).all(): if user.social_id in blacklisted: continue involved_cons = Conversation.findWith(user.social_id) if len(involved_cons) >= user.max_mentees: continue invalid = True for con in involved_cons: if con.mentee == current_user.social_id: # they're already paired break else: invalid = False # stupid way to invert for loop else if invalid: continue these_traits = { "agreeableness": user.agreeableness, "conscientiousness": user.conscientiousness, "emotional_range": user.emotional_range, "extraversion": user.extraversion, "openness": user.openness } score = PersonalityService.get_compatibility_score(current_traits, these_traits) if score < bestScore: bestMentor = user bestScore = score if bestMentor is None: return jsonify({"error": "There are no mentors currently available."}) convo = Conversation(mentee=current_user.social_id, mentor=bestMentor.social_id) db.session.add(convo) db.session.commit() sio.emit('reload', room=bestMentor.social_id) return jsonify({"success": True})
def handle_join_room(data): join_room(data['room']) sio.emit(data, room=data['room'])
def clientToServer(sid, data): sio.emit("serverToClient", data) print("message: ", data)
def emit_message(gid, msg, data={}, players=[1, 2, 3, 4, 5]): data['emit_msg'] = msg data['socketio_players'] = players sio.emit(msg, data, room='game' + str(gid))
def handle_message(msg): # send to all clients print("connected") sio.emit('message', msg)
def messgage(sid, data): sio.emit('message', data=data)
def change_color(msg): sio.emit('data', msg, namespace='/flask')
def train(data): sid = data.get("sid") intents = data.get("intents") trainingData = data.get("trainingData") # First, add all intents and respective entities to the context. client = socket_clients.get(sid) if client is None: return dm = client.dm add_intents_and_entities(dm.context, intents, trainingData) logger.debug( f"finished adding all intents and entities at port {dm.context.rasa_port}" ) # Then, train the NLU model using this new data. training_data = format_training_data(intents, trainingData) res = None try: rasa_url = "http://rasa" + dm.context.rasa_port + ":" + dm.context.rasa_port + "/model/train" res = requests.post(rasa_url, json=training_data) except requests.ConnectionError as e: logger.info("Cannot connect to Rasa server.") return None # If no response from Rasa NLU server, return None if (res is None or res.status_code != 200): logger.info("No response from the Rasa server.") return None logger.debug("Finished training Rasa.") # Replace the currently trained model model_file = res.headers["filename"] model_file_absolute = "/app/models/" + model_file request = {"model_file": model_file_absolute} payload = json.dumps(request) replace_res = None try: rasa_url = "http://rasa" + dm.context.rasa_port + ":" + dm.context.rasa_port + "/model" replace_res = requests.put(rasa_url, data=payload) except requests.ConnectionError as e: logger.info( f"Rasa server at port {dm.context.rasa_port} is restarting.") return None if (replace_res is None or replace_res.status_code != 204): logger.info( "No response from the Rasa server when replacing the model.") return None logger.debug( f"Finished updating the trained model of Rasa at port {dm.context.rasa_port}." ) res = dm.handle_train(intents) # If there is response message, log and send to client dm.context.add_message(res) response = { "message": res, } sio.emit("trained", response, room=str(sid))
def join(data): """Connect to the backend server of Convo""" sid = data.get("sid") if sid is None: logger.info("Client connected without an SID.") return stage = data.get("stage", "sandbox") part = data.get("part", "sandbox") port = data.get("port") intents = data.get("intents") phrases = data.get("phrases") sid_to_rasa_port[sid] = port socket_sessions[request.sid] = (sid, stage, part, port) logger.info(f"[{sid}][{stage},{part},{port}] Client connected.") logger.info(f"Current connected SIDs: {socket_sessions}") # Join room with the SID as the name such that each "room" only contains a single user with the corresponding SID join_room(str(sid)) # Grab client associated with SID, if not exist, create one client = socket_clients.get(sid, UserStudyClient(sid)) get_or_create_user(client) socket_clients[sid] = client if stage in ["practice", "novice", "advanced" ] and part in ["voice", "text", "voice-text"]: # If (stage, part) corresponds to stages/parts of user study, create special dialog manaager scenario = client.inputs[stage][part] if stage == "practice": client.dm = UserStudyDialogManager(sid, stage, part, scenario) elif stage == "novice": client.dm = UserStudyDialogManager(sid, stage, part, scenario[1]) sio.emit("noviceInstructions", {"sounds": scenario[0]}, room=str(sid)) logger.info(f"[{sid}][{stage},{part}] Sounds: {scenario[0]}") logger.info( f"[{sid}][{stage},{part}] Created dialog manager for user studies." ) else: client.dm = UserStudyAdvancedDialogManager( sid, part, scenario[1], advanced_scenario_check) logger.info(f"[{sid}][{stage},{part}] Sounds: {scenario[0]}") logger.info( f"[{sid}][{stage},{part}] Iterations: {len(scenario[1])}") logger.info(f"[{sid}][{stage},{part}] Inputs: {scenario[1]}") logger.debug( f"[{sid}][{stage},{part}] Created dialog manager for user studies." ) sio.emit("advancedInstructions", { "sounds": scenario[0], "iters": len(scenario[1]) }, room=str(sid)) else: # Default client and dialog manager client.dm = DialogManager(sid, port, get_procedures(sid)) logger.debug(f"[{sid}] Created default dialog manager.") if intents and phrases: add_intents_and_entities(client.dm.context, intents, phrases) logger.debug( f"[{sid}] Finish adding intents {intents} to context.") sio.emit("joined", sid, room=str(sid)) intro = ''' Hi, I'm Convo! What would you like to do? To get started, you can create a procedure by saying "Create a procedure". If you want to run a procedure, say "Run" and the name of the procedure. ''' response = { "message": intro, "state": client.dm.context.state, "speak": False } sio.emit("response", response, room=str(sid))
def handleMessage(data): print(data) sio.emit('receive_message', data, room=data['room']) return None
def candidate1(mes): sio.emit('candidate1', mes, namespace='/main')
def description1(mes): sio.emit('description1', mes, namespace='/main')
def ping(data): print('Ping received : ', data) sio.emit('ping', data)