class Server: def __init__(self, host, port): self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.clients = [] self.accepting = True self.message_manager = MessageManager(self) def connect(self): print('Starting up on %s port %s' % (self.host, self.port)) self.sock.bind((self.host, self.port)) self.sock.listen(1) # Put socket into server mode while self.accepting: client_connected = self.sock.accept() print('Connection from', client_connected) client_identify = client_connected[0].recv( config.IDENTIFY_BUFFER).decode( ) # Isso depois pode virar uma função de autenticação self.clients.append((client_connected, client_identify)) def start_message_manager(self): self.message_manager.start() def close(self): print('Closing server socket') self.accepting = False self.sock.close()
class NodeCore: def __init__(self): self.ip = sys.argv[-2] self.port = int(sys.argv[-1]) self.mm = MessageManager() signal.signal(signal.SIGINT, self.__KeyboardInterruptHandler) self.__wait_access() def __wait_access(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((self.ip, self.port)) s.listen(5) executor = ThreadPoolExecutor(max_workers = 5) while True: sleep(1) print("waiting connection...") conn, addr = s.accept() executor.submit(self.__handle_message, conn) def __handle_message(self, conn): self.mm.parse(conn) def __KeyboardInterruptHandler(self, signal, frame): print("\nCtrl+C!!!") sys.exit(0)
def __init__(self, host, port): self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.clients = [] self.accepting = True self.message_manager = MessageManager(self)
class Server: def __init__(self, host, port): self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.clients = [] self.accepting = True self.message_manager = MessageManager(self) def connect(self): print('Starting up on %s port %s' % (self.host, self.port)) self.sock.bind((self.host, self.port)) self.sock.listen(1) # Put socket into server mode while self.accepting: client_connected = self.sock.accept() print('Connection from', client_connected) client_identify = client_connected[0].recv(config.IDENTIFY_BUFFER).decode() # Isso depois pode virar uma função de autenticação self.clients.append((client_connected, client_identify)) def start_message_manager(self): self.message_manager.start() def close(self): print('Closing server socket') self.accepting = False self.sock.close()
def client_socket(): ip = sys.argv[-2] port = int(sys.argv[-1]) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.3", 11111)) message = make_tx() mm = MessageManager() test_message = mm.build(ip, "TEST", message) s.send(test_message.encode()) s.close()
def __init__(self): self.name = sys.argv[-1] with open("node_json.txt", "r") as f: info = json.loads(f.read()) self.info = info[self.name] self.ip = self.info["My_IP"] self.port = 11111 self.mm = MessageManager() signal.signal(signal.SIGINT, self.__KeyboardInterruptHandler) self.__wait_access()
def __init__(self, host, port, callback): self.host = host self.port = port self.mm = MessageManager() self.callback = callback self.peers = set() # connect to 2 peers # self.peers = [(host, 65001), (host, 65002)] # connect to 3 peers self.peers = [(host, 65001), (host, 65002), (host, 65003)]
def receiving_photo(message): raw = message.photo[-1] file_info = get_file_info_or_error_text(raw) if type(file_info) == str: send_message(message.chat.id, file_info) return delete_trash(message) file = download_file(file_info.file_path) manager = MessageManager(message.chat.id) response = manager.dispatch(message.caption, file, file_info) if not send_message(message.chat.id, response['text'], response['markup']): delete_trash(message)
def _execute_action(self, i, return_results): for i in range(self.messages_number): if self.action == Action.Read: read_message = MessageManager.read_msg(i) return_results.append(read_message) else: if self.messages: MessageManager.write_msg(self.messages[i]) else: self.messages = 'My Message #: ' + str(i + 1) MessageManager.write_msg('My Message #: ' + str(i + 1)) return_results.append(self.messages)
def __init__(self, main_window, port, service_id): super().__init__() self.main_window = main_window #ConnectionManager (create Slots) self.connection_manager = ConnectionManager(port, service_id) self.message_manager = MessageManager(self.connection_manager, service_id) self.message_manager.signal_message_received.connect(self.print_string) self.message_manager.signal_election_responded.connect( self.set_election) self.message_manager.signal_leader_responded.connect( self.leader_has_been_found) self.message_manager.signal_has_message_to_send.connect( self.send_udp_message) self.message_manager.signal_leader_alive.connect(self.set_alive) data = {"port": str(port), "leader": "Null"} jdata = json.dumps(data) self.main_window.set_details(jdata) self.main_window.signal_has_message_to_send.connect( self.send_udp_message) self.main_window.signal_has_multicast_to_send.connect( self.send_multicast_message) self.main_window.signal_start_checking.connect(self.close) self.own_port = port self.service_id = service_id self.leader_ip = None self.leader_port = 0 self.leader_id = " " self.election = True self.leader_alive = False self.iam_leader = False self.control_boolean = False self.alive_checker_thread = AliveChecker(self, self.leader_ip, self.leader_port, self.connection_manager) self.alive_checker_thread.signal_election_is_due.connect( self.do_election) self.message_manager.signal_received_ok.connect(self.receive_ok) self.message_manager.signal_critical_request.connect( self.receive_request) self.worker_controller = WorkerController(1) self.worker_controller.signal_request_critical.connect( self.request_critical) self.worker_controller.signal_send_free_message.connect( self.send_free_message) #do first multicast self.th = th.Thread(target=self.request_group) self.th.start()
def __init__(self) -> None: self._cozmo = cozmo_client.Cozmo() self._queue = SimpleQueue() self._mqtt_client = None if MQTT_BROKER_URL is not None: self._mqtt_client = mqtt_client.MqttClient( MQTT_BROKER_URL, MQTT_BROKER_PORT, MQTT_USERNAME, MQTT_PASSWORD, MQTT_TOPICS, self._on_mqtt_message) self.sdk_conn: CozmoConnection = None self._faces: Dict[Face, datetime] = dict() self._visible_objects: Dict[ObservableObject, datetime] = dict() self._message_manager = MessageManager() self._cozmo_state = CozmoStates.Disconnected
class NodeCore: def __init__(self): self.name = sys.argv[-1] with open("node_json.txt", "r") as f: info = json.loads(f.read()) self.info = info[self.name] self.ip = self.info["My_IP"] self.port = 11111 self.mm = MessageManager() signal.signal(signal.SIGINT, self.__KeyboardInterruptHandler) self.__wait_access() def __wait_access(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((self.ip, self.port)) s.listen(5) executor = ThreadPoolExecutor(max_workers=5) while True: sleep(1) print("waiting connection...") conn, addr = s.accept() executor.submit(self.__handle_message, conn) def broadcast(self, message, sender): for ip in self.info.values(): sleep(1) if (ip != self.ip and ip != sender): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, 11111)) s.send(message.encode()) s.close() else: continue def __handle_message(self, conn): result, sender, msg_type, payload = self.mm.parse(conn) if result == "OK": if msg_type == "TEST": message = self.mm.build(self.ip, MSG_TEST, payload) self.broadcast(message, sender) else: print("ERROR") def __KeyboardInterruptHandler(self, signal, frame): print("\nCtrl+C!!!") sys.exit(0)
def __init__(self, parent, controller): if not controller.token: controller.switch_frame("LoginPage") super().__init__(parent, controller) controller.title("SpaceChat client") # Token shower self.token_label = tk.Label(self, text=self.controller.token) self.token_label.grid(row=1, columnspan=1, sticky=tk.E) # Logout Button self.logout_btn = tk.Button(self, text="Logout", command=self._logout_btn_clicked) self.logout_btn.grid(row=2, columnspan=1) # Incoming message box self.incoming_message_box = tk.Text(self, height=4, width=50) self.incoming_message_box_scrollbar = tk.Scrollbar(self) self.incoming_message_box.grid(row=1, column=2, rowspan=2) self.incoming_message_box_scrollbar.grid(row=1, column=3, rowspan=2, sticky="NSW") self.incoming_message_box_scrollbar.config( command=self.incoming_message_box.yview) self.incoming_message_box.config( yscrollcommand=self.incoming_message_box_scrollbar.set, state="disabled") # prevents user from typing in it # Outgoing message box self.outgoing_message_box = tk.Entry(self, width=50) self.outgoing_message_box.grid(row=3, column=2, rowspan=1) # We want to add a binding just to the message sending box self.outgoing_message_box.bind("<Return>", self._send_message) self.pack() # Set up global keyboard shortcuts # TODO: Test on windows self.add_binding("<Alt-l>", self._logout_btn_clicked) self.add_binding("<Command-l>", self._logout_btn_clicked) # Mac # Connect to the message server! self.msg_manager = MessageManager(self) self.msg_manager.bind_message_handler(self.message_handler) self.add_text_to_incoming("Logged into server!")
def __init__(self, config, loop, working_path): """ Class for managing bot. for instance, connect vc and disconnect, receive message and collect. :param config: configuration for launching bot :param loop: event loop for bot, etc. :param working_path: working directory path(/parent_dir/data/) """ # message manager self.mm = MessageManager(bm=self) # initialize bot self._lb = ListenerBot(token=config.listener_token, mm=self.mm, bm=self, loop=loop, working_path="{0}/..".format(working_path)) _sb_list = list() for _t in config.speaker_token_list: _sb = SpeakerBot(token=_t, bm=self, loop=loop, working_path=working_path) _sb_list.append(_sb) # BotCollector self.bc = BotCollector(self._lb, _sb_list) # Status list self._status_list = list()
def callback_handler(call): user_id = call.message.chat.id message_id = call.message.message_id message_text = call.message.text text = call.data delete_buttons(user_id, message_id, message_text) manager = MessageManager(user_id) response = None try: response = manager.dispatch(text) except Exception as e: print(repr(e)) if not send_message(user_id, response['text'], response['markup'], response['file_path']): response = {'text': 'Что-то пошло не так', 'markup': None} send_message(user_id, response['text'], markup=None)
def __init__(self): global MINING_INTERVAL self.name = sys.argv[-1] self.NL = Broadcast(self.name) self.ip, self.port = self.NL.get_my_info() with open("/sim/output/{0}_log.txt".format(self.name), "w") as f: f.write("Hello") self.lock = threading.Lock() self.mm = MessageManager(self.name) self.CL = PoW(self.name) self.previous_hash = self.CL.mine_gblock() signal.signal(signal.SIGINT, self.__KeyboardInterruptHandler) self.wait_thread = threading.Thread(target=self.__wait_access) self.wait_thread.start() self.mining_timer = threading.Timer(MINING_INTERVAL, self.__start_mining) self.mining_timer.start()
def __init__(self): self.name = sys.argv[-1] self.make_table() self.port = 11111 with open("/fika/output/log.txt", "w") as f: f.write("Hello") self.lock = threading.Lock() self.mm = MessageManager() self.bm = BlockchainManager() self.miner = BlockMiner() genesis_block = self.miner.mine_gblock() self.bm.chained(genesis_block) self.previous_hash = self.bm.get_hash(genesis_block) self.MINING_NOW = False self.STOP_MINING = False signal.signal(signal.SIGINT, self.__KeyboardInterruptHandler) self.wait_thread = threading.Thread(target=self.__wait_access) self.wait_thread.start() self.mining_timer = threading.Timer(MINING_INTERVAL, self.__start_mining) self.mining_timer.start()
class CozmoMqttProgram(): def __init__(self) -> None: self._cozmo = cozmo_client.Cozmo() self._queue = SimpleQueue() self._mqtt_client = None if MQTT_BROKER_URL is not None: self._mqtt_client = mqtt_client.MqttClient( MQTT_BROKER_URL, MQTT_BROKER_PORT, MQTT_USERNAME, MQTT_PASSWORD, MQTT_TOPICS, self._on_mqtt_message) self.sdk_conn: CozmoConnection = None self._faces: Dict[Face, datetime] = dict() self._visible_objects: Dict[ObservableObject, datetime] = dict() self._message_manager = MessageManager() self._cozmo_state = CozmoStates.Disconnected @property def cozmo_state(self) -> CozmoStates: return self._cozmo_state @cozmo_state.setter def cozmo_state(self, state: CozmoStates) -> None: self._cozmo_state = state self._publish_cozmo_state() async def run_with_robot_async(self, robot: cozmo.robot.Robot) -> None: self.sdk_conn = robot.world.conn await self._run_async(robot) async def _run_async(self, robot: cozmo.robot.Robot) -> None: await self._initialize_async(robot) try: while self.sdk_conn.is_connected: self._cozmo.update_needs_level() if self._cozmo.needs_charging( ) and not self._cozmo.is_sleeping: await self._charge_cycle() await self._cozmo.wake_up_async() self._cozmo_freetime() if not self._queue.empty(): await self._handel_queue_async() if self._cozmo.world.visible_face_count() > 0: face = self._get_visible_face() if face: if face in self._faces: last_seen = self._faces[face] if (datetime.now() - last_seen).total_seconds() > 60: await self._cozmo_do_async( self._on_saw_face(face)) else: await self._cozmo_do_async(self._on_saw_face(face)) if self._cozmo.robot.is_picked_up: await self._cozmo_do_async(self._on_picked_up_async()) if self._cozmo.robot.is_cliff_detected: await self._cozmo_do_async(self._on_cliff_detected_async()) if self._cozmo.world.visible_object_count( object_type=ObservableObject) > 0: visible_object = self._get_visible_object() if visible_object: if visible_object in self._visible_objects: last_seen = self._visible_objects[visible_object] if (datetime.now() - last_seen).total_seconds() > 60 * 5: await self._cozmo_do_async( self._on_new_object_appeared_async( visible_object)) else: await self._cozmo_do_async( self._on_new_object_appeared_async( visible_object)) await asyncio.sleep(0.1) except: print("Unexpected error:", sys.exc_info()[0]) await self.terminate_async() async def _initialize_async(self, robot: cozmo.robot.Robot) -> None: self._observe_connection_lost(self.sdk_conn, self._on_connection_lost) self._cozmo.set_robot(robot) await asyncio.gather(self._cozmo.connect_to_cubes_async(), self._cozmo.get_off_charger_async()) if self._mqtt_client is not None: await self._mqtt_client.connect_async() self.cozmo_state = CozmoStates.Connected self._cozmo_freetime() async def terminate_async(self) -> None: print("Terminating") if self._mqtt_client is not None: await self._mqtt_client.disconnect_async() if self.sdk_conn.is_connected: print("Sending cozmo back to charger") await self._cozmo.stop_all_actions_async() self._cozmo.back_to_normal() await self._cozmo.get_on_charger_async() def _observe_connection_lost(self, connection: CozmoConnection, cb): meth = connection.connection_lost @functools.wraps(meth) def connection_lost(self, exc): meth(exc) cb() connection.connection_lost = types.MethodType(connection_lost, connection) def _on_connection_lost(self) -> None: print("Captured connection lost") self.cozmo_state = CozmoStates.ConnectionLost def _publish_cozmo_state(self) -> None: if self._mqtt_client is not None: payload = dict() payload["status"] = self.cozmo_state.value attributes = dict() if self._cozmo.robot: attributes["battery_voltage"] = self._cozmo.battery_voltage payload["attributes"] = attributes self._mqtt_client.publish(COZMO_MQTT_PUBLISHING_TOPIC, payload) async def _on_saw_face(self, face: Face) -> None: self._faces[face] = datetime.now() self.cozmo_state = CozmoStates.SawFace print("An face appeared: {}".format(face)) if face.name: await self._cozmo.turn_toward_face_async(face) message = self._message_manager.get_hello_message(face) await self._cozmo.random_positive_anim_async() await self._cozmo.say_async(message) if face.known_expression: message = self._message_manager.get_fece_expression_message( face.known_expression, face) await self._cozmo.say_async(message) else: message = self._message_manager.get_non_recognized_message(face) await self._cozmo.say_async(message) async def _on_picked_up_async(self) -> None: print("Cozmo was picked up") self.cozmo_state = CozmoStates.PickedUp face = self._get_visible_face() message = self._message_manager.get_picked_up_message(face) await self._cozmo.random_positive_anim_async() if face: await self._cozmo.display_camera_image_async() await self._cozmo.say_async(message) while self._cozmo.robot.is_picked_up: await asyncio.sleep(0.1) print("Cozmo was put down") async def _on_cliff_detected_async(self) -> None: print("Cozmo detected a cliff") self.cozmo_state = CozmoStates.OnCliff self._cozmo.stop() self._cozmo.clear_current_animations() await self._cozmo.drive_wheels_async(-40, 1) face = self._get_visible_face() message = self._message_manager.get_cliff_detected_message(face) await self._cozmo.random_negative_anim_async() await self._cozmo.say_async(message) while self._cozmo.robot.is_cliff_detected: await asyncio.sleep(0.1) print("Cozmo away from cliff") async def _on_new_object_appeared_async( self, visible_object: ObservableObject) -> None: self._visible_objects[visible_object] = datetime.now() print("An obbject appeared: {}".format(visible_object)) face = self._get_visible_face() message = self._message_manager.get_object_appeared_message( visible_object, face) await self._cozmo.say_async(message) def _get_visible_face(self) -> Face: if self._cozmo.world.visible_face_count() == 0: print("Found no visibile faces") return None visible_face = next((face for face in self._cozmo.world.visible_faces), None) return visible_face def _get_visible_object(self) -> ObservableObject: if self._cozmo.world.visible_object_count( object_type=ObservableObject) == 0: print("Found no visibile objects") return None visible_obj = next((obj for obj in self._cozmo.world.visible_objects), None) return visible_obj def _cozmo_freetime(self) -> None: self._cozmo.start_free_time() self.cozmo_state = CozmoStates.Freetime async def _cozmo_do_async(self, async_f: Awaitable) -> None: if self._cozmo.freetime_enabled: self._cozmo.stop_free_time() try: await async_f self._cozmo_freetime() except cozmo.RobotBusy: print("Task Exception...cozmo is Busy") async def _charge_cycle(self) -> None: self.cozmo_state = CozmoStates.GoingToCharge print("Cozmo needs charging. Battery level {}".format( self._cozmo.battery_voltage)) await self._cozmo.start_charging_routine_async() self.cozmo_state = CozmoStates.Charging await self._cozmo.charge_to_full_async() print("Cozmo charged") # MQTT Queue Related------------------------------------------------------------------------------------------------------------------- def _on_mqtt_message(self, client, topic, payload, qos, properties) -> None: try: json_data = json.loads(payload.decode('utf-8')) print("Topic: {}".format(topic)) print("Data: {}".format(json_data)) topic_data_tuple = (topic, json_data) self._queue.put(topic_data_tuple) except: print("Unexpected error:", sys.exc_info()[0]) async def _handel_queue_async(self) -> None: if not self._queue.empty(): print("Cozmo processing queue") await self._cozmo_do_async( self._process_message_async(self._queue.get())) await self._handel_queue_async() async def _process_message_async(self, topic_data_tuple: tuple) -> None: topic = topic_data_tuple[0] json_data = topic_data_tuple[1] if topic == MQTT_WEATHER_TOPIC: await self._process_weather_notification_async(json_data) elif topic == MQTT_CONTROL_TOPIC: await self._process_control_msg_async(json_data) async def _process_control_msg_async(self, json_data: dict) -> None: if "msg" in json_data: msg = json_data["msg"] if msg == 'sleep': asyncio.create_task(self._cozmo.sleep_async()) if msg == 'freetime': await self._cozmo.wake_up_async() self._cozmo_freetime() async def _process_weather_notification_async(self, json_data: dict) -> None: if "msg" in json_data: msg = json_data["msg"] image_url = None color = None title = "I have a weather update notification for you." if "imagePath" in json_data: image_url = json_data["imagePath"] if 'clear' in msg: print("Clear outside!") color = YELLOW elif 'cloudy' in msg: print("Cloudy outside!") color = SLATE_GRAY await self._cozmo_annonuce_weather_update_async( msg, title, color, image_url) async def _cozmo_annonuce_weather_update_async( self, msg: str, title: str, rgb: Union[Tuple, None] = None, image_url: str = None) -> None: self.cozmo_state = CozmoStates.Anouncing if rgb: light = Light(Color(rgb=rgb)).flash() self._cozmo.cubes_change_lights(light) self._cozmo.backpack_change_light(light) await self._cozmo.random_positive_anim_async() await self._cozmo.say_async(title) await self._cozmo.say_async(msg) if image_url: await self._cozmo.show_image_from_url_async(image_url) if rgb: self._cozmo.turn_cubes_lights_off() self._cozmo.turn_backpack_light_off()
class NodeCore: def __init__(self): self.name = sys.argv[-1] self.make_table() self.port = 11111 with open("/fika/output/log.txt", "w") as f: f.write("Hello") self.lock = threading.Lock() self.mm = MessageManager() self.bm = BlockchainManager() self.miner = BlockMiner() genesis_block = self.miner.mine_gblock() self.bm.chained(genesis_block) self.previous_hash = self.bm.get_hash(genesis_block) self.MINING_NOW = False self.STOP_MINING = False signal.signal(signal.SIGINT, self.__KeyboardInterruptHandler) self.wait_thread = threading.Thread(target=self.__wait_access) self.wait_thread.start() self.mining_timer = threading.Timer(MINING_INTERVAL, self.__start_mining) self.mining_timer.start() def make_table(self): with open("/fika/ip_info.txt", "r") as f: info = json.loads(f.read()) with open("/fika/logicnet_info.txt", "r") as f: my_info = json.loads(f.read()) self.peer = dict() self.ip = info[self.name] my_info = my_info[self.name] for i in my_info: self.peer[i] = info[i] def __wait_access(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((self.ip, self.port)) s.listen(0) executor = ThreadPoolExecutor(max_workers=10) while True: conn, addr = s.accept() executor.submit(self.__handle_message, conn) def __start_mining(self): while self.STOP_MINING is not True: self.MINING_NOW = True with open("/fika/output/log.txt", "a") as f: f.write("\nMining start!!!") self.MINING_NOW = True length = self.bm.get_length() + 1 block = self.miner.mine_block(length, self.previous_hash) if (block["previous_hash"] != self.previous_hash) or ( block["height"] != self.bm.get_length() + 1): with open("/fika/output/log.txt", "a") as f: f.write("\nOops! I might have lost mining competition") break self.bm.chained(block) self.previous_hash = self.bm.get_hash(block) message = self.mm.build(self.ip, MSG_BLOCK, block) self.broadcast(message, self.ip) self.STOP_MINING = True self.STOP_MINING = False self.MINING_NOW = False self.mining_timer = threading.Timer(MINING_INTERVAL, self.__start_mining) self.mining_timer.start() def broadcast(self, message, sender): for ip in self.peer.values(): if (ip != self.ip and ip != sender): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, 11111)) s.sendall(message.encode()) s.close() except: with open("/fika/output/log.txt", "a") as f: f.write("\nConnection failed...") else: continue def __handle_message(self, conn): result, sender, msg_type, payload = self.mm.parse(conn) if result == "OK": if msg_type == MSG_TEST: self.broadcast(message, sender) elif msg_type == MSG_BLOCK: result, result2 = self.bm.verify_block(self.previous_hash, payload) if result is True: if MINING_NOW: STOP_MINING = True self.bm.chained(payload) self.previous_hash = self.bm.get_hash(payload) with open("/fika/output/log.txt", "a") as f: f.write("\nprevious_hash is changed...{0}".format( self.previous_hash)) self.mining_timer = threading.Timer( MINING_INTERVAL, self.__start_mining) self.mining_timer.start() message = self.mm.build(self.ip, MSG_BLOCK, payload) self.broadcast(message, sender) else: if result2 == 1: message = self.mm.build(self.ip, MSG_CHAIN, None) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((sender, 11111)) s.sendall(message.encode()) s.close() elif msg_type == MSG_CHAIN: chain = self.bm.get_mychain() message = self.mm.build(self.ip, MSG_RSP_CHAIN, chain) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((sender, 11111)) s.sendall(message.encode()) s.close() elif msg_type == MSG_RSP_CHAIN: with self.lock: result = self.bm.verify_chain(payload) if result: last_block = self.bm.get_lastblock() self.previous_hash = self.bm.get_hash(last_block) else: with open("/fika/output/log.txt", "a") as f: f.write("\nReceived Blockchain is useless") else: with open("/fika/output/log.txt", "a") as f: f.write("\nERROR") def __KeyboardInterruptHandler(self, signal, frame): with open("/fika/output/log.txt", "a") as f: f.write("\nCtrl+C!!!") chain = self.bm.get_mychain() with open("/fika/output/blockchain.txt", "w") as f: f.write(json.dumps(chain, indent=4, sort_keys=True)) sys.exit(0)
def receiving_messages(message): manager = MessageManager(message.chat.id) response = manager.dispatch(message.text) if not send_message(message.chat.id, response['text'], response['markup'], response['file_path']): delete_trash(message)
def send_welcome(message): manager = MessageManager(message.chat.id) response = manager.start() if not send_message(message.chat.id, response['text'], response['markup']): delete_trash(message)
class NodeCore: def __init__(self): global MINING_INTERVAL self.name = sys.argv[-1] self.NL = Broadcast(self.name) self.ip, self.port = self.NL.get_my_info() with open("/sim/output/{0}_log.txt".format(self.name), "w") as f: f.write("Hello") self.lock = threading.Lock() self.mm = MessageManager(self.name) self.CL = PoW(self.name) self.previous_hash = self.CL.mine_gblock() signal.signal(signal.SIGINT, self.__KeyboardInterruptHandler) self.wait_thread = threading.Thread(target=self.__wait_access) self.wait_thread.start() self.mining_timer = threading.Timer(MINING_INTERVAL, self.__start_mining) self.mining_timer.start() def __wait_access(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((self.ip, self.port)) s.listen(0) executor = ThreadPoolExecutor(max_workers=10) while True: conn, addr = s.accept() executor.submit(self.__handle_message, conn) def __start_mining(self): global STOP_MINING global MINING_INTERVAL t1 = self.CL.get_time() t2 = time() t3 = t2 - t1 if t3 < MINING_INTERVAL: sleep(MINING_INTERVAL - t3) if STOP_MINING is False: result, block = self.CL.start_mining(self.previous_hash) if result == 0: message = self.mm.build((self.ip, self.port), MSG_BLOCK, block) self.NL.broadcast(message, (self.ip, self.port)) STOP_MINING = False self.mining_timer = threading.Timer(MINING_INTERVAL, self.__start_mining) self.mining_timer.start() def __handle_message(self, conn): global MINING_INTERVAL global STOP_MINING result, sender, msg_type, payload = self.mm.parse(conn) if result == "OK": if msg_type == MSG_TEST: self.NL.broadcast(message, sender) elif msg_type == MSG_BLOCK: result, result2 = self.CL.verify_block(self.previous_hash, payload) if result is True: STOP_MINING = True self.CL.stop_mining() self.CL.chained(payload) self.previous_hash = self.CL.get_hash(payload) with open("/sim/output/{0}_log.txt".format(self.name), "a") as f: f.write("\nprevious_hash is changed...{0}".format( self.previous_hash)) message = self.mm.build((self.ip, self.port), MSG_BLOCK, payload) self.NL.broadcast(message, sender) else: if result2 == 1: message = self.mm.build((self.ip, self.port), MSG_CHAIN, None) self.NL.send_message(message, sender) elif msg_type == MSG_CHAIN: chain = self.CL.get_mychain() message = self.mm.build((self.ip, self.port), MSG_RSP_CHAIN, chain) self.NL.send_message(message, sender) elif msg_type == MSG_RSP_CHAIN: with self.lock: result = self.CL.verify_chain(payload) if result: last_block = self.CL.get_lastblock() self.previous_hash = self.CL.get_hash(last_block) else: with open("/sim/output/{0}_log.txt".format(self.name), "a") as f: f.write("\nReceived Blockchain is useless") else: with open("/sim/output/{0}_log.txt".format(self.name), "a") as f: f.write("\nERROR") def __KeyboardInterruptHandler(self, signal, frame): with open("/sim/output/{0}_log.txt".format(self.name), "a") as f: f.write("\nCtrl+C!!!") chain = self.CL.get_mychain() with open("/sim/output/{0}_blockchain.txt".format(self.name), "w") as f: f.write(json.dumps(chain, indent=4, sort_keys=True)) sys.exit(0)
def main(): config = ConfigParser.ConfigParser() config.readfp(codecs.open('config.ini', 'r', 'utf-8-sig')) prototype_file = config.get('Global', 'prototype', 'prototype') manager = MessageManager() manager._ignore_messages.extend(message.strip() for message in config.get('Message', 'ignore', '').split(',')) manager._skip_fields.extend(field.strip() for field in config.get('Message', 'skip', '').split(',')) manager.scan_messages('%s/*.py' % prototype_file) readline.parse_and_bind("tab: complete") readline.set_completer(MessageCompleter(manager).complete) history_file = config.get('History', 'file', '.message_history') open(history_file, 'w').close() readline.read_history_file(history_file) gateway_channel = login.auto_login( host=str(config.get('GatewayServer', 'host', '192.168.78.132')), port=int(config.get('GatewayServer', 'port', '12003')), account=config.get('GatewayServer', 'account'), rolename=config.get('GatewayServer', 'rolename'), soldierid=int(config.get('GatewayServer', 'soldierid', 11101000)), zoneid=int(config.get('GatewayServer', 'zoneid', 0)), manager=manager) while True: sleep(0.1) message_name = '' try: print gateway_channel.login_url print '%s@%s:%s, %s(%s)' % (gateway_channel.unitid, gateway_channel.host, gateway_channel.port, gateway_channel.rolename, gateway_channel.soldierid) message_name = raw_input('Enter the MessageName(Full): ') message_name = message_name.strip() if message_name in manager._fuzzy_search.keys(): message_full_names = manager._fuzzy_search[message_name] if len(message_full_names) > 1: print "%s in %s means:%s" % (message_name, len(message_full_names), message_full_names) message_name = message_full_names[0] if message_name in manager._message_classes.keys(): message = manager.build_message(message_name) gateway_channel.send(message) elif message_name.startswith('#'): message_cls = manager._message_classes.get('msg.role.MessageRoleChat', None) if message_cls: message = message_cls() message.message = message_name gateway_channel.send(message) else: print 'gmcommand not support' elif message_name.startswith('$'): if message_name == '$sleep': try: while True: sleep(1) except: pass elif message_name.startswith('$run '): try: file_name = message_name.split(' ')[1] print 'run:', file_name execfile(file_name) except Exception as e: print e, type(e) else: if message_name: print '%s: not found' % message_name except EOFError as e: print '\n' exit() except Exception as e: print 'error:', str(e) pass finally: readline.write_history_file(history_file)
def __init__(self): self.ip = sys.argv[-2] self.port = int(sys.argv[-1]) self.mm = MessageManager() signal.signal(signal.SIGINT, self.__KeyboardInterruptHandler) self.__wait_access()
class ConnectionManager: def __init__(self, host, port, callback): self.host = host self.port = port self.mm = MessageManager() self.callback = callback self.peers = set() # connect to 2 peers # self.peers = [(host, 65001), (host, 65002)] # connect to 3 peers self.peers = [(host, 65001), (host, 65002), (host, 65003)] def start(self): t = threading.Thread(target=self.__wait_for_access) t.start() def add_peer(self, peer): self.peers.append(peer) def clear_peer(self, peer): self.peers.remove(peer) def __wait_for_access(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) self.socket.listen(0) while True: print('Waiting for the connection ...') soc, addr = self.socket.accept() data_sum = '' params = (soc, addr, data_sum) self.__handle_message(params) def __handle_message(self, params): soc, addr, data_sum = params while True: data = soc.recv(1024) data_sum = data_sum + data.decode('utf-8') if not data: break if not data_sum: return cmd, peer_port, payload = self.mm.parse(data_sum) print(cmd, peer_port, payload) if cmd == MSG_ADD: print('ADD node request was received!') self.add_peer((addr[0], peer_port)) else: self.callback((cmd, peer_port, payload)) def broadcast_tx(self, tx): msg = self.mm.build(MSG_NEW_TX, self.port, json.dumps(tx)) self.send_msg_to_all_peer(msg) def broadcast_block(self, block): msg = self.mm.build(MSG_NEW_BLOCK, self.port, block.to_dict()) self.send_msg_to_all_peer(msg) def request_chain(self, port): msg = self.mm.build(MSG_NEW_BLOCK, self.port) self.send_msg((self.host, port), msg) def send_chain(self, chain, port): msg = self.mm.build(MSG_CHAIN, self.port, chain) self.send_msg((self.host, port), msg) @staticmethod def send_msg(peer, msg): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((peer)) s.sendall(msg.encode('utf-8')) s.close() except OSError: print('Connection failed for peer : ', peer) def send_msg_to_all_peer(self, msg): print('send_msg_to_all_peer was called!') for peer in self.peers: if peer != (self.host, self.port): print('message will be sent to ...', peer) self.send_msg(peer, msg) def join_network(self, host, port): self.my_host = host self.my_port = port self.__connect_to_P2PNW(host, port) def __connect_to_P2PNW(self, host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) self.__add_peer((host, port)) msg = self.mm.build(MSG_ADD, self.port) s.sendall(msg.encode('utf-8')) s.close()
class Controller(QObject): def __init__(self, main_window, port, service_id): super().__init__() self.main_window = main_window #ConnectionManager (create Slots) self.connection_manager = ConnectionManager(port, service_id) self.message_manager = MessageManager(self.connection_manager, service_id) self.message_manager.signal_message_received.connect(self.print_string) self.message_manager.signal_election_responded.connect( self.set_election) self.message_manager.signal_leader_responded.connect( self.leader_has_been_found) self.message_manager.signal_has_message_to_send.connect( self.send_udp_message) self.message_manager.signal_leader_alive.connect(self.set_alive) data = {"port": str(port), "leader": "Null"} jdata = json.dumps(data) self.main_window.set_details(jdata) self.main_window.signal_has_message_to_send.connect( self.send_udp_message) self.main_window.signal_has_multicast_to_send.connect( self.send_multicast_message) self.main_window.signal_start_checking.connect(self.close) self.own_port = port self.service_id = service_id self.leader_ip = None self.leader_port = 0 self.leader_id = " " self.election = True self.leader_alive = False self.iam_leader = False self.control_boolean = False self.alive_checker_thread = AliveChecker(self, self.leader_ip, self.leader_port, self.connection_manager) self.alive_checker_thread.signal_election_is_due.connect( self.do_election) self.message_manager.signal_received_ok.connect(self.receive_ok) self.message_manager.signal_critical_request.connect( self.receive_request) self.worker_controller = WorkerController(1) self.worker_controller.signal_request_critical.connect( self.request_critical) self.worker_controller.signal_send_free_message.connect( self.send_free_message) #do first multicast self.th = th.Thread(target=self.request_group) self.th.start() def request_group(self): data = {"code": ENTER_GROUP, "msg": self.own_port} jdata = json.dumps(data) self.connection_manager.send_multicast_message(jdata) qDebug(QDateTime.currentDateTime().toString()) time.sleep(2) qDebug(QDateTime.currentDateTime().toString()) if self.leader_ip is None: self.iam_leader = True self.message_manager.set_is_leader(True) self.message_manager.send_message_to_main_window( str("I'm Leader!")) else: self.iam_leader = False self.message_manager.set_is_leader(False) self.alive_checker_thread.start() #colocar a mudaça de numero de processos aqui self.worker_controller.start() @pyqtSlot(str) def print_string(self, string): self.main_window.print_string(string) @pyqtSlot(str) def send_udp_message(self, jdata): self.connection_manager.send_message(jdata) @pyqtSlot(str) def send_multicast_message(self, jdata): self.connection_manager.send_multicast_message(jdata) def do_election(self): election_handler = ElectionHandler(self.service_id, self.message_manager) self.leader_ip, self.leader_port, self.leader_id = election_handler.do_election( ) election_handler.deleteLater() self.leader_alive = True self.alive_checker_thread.set_leader(self.leader_ip, self.leader_port) self.alive_checker_thread.start() def elected(self): self.message_manager.send_message_to_main_window("elected") data = {"code": NEW_LEADER, "msg": self.service_id} jdata = json.dumps(data) self.connection_manager.send_multicast_message(jdata) @pyqtSlot(bool) def set_election(self, status): self.election = status def set_is_leader(self): self.message_manager.send_message_to_main_window( str("id leader " + self.leader[0])) if self.leader[0] != " ": if int(self.leader[0]) == int(self.service_id): return True return False @pyqtSlot() def set_alive(self): self.alive_checker_thread.set_alive() @pyqtSlot(str, str, str) def leader_has_been_found(self, id, ip, port): self.leader_ip = ip self.leader_port = port self.leader_id = id self.leader_alive = True self.alive_checker_thread.set_leader(self.leader_ip, self.leader_port) self.alive_checker_thread.start() @pyqtSlot() def close(self): self.alive_checker_thread.terminate() self.worker_controller.end() @pyqtSlot(int) def request_critical(self, tick): self.message_manager.request_critical(tick) @pyqtSlot(int, str) def send_free_message(self, tick, ip): self.message_manager.send_free_message(tick, ip) @pyqtSlot(int) def receive_ok(self, tick): self.worker_controller.receive_ok(tick) @pyqtSlot(int, str) def receive_request(self, tick, ip): self.worker_controller.receive_request(tick, ip)
class MainPage(PageBase): def __init__(self, parent, controller): if not controller.token: controller.switch_frame("LoginPage") super().__init__(parent, controller) controller.title("SpaceChat client") # Token shower self.token_label = tk.Label(self, text=self.controller.token) self.token_label.grid(row=1, columnspan=1, sticky=tk.E) # Logout Button self.logout_btn = tk.Button(self, text="Logout", command=self._logout_btn_clicked) self.logout_btn.grid(row=2, columnspan=1) # Incoming message box self.incoming_message_box = tk.Text(self, height=4, width=50) self.incoming_message_box_scrollbar = tk.Scrollbar(self) self.incoming_message_box.grid(row=1, column=2, rowspan=2) self.incoming_message_box_scrollbar.grid(row=1, column=3, rowspan=2, sticky="NSW") self.incoming_message_box_scrollbar.config( command=self.incoming_message_box.yview) self.incoming_message_box.config( yscrollcommand=self.incoming_message_box_scrollbar.set, state="disabled") # prevents user from typing in it # Outgoing message box self.outgoing_message_box = tk.Entry(self, width=50) self.outgoing_message_box.grid(row=3, column=2, rowspan=1) # We want to add a binding just to the message sending box self.outgoing_message_box.bind("<Return>", self._send_message) self.pack() # Set up global keyboard shortcuts # TODO: Test on windows self.add_binding("<Alt-l>", self._logout_btn_clicked) self.add_binding("<Command-l>", self._logout_btn_clicked) # Mac # Connect to the message server! self.msg_manager = MessageManager(self) self.msg_manager.bind_message_handler(self.message_handler) self.add_text_to_incoming("Logged into server!") def add_text_to_incoming(self, text): # Used to add text to the incoming box self.incoming_message_box.configure(state="normal") self.incoming_message_box.insert("end", text) self.incoming_message_box.see("end") # Scrolls to bottom self.incoming_message_box.configure(state="disabled") def message_handler(self, resp): msg_type = resp.get("type", None) if msg_type is None: # TODO: Error? print(resp) elif msg_type == "generic": # TODO print(resp) elif msg_type == "user": username = resp["username"] msg = resp["msg"] msg_format = f"\n{username}: {msg}" self.add_text_to_incoming(msg_format) elif msg_type == "whisper": from_user = resp["username"] to_user = resp["recipient"] msg = resp["msg"] msg_format = f"\nwhisper from {from_user} to {to_user}: {msg}" self.add_text_to_incoming(msg_format) elif msg_type == "server": msg = resp["msg"] tm.showinfo("Server Message", msg) elif msg_type == "alert": msg = resp["msg"] msg_format = f"\nALERT! {msg}" self.add_text_to_incoming(msg_format) else: # TODO: Error? Unsupported format print(resp) def _logout_btn_clicked(self, event=None): self.controller.token = None # TODO: Move this to some request handler make_request("logout", dict(token=self.controller.token)) self.controller.switch_frame("LoginPage") def _send_message(self, event=None): msg = self.outgoing_message_box.get() # Clear message box self.outgoing_message_box.delete(0, "end") if msg == "": return self.msg_manager.send_message(msg)
async def on_message(message): nonlocal mm nonlocal voice nonlocal sound_map if client.user != message.author: input_msg = message.content if input_msg == '/bye': await message.channel.send('[INFO]ごきげんよう') await client.close() sys.exit(0) elif input_msg.startswith('/yasumi init'): if input_msg == '/yasumi init': mode = 'free' else: mode, = parse('/yasumi init {}', input_msg).fixed try: with open('config.json') as f: conf = json.load(f) sound_map = conf['sound'] mm = MessageManager(mode, conf) channel = message.author.voice.channel try: voice = await channel.connect() except ClientException: print( '[yasumi]Allready connected voice channel, continue.' .format(client)) pass await message.channel.send('[INFO]イニシャライズしたわ(システム: **' + mode + '**)') except ValueError as ve: await message.channel.send('[INFO]登録されていないシステムよ: __' + mode + '__') except AttributeError as ae: await message.channel.send('[INFO]適当なボイスチャンネルにログインして貰えるかしら' ) elif input_msg.startswith('/yasumi help'): if mm is None: await message.channel.send('[INFO]イニシャライズして頂戴') else: if input_msg == '/yasumi help': help_at = 'main' else: help_at, = parse('/yasumi help {}', input_msg).fixed try: help_msg = mm.help(help_at, sound_map) await message.channel.send(help_msg) except ValueError as ve: await message.channel.send('[INFO]登録されていないシステムよ: __' + help_at + '__') elif input_msg.startswith('/'): if mm is None: await message.channel.send('[INFO]イニシャライズして頂戴') else: player = str(message.author) msg = mm(input_msg, player) if isinstance(msg, str): if not msg: pass else: await message.channel.send(msg) elif isinstance(msg, list): for sub_msg in msg: await message.channel.send(sub_msg[0], file=sub_msg[1]) time.sleep(1.0) elif isinstance(msg, tuple): if isinstance(msg[1], discord.File): await message.channel.send(msg[0], file=msg[1]) else: if voice.is_playing(): voice.source = discord.FFmpegPCMAudio( mm.voice_path) else: voice.play( discord.FFmpegPCMAudio(mm.voice_path)) await message.channel.send(msg[0]) else: await message.channel.send('[INFO]無効なコマンドよ: __' + input_msg + '__') elif input_msg.startswith('#'): if not voice: await message.channel.send('[INFO]イニシャライズして頂戴') elif voice.is_playing(): voice.source = discord.FFmpegPCMAudio(sound_map[input_msg]) else: try: voice.play(discord.FFmpegPCMAudio( sound_map[input_msg])) except KeyError: await message.channel.send('[INFO]登録されていないサウンドよ: __' + input_msg + '__') except TypeError: await message.channel.send('[INFO]ファイルが正しい形式じゃないわね')