def save_message(data, methods=['GET', 'POST']): recipients = data['recipients'] message = data['message'] for mobile_id in recipients: current_date_time = time.strftime('%Y-%m-%d %H:%M:%S') insert_message = SmsOutboxUsers(ts_written=current_date_time, sms_msg=message) DB.session.add(insert_message) DB.session.flush() latest_outbox_id = insert_message.outbox_id returned_gsm_id = get_gsm_id(mobile_id) insert_message_status = SmsOutboxUserStatus( outbox_id=latest_outbox_id, mobile_id=mobile_id, ts_sent=current_date_time, send_status=0, event_id_reference=0, gsm_id=int(returned_gsm_id['gsm_id'])) DB.session.add(insert_message_status) DB.session.commit() SOCKETIO.emit('dataResponse', "success", callback='successfully inserted to database')
def get_routine_sites(): get_sites = get_sites_data() schema = SitesSchema(many=True).dump(get_sites).data day = calendar.day_name[CURRENT_DATE.weekday()] wet_season = [[1, 2, 6, 7, 8, 9, 10, 11, 12], [5, 6, 7, 8, 9, 10]] dry_season = [[3, 4, 5], [1, 2, 3, 4, 11, 12]] routine_sites = [] if (day == "Friday" or day == "Tuesday"): print(day) for sites in schema: season = int(sites['season']) - 1 if sites['season'] in wet_season[season]: routine_sites.append(sites['site_code']) elif day == "Wednesday": print(day) for sites in schema: season = int(sites['season']) - 1 if sites['season'] in dry_season[season]: routine_sites.append(sites['site_code']) else: routine_sites = [] # note the you need to pass the routine and reminder template SOCKETIO.emit('routineSitesResponse', {"routine_sites": routine_sites}, callback='successfully fetched data') return jsonify({"routine_sites": routine_sites})
def wrap_update_all_contacts(): sid = request.sid global CONTACTS_USERS CONTACTS_USERS = get_contacts(orientation="users") SOCKETIO.emit("receive_all_contacts", CONTACTS_USERS, room=sid, namespace="/communications")
def wrap_get_search_results(payload): print(f"====> Message received", payload) sid = request.sid result = get_search_results(payload) SOCKETIO.emit("receive_search_results", result, room=sid, namespace="/communications")
def sample_websocket(interval): print("===> One client connected by ", interval) SOCKETIO.emit("receive_generated_alerts", "Connected", callback="successfully accessed", namespace="/test") SOCKETIO.emit("sample_2", "Resent connected successful", callback="successfully accessed", broadcast=True)
def emit_data(keyword, sid=None): data_to_emit = None if keyword == "receive_generated_alerts": data_to_emit = retrieve_data_from_memcache("GENERATED_ALERTS") elif keyword == "receive_candidate_alerts": data_to_emit = retrieve_data_from_memcache("CANDIDATE_ALERTS") elif keyword == "receive_alerts_from_db": data_to_emit = retrieve_data_from_memcache("ALERTS_FROM_DB") elif keyword == "receive_issues_and_reminders": data_to_emit = retrieve_data_from_memcache("ISSUES_AND_REMINDERS") elif keyword == "receive_rainfall_data": data_to_emit = retrieve_data_from_memcache("RAINFALL_DATA") # var_checker("data_list", data_list, True) if sid: SOCKETIO.emit(keyword, data_to_emit, to=sid, namespace="/monitoring") else: SOCKETIO.emit(keyword, data_to_emit, namespace="/monitoring")
def join_mobile_id_room(mobile_id): """ mobile_id (str): variable is integer from origin but converted to string on websocket """ mobile_id = int(mobile_id) sid = request.sid global ROOM_MOBILE_IDS room_mobile_ids = ROOM_MOBILE_IDS room_users = [] if mobile_id in room_mobile_ids.keys(): room_users = room_mobile_ids[mobile_id]["users"] room_users.append(sid) else: mobile_details = get_user_mobile_details(mobile_id) msgs = get_latest_messages(mobile_id) msgs_schema = get_messages_schema_dict(msgs) message_row = { "mobile_details": mobile_details, "messages": msgs_schema } room_mobile_ids[mobile_id] = {"users": [sid], "details": message_row} ROOM_MOBILE_IDS = room_mobile_ids join_room(mobile_id) SOCKETIO.emit("receive_mobile_id_room_update", room_mobile_ids[mobile_id]["details"], room=sid, namespace="/communications") print(f"=====> {sid} JOINED ROOM", mobile_id) print(f"=====> Available rooms", room_mobile_ids.keys())
def connect(): sid = request.sid CLIENTS.append(sid) print("Connected user: "******"Current connected clients: {CLIENTS}") SOCKETIO.emit("receive_latest_messages", MESSAGES, room=sid, namespace="/communications") SOCKETIO.emit("receive_all_contacts", CONTACTS_USERS, room=sid, namespace="/communications") SOCKETIO.emit("receive_all_mobile_numbers", CONTACTS_MOBILE, room=sid, namespace="/communications")
from argparse import ArgumentParser from gevent import monkey monkey.patch_all() from connection import create_app, SOCKETIO PARSER = ArgumentParser(description="Run Dynaslope 3.0 Server") PARSER.add_argument("-sm", "--skip_memcache", help="skip memcache initialization", action="store_true") PARSER.add_argument("-sw", "--skip_websocket", help="skip running of websocket background task", action="store_true") ARGS = PARSER.parse_args() CONFIG_NAME = os.getenv("FLASK_CONFIG") APP = create_app(CONFIG_NAME, skip_memcache=ARGS.skip_memcache, skip_websocket=ARGS.skip_websocket) if __name__ == "__main__": print("Flask server is now running...") SOCKETIO.run(APP, host='192.168.150.159', port=5000, debug=True, use_reloader=False)
def monitoring_background_task(): generated_alerts = [] while True: try: if not generated_alerts: generated_alerts = generate_alerts() set_data_to_memcache(name="GENERATED_ALERTS", data=generated_alerts) alerts_from_db = wrap_get_ongoing_extended_overdue_events() set_data_to_memcache(name="ALERTS_FROM_DB", data=alerts_from_db) candidate_alerts = candidate_alerts_generator.main( generated_alerts_list=generated_alerts, db_alerts_dict=alerts_from_db) set_data_to_memcache(name="CANDIDATE_ALERTS", data=candidate_alerts) set_data_to_memcache(name="ISSUES_AND_REMINDERS", data=wrap_get_issue_reminder()) rainfall_data = execute_get_all_site_rainfall_data() set_data_to_memcache(name="RAINFALL_DATA", data=rainfall_data) emit_data("receive_generated_alerts") emit_data("receive_alerts_from_db") emit_data("receive_candidate_alerts") emit_data("receive_issues_and_reminders") emit_data("receive_rainfall_data") elif datetime.now().minute % 5 == 1: print() system_time = datetime.strftime( datetime.now(), "%Y-%m-%d %H:%M:%S") print(f"{system_time} | Websocket running...") try: generated_alerts = generate_alerts() set_data_to_memcache( name="GENERATED_ALERTS", data=generated_alerts) alerts_from_db = wrap_get_ongoing_extended_overdue_events() set_data_to_memcache( name="ALERTS_FROM_DB", data=alerts_from_db) set_data_to_memcache(name="CANDIDATE_ALERTS", data=candidate_alerts_generator.main( generated_alerts_list=generated_alerts, db_alerts_dict=alerts_from_db) ) print(f"{system_time} | Done processing Candidate Alerts.") except Exception as err: print(err) raise emit_data("receive_generated_alerts") emit_data("receive_candidate_alerts") emit_data("receive_alerts_from_db") # Update rainfall summary data elif datetime.now().minute in [15, 45]: rainfall_data = execute_get_all_site_rainfall_data() set_data_to_memcache(name="RAINFALL_DATA", data=rainfall_data) emit_data("receive_rainfall_data") except Exception as err: print("") print("Monitoring Thread Exception") var_checker("Exception Detail", err, True) print(traceback.format_exc()) DB.session.rollback() SOCKETIO.sleep(60) # Every 60 seconds in production stage
def communication_background_task(): global MESSAGES global ROOM_MOBILE_IDS inbox_messages_arr = MESSAGES["inbox"] is_first_run = False ground_meas_run = False while True: try: is_first_run, ground_meas_run = process_ground_measurement_reminder( is_first_run, ground_meas_run) updates = get_sms_user_updates() update_process_start = datetime.now() for row in updates: query_start = datetime.now() mobile_id = row.mobile_id update_source = row.update_source inbox_index = next( (index for (index, row_arr) in enumerate(inbox_messages_arr) if row_arr["mobile_details"]["mobile_id"] == mobile_id), -1) if update_source == "inbox": msgs = get_latest_messages(mobile_id) msgs_schema = get_messages_schema_dict(msgs) if inbox_index > -1: message_row = inbox_messages_arr[inbox_index] del inbox_messages_arr[inbox_index] else: message_row = { "mobile_details": get_user_mobile_details(mobile_id) } message_row["messages"] = msgs_schema inbox_messages_arr.insert(0, message_row) MESSAGES["inbox"] = inbox_messages_arr elif update_source == "outbox": if inbox_index > -1: msgs = get_latest_messages(mobile_id) msgs_schema = get_messages_schema_dict(msgs) MESSAGES["inbox"][inbox_index][ "messages"] = msgs_schema unsent_messages_arr = get_unsent_messages(duration=1) unsent_messages = format_unsent_messages( unsent_messages_arr) MESSAGES["unsent"] = unsent_messages # CHECK FOR UPDATES IN MOBILE ID ROOM if mobile_id in ROOM_MOBILE_IDS.keys(): if inbox_index > -1: msgs_schema = MESSAGES["inbox"][inbox_index][ "messages"] else: msgs = get_latest_messages(mobile_id) msgs_schema = get_messages_schema_dict(msgs) ROOM_MOBILE_IDS[mobile_id]["details"][ "messages"] = msgs_schema SOCKETIO.emit("receive_mobile_id_room_update", ROOM_MOBILE_IDS[mobile_id]["details"], room=mobile_id, namespace="/communications") elif update_source == "blocked_numbers": if inbox_index > -1: del MESSAGES["inbox"][inbox_index] elif update_source == "inbox_tag": if inbox_index > -1: msgs = get_latest_messages(mobile_id) msgs_schema = get_messages_schema_dict(msgs) inbox_messages_arr[inbox_index][ "messages"] = msgs_schema query_end = datetime.now() delete_sms_user_update(row) emit_data("receive_latest_messages") print("") print("GET MESSAGE ON MEMCACHE (WS)", (query_end - query_start).total_seconds()) print("") update_process_end = datetime.now() if updates: print("") print(f"COMMS UPDATE PROCESS LOOP (WS) {len(updates)} updates", (update_process_end - update_process_start).total_seconds()) print("") except Exception as err: print("") print("Communication Thread Exception") var_checker("Exception Detail", err, True) print(traceback.format_exc()) DB.session.rollback() pass SOCKETIO.sleep(0.5)
def wrap_get_all_mobile_numbers(): sid = request.sid SOCKETIO.emit("receive_all_mobile_numbers", CONTACTS_MOBILE, room=sid, namespace="/communications")
def emit_data(keyword): global MESSAGES data_list = {"receive_latest_messages": MESSAGES} SOCKETIO.emit(keyword, data_list[keyword], namespace="/communications")
def wrap_get_all_contacts(): sid = request.sid SOCKETIO.emit("receive_all_contacts", CONTACTS_USERS, room=sid, namespace="/communications")
def wrap_get_latest_messages(): sid = request.sid SOCKETIO.emit("receive_latest_messages", MESSAGES, room=sid, namespace="/communications")