def __init__(self): super(EventProcessor, self).__init__() self.message_handler = MessageHandler() self.gps = GPS() Message.init() Detector.start_plugins() Reactor.add_plugin_events()
def __init__(self, kakopts): super(Client, self).__init__(None) self.Bind(wx.EVT_CLOSE, self.OnExit) self.makeMenuBar() self.CreateStatusBar() self.status_line = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH) self.buffer_view = FacedStaticText(self) self.buffer_view.Bind(wx.EVT_SIZE, self.OnBufferSize) self.buffer_view.Bind(wx.EVT_KEY_DOWN, self.OnBufferKeyPress) self.buffer_view.Bind(wx.EVT_CHAR, self.OnBufferChar) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.status_line, 0, wx.EXPAND) sizer.Add(self.buffer_view, 1, wx.EXPAND) sizer.SetSizeHints(self) self.SetSizerAndFit(sizer) self.kakoune = Kakoune(**kakopts) self.kakoune.start() self.message_handler = MessageHandler(self) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.kakoune_tick, self.timer) self.timer.Start(10) self.Size = (600, 800)
class Torrent_Downloader(): ''' Manages download logic: - Creation and removal of peers. - Book keeping of pieces downloaded and in progress. - Checking completed pieces and writing to file. ''' def __init__(self, torrent, start_listener_callback): self.torrent = torrent self.message_handler = MessageHandler(self.torrent, self) self.start_listener_callback = start_listener_callback self.ip = self.get_IP_address() self.tracker = Tracker(self.torrent.announce, self.torrent.get_params()) self.peers = self.create_peers() self.io_loop = get_event_loop() self.index = 0 self.callback_dict = { 'check_piece': self.torrent.check_piece_callback, 'pieces_changed': self.pieces_changed_callback, 'start_listener': self.start_listener_callback, } self.pieces_needed = [] def get_IP_address(self): response = get('http://api.ipify.org?format=json') ip_object = loads(response.text) return ip_object["ip"] def create_peers(self): peers = [] for p in self.tracker.parse_peer_address(): if p[0] == self.ip: continue peers.append(Peer(p[0], p[1], self)) return peers def pieces_changed_callback(self, peer): ''' Check if connected peer has pieces I need. Send interested message. Call choose_piece. If peer has no pieces I need, disconnect and remove from peers list. ''' self.torrent.update_pieces_needed() for i in self.torrent.pieces_needed: if peer.has_pieces[i]: self.io_loop.create_task( self.message_handler.send_message(peer=peer, message_id=2)) self.choose_piece(peer=peer) break else: self.peers.remove(peer) def choose_piece(self, peer): ''' Finds the next needed piece, updates self.have and self.pieces_needed. calls construct_request_payload. ''' piece_index = self.torrent.pieces_needed[0] self.torrent.have[piece_index] = True self.torrent.update_pieces_needed() self.message_handler.construct_request_payload(peer=peer, piece_index=piece_index)
def __init__(self, torrent): self.torrent = torrent self.tracker = Tracker(self.torrent.announce, self.torrent.get_params()) self.peers = self.create_peers() self.message_handler = MessageHandler(self.torrent, self) self.io_loop = get_event_loop() self.visualizer = Visualizer()
def run(self): sock = socket(AF_INET, SOCK_STREAM) sock.connect(self.server_adr) print("Client started") mh = MessageHandler(sock, self.bsize, self.pubkey, self.privkey) print("Enter command after the PocketDB > prompt. Enter .exit to exit") while True: print("PocketDB > ", end='') command = input().strip() if command == ".q": mh.send_message("\n") break if command.startswith("filter"): mh.send_message("select") data = mh.receive_message() lines = data.split("\n") lines = lines[1:-1] words = [i.strip() for i in lines] target = command.split()[1:] target = ' '.join(target) rst = [] words.pop() for word in words: if match(target, word.split(',')[1].strip()): rst.append(word) print(">Matched results:") print(rst) continue mh.send_message(command) data = mh.receive_message() if data == "\n\n\n": break print(data) print("Database connection closed")
def __init__(self, botId, botName, client, socket_delay=1): self.botId = botId self.botName = botName self.mention = self.getMention(botId) self.client = client self.delay = socket_delay self.messageHandler = MessageHandler(self.mention)
class Client: def __init__(self, host: str, port: int, connection_type: SocketKind = SOCK_STREAM, connection_family: AddressFamily = AF_INET, *args, **kwargs): self.__host = host self.__port = port self.__address = ( host, port, ) self.__conn_type = connection_type self.__conn_family = connection_family self.__to_stop = False self.user = "******" self.__message_handler = MessageHandler(PROTOCOLS_PATH, self.user) def run(self) -> None: # ToDo use ZeroMQ or socket + select (lib) with socket(family=self.__conn_family, type=self.__conn_type) as s: if not self.__conn_family == AF_INET: raise ConnectionError( f"Unknown connection family. " f"Expected: AF_INET. Actual: {str(self.__conn_family)}") if self.__conn_type == SOCK_STREAM: try: s.connect(self.__address) except ConnectionRefusedError as exc: raise ConnectionError( f"Server is not running or unknown ServerError occurred. Error: {exc}" ) self.__message_handler.communicator = s self.__start_chat_session(s) else: raise ConnectionError( f"Unknown connection type. " f"Expected: SOCK_STREAM. Actual: {str(self.__conn_type)}") def __start_chat_session(self, sock: socket) -> None: while not self.__to_stop: received_data = sock.recv(1024) self.__message_handler.handle_message(received_data) message = input('Write something to send to the server: ') to_send = dict( username=self.user, send_to="Petrov12345", message=message, ) self.__message_handler.send_user_message( to_send, temporary_communicator=sock) def stop(self) -> None: """ Switch-flag for stopping the client """ self.__to_stop = True
class Torrent_Downloader(): ''' Manages download logic: - Creation and removal of peers. - Book keeping of pieces downloaded and in progress. - Checking completed pieces and writing to file. ''' def __init__(self, torrent, start_listener_callback): self.torrent = torrent self.message_handler = MessageHandler(self.torrent, self) self.start_listener_callback = start_listener_callback self.ip = self.get_IP_address() self.tracker = Tracker(self.torrent.announce, self.torrent.get_params()) self.peers = self.create_peers() self.io_loop = get_event_loop() self.index = 0 self.callback_dict = { 'check_piece' : self.torrent.check_piece_callback, 'pieces_changed' : self.pieces_changed_callback, 'start_listener' : self.start_listener_callback, } self.pieces_needed = [] def get_IP_address(self): response = get('http://api.ipify.org?format=json') ip_object = loads(response.text) return ip_object["ip"] def create_peers(self): peers = [] for p in self.tracker.parse_peer_address(): if p[0] == self.ip: continue peers.append(Peer(p[0], p[1], self)) return peers def pieces_changed_callback(self, peer): ''' Check if connected peer has pieces I need. Send interested message. Call choose_piece. If peer has no pieces I need, disconnect and remove from peers list. ''' self.torrent.update_pieces_needed() for i in self.torrent.pieces_needed: if peer.has_pieces[i]: self.io_loop.create_task(self.message_handler.send_message(peer=peer, message_id=2)) self.choose_piece(peer=peer) break else: self.peers.remove(peer) def choose_piece(self, peer): ''' Finds the next needed piece, updates self.have and self.pieces_needed. calls construct_request_payload. ''' piece_index = self.torrent.pieces_needed[0] self.torrent.have[piece_index] = True self.torrent.update_pieces_needed() self.message_handler.construct_request_payload(peer=peer, piece_index=piece_index)
class RootView(BoxLayout): def __init__(self, *args, **kwargs): super(RootView, self).__init__(*args, **kwargs) self.message_handler = MessageHandler(self) self.serial = None self.last_serial_choices = set() self.update_serial_choices() def on_message(self, msg): self.message_handler.handle(bytes(msg)) def on_serial_choice(self, checkbox, value): if self.serial is not None: if self.serial.port == checkbox.port: return self.serial.close() self.serial = None if value: self.serial = SerialBindings(checkbox.port, self.on_message) def update_serial_choices(self, *largs): extra_mac_ports = set(glob.glob('/dev/tty.usbserial*')) new_serial_choices = set([port for port, _, _ in comports()]) for i_hate_macs in extra_mac_ports: new_serial_choices.add(i_hate_macs) if not sets_equal(self.last_serial_choices, new_serial_choices): self.indicators.serial_choices.clear_widgets() self.last_serial_choices = new_serial_choices for port in sorted(list(new_serial_choices)): port_name = port if port_name.startswith('/dev/'): port_name = port[5:] btn = Builder.load_string(''' CheckBox: size_hint_y: 1 group: 'serial_choice_group' ''') lbl = Builder.load_string(''' SaneLabel: size_hint_y: 1 text: '%s' ''' % (port_name,)) btn.bind(active=self.on_serial_choice) btn.port = port if self.serial is not None and self.serial.port == port: btn.active = True self.indicators.serial_choices.add_widget(btn) self.indicators.serial_choices.add_widget(lbl)
def _handle_server_response(self, response): """ Handles server response. Passes raw response from server to MessageHandler and except that MessageHandler.handle returns instance of IrcEvent class, so ircbot knows what to do next with the event. """ message_handler = MessageHandler() event = message_handler.handle(response) if event and event.to_server: for irc_message in event.to_server: self._send_to_server(irc_message.get_command())
def main(): message_handler1 = MessageHandler() message_handler1.read_message(SLAVE_PORT) time.sleep(1) broadcast.send('hei, dette er heis1',SLAVE_PORT) broadcast.send('heis1 er sulten',SLAVE_PORT) time.sleep(1) print message_handler1.read_message(SLAVE_PORT) print message_handler1.read_message(SLAVE_PORT)
class EventProcessor(Component): _singleton = None def __new__(cls, *args, **kwargs): if not cls._singleton: cls._singleton = super(EventProcessor, cls).__new__(cls) return cls._singleton def __init__(self): super(EventProcessor, self).__init__() self.message_handler = MessageHandler() #self.gps = GPS() Message.init(self.message_handler.plugin.address()) Detector.start_plugins() Reactor.add_plugin_events() def react_internal(self, event): temp = 1 #alert = Alert(event) #Reactor.react(alert) def compute_distance(self, location): # Not relevant for simulation #current_location = self.gps.get_current_coordinates() #return GPS.distance_between(current_location, location) return 0 def react_external(self, event): temp = 1 #distance = self.compute_distance(event.location) #alert = Alert(event, distance) #Reactor.react(alert) @handler("msg_received") def msg_received(self, *args): self.react_external(args[0]) @handler("detection_received") def detection_received(self, *args): event = args[0] if event.own_warning: self.react_internal(event) self.message_handler.emit_event(event) @classmethod def handle_detection(cls, event): cls._singleton.fire(detection_received(event)) @classmethod def handle_message(cls, event): cls._singleton.fire(msg_received(event))
def main(): SLAVE_TIMEOUT = 2 SLAVE_MESSAGE_TIMEOUT = 1 #instantiating classes message_handler = MessageHandler() master_handler = MasterHandler() active_master = False while True: #try: time.sleep(TICK) master_handler.update_master_alive(MY_ID) if master_handler.check_master_alive() == MY_ID: active_master = True else: slave_message = message_handler.receive_from_slave() if slave_message is not None: master_handler.update_elevator_online(slave_message['slave_id']) print "I am NOT master, my id is: " + str(MY_ID) #print elevator_online while active_master: time.sleep(TICK) #print "I AM master, my id is: " + str(my_id) master_handler.update_master_alive(MY_ID) slave_message = message_handler.receive_from_slave() if slave_message is not None: master_handler.clear_completed_orders(slave_message['direction'], slave_message['last_floor'], slave_message['next_floor']) master_handler.update_elevator_position(slave_message['slave_id'],slave_message['last_floor'],slave_message['next_floor'],slave_message['direction']) master_handler.add_new_orders(slave_message['slave_floor_up'],slave_message['slave_floor_down']) master_handler.update_sync_state(slave_message['orders_id'],slave_message['slave_id']) (orders_up,orders_down,orders_id) = master_handler.get_orders() message_handler.send_to_slave(orders_up,orders_down,MY_ID,orders_id) if master_handler.check_master_alive() != MY_ID: active_master = False
class Server: def __init__(self, port: int, host: str = "", connection_type: SocketKind = SOCK_STREAM, connection_family: AddressFamily = AF_INET, *args, **kwargs): self.__host = host self.__port = port self.__address = ( host, port, ) self.__conn_type = connection_type self.__conn_family = connection_family self.__to_stop = False self.__message_handler = MessageHandler(PROTOCOLS_PATH) def run(self) -> None: # ToDo make the server work with multiple clients with socket(family=self.__conn_family, type=self.__conn_type) as s: if not self.__conn_family == AF_INET: raise ConnectionError( f"Unknown connection family. " f"Expected: AF_INET. Actual: {str(self.__conn_family)}") if self.__conn_type == SOCK_STREAM: s.bind(self.__address) s.listen() print("Server started and waiting for connections...") conn, addr = s.accept() self.__message_handler.communicator = conn with conn: print(f"Connection established with {addr}") self.__message_handler.send_precence_request_message() while not self.__to_stop: received_message = conn.recv(4096) self.__message_handler.handle_message(received_message) # if not received_message: # break # print(f"Received data from client: {received_message.decode(encoding='utf-8')}") # conn.sendall(received_message) else: raise ConnectionError( f"Unknown connection type. " f"Expected: SOCK_STREAM. Actual: {str(self.__conn_type)}") def stop(self) -> None: """ Switch-flag for stopping the server """ self.__to_stop = True
class EventProcessor(Component): _singleton = None def __new__(cls, *args, **kwargs): if not cls._singleton: cls._singleton = super(EventProcessor, cls).__new__(cls) return cls._singleton def __init__(self): super(EventProcessor, self).__init__() self.message_handler = MessageHandler() #self.gps = GPS() Message.init(self.message_handler.plugin.address()) Detector.start_plugins() Reactor.add_plugin_events() def react_internal(self, event): temp = 1 #alert = Alert(event) #Reactor.react(alert) def compute_distance(self, location): # Not relevant for simulation #current_location = self.gps.get_current_coordinates() #return GPS.distance_between(current_location, location) return 0 def react_external(self, event): temp = 1 #distance = self.compute_distance(event.location) #alert = Alert(event, distance) #Reactor.react(alert) @handler("msg_received") def msg_received(self, *args): self.react_external(args[0]) @handler("detection_received") def detection_received(self, *args): event = args[0] if event.own_warning: self.react_internal(event) self.message_handler.emit_event(event) @classmethod def handle_detection(cls, event): cls._singleton.fire(detection_received(event)) @classmethod def handle_message(cls, event): cls._singleton.fire(msg_received(event))
def test_sms_sender(properties, deliver, channel, twilio_client, message, to, fixed_to): config = ConfigManager().configuration handler = MessageHandler(**config.get("sms")) handler.client = twilio_client consumer = MessageConsumer(handler, **config.get("rabbit")) consumer._handle_message(channel, deliver, properties, json.dumps({ "receiver_phones": to, "message": message }).encode("utf8")) twilio_client.messages.create.assert_called_once_with(body=message, from_=config.get("sms").get("sender"), to=fixed_to)
def test_http_sender_queue(properties, deliver, channel, message, url, format): # Add message to queue message_raw = {"url": url, "message": message, "format": format} config = ConfigManager().configuration message_handler = MessageHandler() consumer = MessageConsumer(message_handler, **config.get("rabbit")) message_handler._send_http_post = MagicMock() consumer._handle_message(channel, deliver, properties, json.dumps(message_raw).encode("utf8")) assert message_handler._send_http_post.called
class Marvin(SingleServerIRCBot): def __init__(self, conf, tui, all_joined): SingleServerIRCBot.__init__(self, [(conf.server, conf.port)], conf.nickname, conf.realname) self.conf = conf self.tui = tui tui.bot = self self.handler = MessageHandler(conf, self) self.pollers = [] self.all_joined = all_joined self.joined = [] for (user, project) in self.conf.issues: p = IssuePoller(conf, self, user, project) self.pollers.append(p) self.tui.msg(u'Poller built for ' + user + '/' + project) def on_nicknameinuse(self, c, e): c.nick(c.get_nickname() + '_') def on_welcome(self, c, e): self.tui.msg(u'Connected, joining channels...') for chan in self.conf.channels: c.join(chan) for p in self.pollers: p.start() def on_join(self, c, e): self.joined.append(e.target()) self.tui.msg(u'Joined ' + e.target() + '!') if util.are_equal_lower(self.joined, self.conf.channels): self.all_joined.set() def on_privmsg(self, c, e): self.handle_msg(c, e) def on_pubmsg(self, c, e): self.handle_msg(c, e) def handle_msg(self, c, e): user = irc.client.nm_to_n(e.source()) channel = e.target() msg = e.arguments()[0] self.handler.handle_msg(user, channel, msg) def broadcast(self, msg): for c in self.conf.channels: self.connection.privmsg(c, msg)
def test_http_sender_integration(message, url, format): # Fake message from queue message_raw = {"url": url, "message": message, "format": format} response = MessageHandler().process_message(message_raw) assert response.status_code == 200
def __init__(self): self._runner_process = None self._control_process = None self._watchdog = ProcessWatchdog(config.Watchdog.CHECK_INTERVAL) self.push_messages_receiver = PushMessageReceiver() self.config_builder = ConfigurationBuilder( config.Engine.CONFIGURATION_BUILDER) self.message_handler = MessageHandler(self) self.message_sender = MessageSender() self.message_router = MessageRouter( self.message_sender, self.message_handler.default_message_handler) self.state = ManagerState.EMPTY self._http_client = httpclient.HTTPClient() self._alert_registered = False self.obsi_id = getnode() # A unique identifier of this OBSI self._engine_running = False self._engine_running_lock = locks.Lock() self._processing_graph_set = False self._engine_config_builder = None self._keep_alive_periodic_callback = None self._avg_cpu = 0 self._avg_duration = 0 self._supported_elements_types = [] self._alert_messages_handler = None self._log_messages_handler = None
def main(): message_handler = MessageHandler() old_message = "this message will never be sent" while True: (floor,button) = message_handler.read_message(SLAVE_TO_MASTER_PORT) time.sleep(0.01) ''' Do some massive shit and calculations ''' if (floor and button) is not None: message = "%s,%s" % (floor,button) if message != old_message: broadcast.send(message,MASTER_TO_SLAVE_PORT)
def __init__(self): super(EventProcessor, self).__init__() self.message_handler = MessageHandler() #self.gps = GPS() Message.init(self.message_handler.plugin.address()) Detector.start_plugins() Reactor.add_plugin_events()
def main(): message_handler = MessageHandler() old_message = "this message will never be sent" while True: (floor, button) = message_handler.read_message(SLAVE_TO_MASTER_PORT) time.sleep(0.01) ''' Do some massive shit and calculations ''' if (floor and button) is not None: message = "%s,%s" % (floor, button) if message != old_message: broadcast.send(message, MASTER_TO_SLAVE_PORT)
def __init__(self, torrent, start_listener_callback): self.torrent = torrent self.message_handler = MessageHandler(self.torrent, self) self.start_listener_callback = start_listener_callback self.ip = self.get_IP_address() self.tracker = Tracker(self.torrent.announce, self.torrent.get_params()) self.peers = self.create_peers() self.io_loop = get_event_loop() self.index = 0 self.callback_dict = { 'check_piece': self.torrent.check_piece_callback, 'pieces_changed': self.pieces_changed_callback, 'start_listener': self.start_listener_callback, } self.pieces_needed = []
async def test_keep_light(self): handler = MessageHandler() [x, y, z] = lights.accel_to_color(0, 0, 255) handler.set_light_data([int(x), int(y), int(z)]) print("Original light:", handler.get_light_data()) handler.set_new_message(True) result = await lights.keep_light(handler) self.assertEqual("Finished", result) self.assertEqual([255, 255, 0], handler.get_light_data())
async def ensure_connection(handler: MessageHandler) -> None: """Task that attempts server connection, if connection closes, it waits for retry period. Args: handler (MessageHandler): Message handler """ message = json.dumps({'type': "Auth", 'payload': { 'username': USER_NAME, 'secret': SHARED_SECRET}}) t = 1 while True: logging.info("Establishing connection") await init_connection(message, handler) logging.info("Connection closed") handler.set_connection(False) await asyncio.sleep(t) t = get_connection_retry_time(t) logging.info(f'Retrying connection in {t} seconds')
def full_diags(): msg_handler = MessageHandler() message = Message( category='Full Diagnosis', message_txt= f"<span class='text-info'>Kicking off full diagnostic</span>") msg_handler.add_message(message) # Check if the diags path was ever created # if not, create create_diags_path() # Is internet running is_connected = internet_connected() if is_connected is False: critical_alert( "<span class='text-danger'>No Internet Connection</span>")
def __init__(self, port: int, host: str = "", connection_type: SocketKind = SOCK_STREAM, connection_family: AddressFamily = AF_INET, *args, **kwargs): self.__host = host self.__port = port self.__address = ( host, port, ) self.__conn_type = connection_type self.__conn_family = connection_family self.__to_stop = False self.__message_handler = MessageHandler(PROTOCOLS_PATH)
def __init__(self): """ Initializes the client object """ super(Client, self).__init__() self.host = None self.port = '9300' self.nick = None self.name = None self.parser = Parser(self) self.message_handler = MessageHandler() self.update_callback = None self.tcp = Connection(self, 'TCP') self.udp = Connection(self, 'UDP')
def main(): message_handler = MessageHandler() elevator_driver = ElevatorDriver() elevator_driver.start() old_message = 12345678 while True: (master_floor, master_button) = elevator_driver.pop_button_queue() if (master_floor and master_button) is not None: message = "%i,%i" % (master_floor, master_button) if message != old_message: broadcast.send(message, SLAVE_TO_MASTER_PORT) time.sleep(0.001) (floor, button) = message_handler.read_message(MASTER_TO_SLAVE_PORT) if (floor and button) is not None: floor = int(floor) button = int(button) elevator_driver.queue_floor_button_run(floor, button)
def main(): message_handler = MessageHandler() elevator_driver = ElevatorDriver() elevator_driver.start() old_message = 12345678 while True: (master_floor, master_button) = elevator_driver.pop_button_queue() if (master_floor and master_button) is not None: message = "%i,%i" % (master_floor,master_button) if message != old_message: broadcast.send(message,SLAVE_TO_MASTER_PORT) time.sleep(0.001) (floor, button) = message_handler.read_message(MASTER_TO_SLAVE_PORT) if (floor and button) is not None: floor = int(floor) button = int(button) elevator_driver.queue_floor_button_run(floor, button)
def main(): '''Starts execution once everything is loaded''' hostname = sys.argv[1] port = int(sys.argv[2]) username = sys.argv[3] directory = sys.argv[4].rstrip('/') client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client_socket.connect((hostname, port)) except Exception as _: utils.log_message("ERROR", "PyBox is currently unavailable due to socket error") client_socket.close() return object_socket = ObjectSocket(client_socket) message_handler = MessageHandler(object_socket) message_handler.do_login(username, directory) message_handler.process()
class Consumer(): _BINDING_IP = '127.0.0.1' _BINDING_PORT = 65432 _socketSelector = None _CONNECTION_ID = None _messageHandler = None _MAX_BUFFER_SIZE = 4096 def __init__(self): self._CONNECTION_ID = uuid.uuid1() self._socketSelector = selectors.DefaultSelector() self._messageHandler = MessageHandler() self._start_connection() def _start_connection(self): broker_addr = (self._BINDING_IP, self._BINDING_PORT) print('starting connection', self._CONNECTION_ID, 'to', broker_addr) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(False) sock.connect_ex(broker_addr) events = selectors.EVENT_READ data = types.SimpleNamespace(connectionId = self._CONNECTION_ID, inb = b'') self._socketSelector.register(sock, events, data=data) self._checkForMessages(); def _checkForMessages(self): while True: events = self._socketSelector.select(timeout=None) if events: for key, mask in events: self._serviceConnection(key, mask) '''if not self._socketSelector.get_map(): break''' def _writeToFile(self, message): fileName = message.header.split('=')[1] with open('output/'+fileName,"wb") as f: f.write(message.data) def _serviceConnection(self, key, mask): sock = key.fileobj data = key.data if mask & selectors.EVENT_READ: message = self._messageHandler.readMessage(sock) #recv_data = sock.recv(1024) # Should be ready to read if message: #print('received', repr(message), 'from connection', data.connectionId) self._writeToFile(message) if not message: print('closing connection', data.connectionId) self._socketSelector.unregister(sock) sock.close()
async def init_connection(message: str, handler: MessageHandler) -> None: """Initiate websocket connection and bind message handler Args: message (str): Auth Message handler (MessageHandler): Message handler """ uri = WS_URI try: logging.info("Connecting to server") async with websockets.connect(uri) as websocket: handler.set_connection(True) handler.set_websocket(websocket) await websocket.send(message) logging.info("Connection is open") await handle_messages(websocket, message, handler) logging.info("Connection is closed") await websocket.close() except TimeoutError as err: logging.error(f'Could not connect to web server {err}')
def test_email_sender(properties, deliver, channel, server, sender, recipients, subject, message): def _build_server(): return server config = ConfigManager().configuration handler = MessageHandler(**config.get("smtp")) handler._build_server = _build_server consumer = MessageConsumer(handler, **config.get("rabbit")) consumer._handle_message( channel, deliver, properties, json.dumps({ "receiver_emails": recipients, "message_html": message, "title": subject }).encode("utf8")) server.sendmail.assert_called_once_with(sender, '*****@*****.**', ANY)
def __init__(self, *args, **kwargs): super(RootView, self).__init__(*args, **kwargs) self.message_handler = MessageHandler(self) self.serial = None self.last_serial_choices = set() self.update_serial_choices()
def main(): '''Starts execution once everything is loaded''' port = int(sys.argv[1]) server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', port)) server_socket.listen(5) while True: connection_socket, _ = server_socket.accept() object_socket = ObjectSocket(connection_socket) MessageHandler(object_socket, thread=True)
class Torrent_Downloader: def __init__(self, torrent): self.torrent = torrent self.tracker = Tracker(self.torrent.announce, self.torrent.get_params()) self.peers = self.create_peers() self.message_handler = MessageHandler(self.torrent, self) self.io_loop = get_event_loop() self.visualizer = Visualizer() def create_peers(self): peers = [] for p in self.tracker.peer_list: if p[0] == self.torrent.ip: continue peers.append(Peer(p[0], p[1], self)) return peers def pieces_changed_callback(self, peer): ''' Check if connected peer has pieces I need. Send interested message. Call choose_piece. If peer has no pieces I need, disconnect and remove from peers list. ''' self.torrent.update_pieces_needed() for i in self.torrent.pieces_needed: if peer.has_pieces[i]: # created in bitfield function in message_handler self.io_loop.create_task(self.message_handler.send_message(peer=peer, message_id=2)) self.choose_piece(peer=peer) break else: self.peers.remove(peer) def choose_piece(self, peer): ''' Finds the next needed piece, updates self.have and self.pieces_needed. calls construct_request_payload. ''' piece_index = self.torrent.pieces_needed[0] self.torrent.have[piece_index] = True self.torrent.update_pieces_needed() self.message_handler.construct_request_payload(peer=peer, piece_index=piece_index, piece_length=self.torrent.piece_length)
def main(): message_handler = MessageHandler() driver = Driver() #my_id = get IP address on this computer my_id = 3 acknowledge = 4 run_floor = 0 run_button = 0 old_f = None old_but = None floor_up = [0] * 4 floor_down = [0] * 4 while True: position = driver.read_position() master_message = message_handler.receive_from_master() for i in range(0, 4): if (master_message['master_floor_up'][i] == 0): floor_up[i] = 0 if (master_message['master_floor_down'][i] == 0): floor_down[i] = 0 time.sleep(0.1) (floor, button) = driver.pop_floor_panel_queue() if floor is not None: if button == 0: floor_up[floor] = 1 elif button == 1: floor_down[floor] = 1 message_handler.send_to_master(floor_up, floor_down, my_id, position[0], position[1], position[2], master_message['queue_id']) print floor_up print floor_down (run_floor, run_button) = message_handler.get_my_master_order() print run_floor print run_button if run_floor is not None: driver.queue_elevator_run(run_floor, run_button) print['floor_up:'] + master_message['master_floor_up'] + [ 'floor_down:' ] + master_message['master_floor_down'] #print master_message['queue_id'] time.sleep(0.5) '''
class PushMessagesAPIHandler(tornado.web.RequestHandler): def get(self): message = self.get_argument('message', default=None) if message is None: return try: message = json.loads(message) except Exception, e: print "Failed json loading ", e return handler = MessageHandler.get_handler() handler.handle_message(message, self)
def __init__(self, conf, tui, all_joined): SingleServerIRCBot.__init__(self, [(conf.server, conf.port)], conf.nickname, conf.realname) self.conf = conf self.tui = tui tui.bot = self self.handler = MessageHandler(conf, self) self.pollers = [] self.all_joined = all_joined self.joined = [] for (user, project) in self.conf.issues: p = IssuePoller(conf, self, user, project) self.pollers.append(p) self.tui.msg(u'Poller built for ' + user + '/' + project)
def main(): SLAVE_TIMEOUT = 2 SLAVE_MESSAGE_TIMEOUT = 1 #instantiating classes message_handler = MessageHandler() master_handler = MasterHandler() active_master = False while True: #try: time.sleep(TICK) master_handler.update_master_alive(MY_ID) if master_handler.check_master_alive() == MY_ID: active_master = True else: slave_message = message_handler.receive_from_slave() if slave_message is not None: master_handler.update_elevator_online( slave_message['slave_id']) print "I am NOT master, my id is: " + str(MY_ID) #print elevator_online while active_master: time.sleep(TICK) #print "I AM master, my id is: " + str(my_id) master_handler.update_master_alive(MY_ID) slave_message = message_handler.receive_from_slave() if slave_message is not None: master_handler.clear_completed_orders( slave_message['direction'], slave_message['last_floor'], slave_message['next_floor']) master_handler.update_elevator_position( slave_message['slave_id'], slave_message['last_floor'], slave_message['next_floor'], slave_message['direction']) master_handler.add_new_orders( slave_message['slave_floor_up'], slave_message['slave_floor_down']) master_handler.update_sync_state(slave_message['orders_id'], slave_message['slave_id']) (orders_up, orders_down, orders_id) = master_handler.get_orders() message_handler.send_to_slave(orders_up, orders_down, MY_ID, orders_id) if master_handler.check_master_alive() != MY_ID: active_master = False
async def main(): """Start asyncio tasks """ handler = MessageHandler() logging.debug("Starting light task") start_light = asyncio.create_task(lights.read_light_data(handler)) start_light.set_name("start light") connect = asyncio.create_task(ensure_connection(handler)) connect.set_name("ws connect") lights.event.set() await asyncio.gather(connect, start_light)
def __init__(self, torrent, start_listener_callback): self.torrent = torrent self.message_handler = MessageHandler(self.torrent, self) self.start_listener_callback = start_listener_callback self.ip = self.get_IP_address() self.tracker = Tracker(self.torrent.announce, self.torrent.get_params()) self.peers = self.create_peers() self.io_loop = get_event_loop() self.index = 0 self.callback_dict = { 'check_piece' : self.torrent.check_piece_callback, 'pieces_changed' : self.pieces_changed_callback, 'start_listener' : self.start_listener_callback, } self.pieces_needed = []
def main(): #instantiating classes message_handler = MessageHandler() slave_driver = SlaveDriver() orders_id = 0 while True: #try: time.sleep(TICK) position = slave_driver.read_position() master_message = message_handler.receive_from_master() if master_message is not None: slave_driver.clear_floor_panel(master_message['orders_up'][:],master_message['orders_down'][:]) orders_id = master_message['orders_id'] if slave_driver.changing_master(master_message['master_id']): my_master_queue = slave_driver.read_saved_master_queue() print "CHANGING MASTER STATE = TRUE -> my_master_queue: " + str(my_master_queue) for i in range(0,8): if my_master_queue[i] > 0: my_master_queue[i]=1 message_handler.send_to_master(my_master_queue[0:4],my_master_queue[4:8],MY_ID,position[0],position[1],position[2],master_message['orders_id']) orders_ok = True for order in range(0,N_FLOORS): if ( (my_master_queue[order] > 0) and (master_message['orders_up'][order] == 0) ) and ( (my_master_queue[4+order] > 0) and (master_message['orders_down'][order]) ): orders_ok = False if orders_ok: #is_master = False changing_master = False else: print master_message['orders_up'][:] + master_message['orders_down'][:] slave_driver.master_queue_elevator_run(master_message['orders_up'][:] + master_message['orders_down'][:]) (floor_up,floor_down) = slave_driver.get_floor_panel() print floor_up + floor_down + ['pikk'] message_handler.send_to_master(floor_up,floor_down,MY_ID,position[0],position[1],position[2],orders_id)
def main(): message_handler = MessageHandler() driver = Driver() #my_id = get IP address on this computer my_id = 3 acknowledge = 4 run_floor = 0 run_button = 0 old_f = None old_but = None floor_up = [0]*4 floor_down = [0]*4 while True: position = driver.read_position() master_message = message_handler.receive_from_master() for i in range (0,4): if (master_message['master_floor_up'][i] == 0): floor_up[i] = 0 if (master_message['master_floor_down'][i] == 0): floor_down[i] = 0 time.sleep(0.1) (floor,button) = driver.pop_floor_panel_queue() if floor is not None: if button == 0: floor_up[floor] = 1 elif button == 1: floor_down[floor] = 1 message_handler.send_to_master(floor_up,floor_down,my_id,position[0],position[1],position[2],master_message['queue_id']) print floor_up print floor_down (run_floor,run_button) = message_handler.get_my_master_order() print run_floor print run_button if run_floor is not None: driver.queue_elevator_run(run_floor,run_button) print ['floor_up:'] + master_message['master_floor_up'] + ['floor_down:'] + master_message['master_floor_down'] #print master_message['queue_id'] time.sleep(0.5) '''
print "options (Event logging) log: %s" % logflg file_name = "/tmp/pi-server-lock" fp = open(file_name, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except Exception, e: print "Lock file:%s is in use" % (file_name) print "Only one instance of the server can run at any one time" print "Please kill the other instance or remove the lock file" sys.exit(1) # kbrd = KeyBoard() # kbrd.echo_off() message_handler = MessageHandler(host, port, username, password, logdir, logflg) message_handler.start() message_handler.join() # try: # while (True): # # if kbrd.test_input(): # kbrd.echo_on() # print "\n" # cmd = raw_input(">") # # if cmd.find("h") != -1: # print "Commands: h=help, r=registrations, s=status q=quit" # # if cmd.find("q") != -1:
def main(): message_handler = MessageHandler() queue_id = 1 active_slaves = 1 acknowledges = 0 execute_queue = 0 arivied = 0 acknowledged_queue_id = [] last_direction = 0 executer_id = [0]*8 my_id = 1 active_master = 0 while True: message_handler.update_master_alive(my_id) print message_handler.check_master_alive() if message_handler.check_master_alive() == my_id: active_master = 1 time.sleep(0.1) while active_master == 1: message_handler.update_master_alive(my_id) slave_message = message_handler.receive_from_slave() print ['floor_up:'] + slave_message['slave_floor_up'] + ['floor_down:'] + slave_message['slave_floor_down'] print queue_id #if slave_message['direction'] is not DIRN_STOP: last_direction = slave_message['direction'] if slave_message['last_floor'] == slave_message['next_floor']: arrived = slave_message['last_floor'] if (last_direction == DIRN_UP) or (last_direction == DIRN_STOP): slave_message['slave_floor_up'][arrived] = 0 if (last_direction == DIRN_DOWN) or (last_direction == DIRN_STOP): slave_message['slave_floor_down'][arrived] = 0 #if queue_id == int(slave_message['queue_id']): # acknowledges += 1 # print '111111111111111111111111111111111111111111111111111111111' #if acknowledges == active_slaves: # execute_queue = 1 # print '12222222222222222222222222222222222222222222222222222' # message_handler.send_to_slave(slave_message['slave_floor_up'],slave_message['slave_floor_down'],executer_id,execute_queue,queue_id) # execute_queue = 0 # acknowledges = 0 # queue_id += 1 #else: # message_handler.send_to_slave(slave_message['slave_floor_up'],slave_message['slave_floor_down'],executer_id,execute_queue,queue_id) message_handler.send_to_slave(slave_message['slave_floor_up'],slave_message['slave_floor_down'],executer_id,execute_queue,queue_id) time.sleep(0.1) if message_handler.check_master_alive() != my_id: active_master = 0
def main(): #instantiating classes message_handler = MessageHandler(123) master_handler = MasterHandler() queue_id = 1 #allocating arrays button_orders = [0]*8 last_button_orders = [10]*8 elevator_positions = [[0,0,1],[0,0,1],[0,0,1]] elevator_orders = [0]*8 last_elevator_orders = [10]*8 elevator_online = [0]*N_ELEVATORS elevators_received_current_queue_id = [0]*N_ELEVATORS active_slaves = 0 #acknowledges = 0 #execute_queue = 0 arrived = 0 acknowledged_queue_id = [] goto_floor_up = [0]*4 goto_floor_down = [0]*4 last_direction = 0 executer_id = [0]*8 active_master = False #semi_active_master = False downtime_elevator_online = [time.time() + 3]*N_ELEVATORS downtime_queue_id = time.time() + 3 timeout_active_slaves = 0 while True: master_handler.update_master_alive(MY_ID) master_queue = master_handler.get_master_queue() if master_handler.check_master_alive() == MY_ID: active_master = True button_orders = master_queue[:] print "I am NOT master, my id is: " + str(MY_ID) time.sleep(0.02) while active_master: #print "I AM master, my id is: " + str(my_id) master_handler.update_master_alive(MY_ID) slave_message = message_handler.receive_from_slave() if slave_message is not None: last_direction = slave_message['direction'] if slave_message['last_floor'] == slave_message['next_floor']: arrived = slave_message['last_floor'] if (last_direction == DIRN_UP) or (last_direction == DIRN_STOP): #slave_message['slave_floor_up'][arrived] = 0 button_orders[arrived] = 0 if (last_direction == DIRN_DOWN) or (last_direction == DIRN_STOP): #slave_message['slave_floor_down'][arrived] = 0 button_orders[arrived+4] = 0 slave_id = slave_message['slave_id'] print str(slave_id) + ' slave id' elevator_positions[slave_id-1] = [slave_message['last_floor'],slave_message['next_floor'],slave_message['direction']] for i in range(0,4): if (button_orders[i] == 1) or (slave_message['slave_floor_up'][i] == 1): button_orders[i] = 1 for i in range(0,4): if (button_orders[i+4] == 1) or (slave_message['slave_floor_down'][i] == 1): button_orders[i+4] = 1 #print str(button_orders) + ' button_orders' #button_orders = slave_message['slave_floor_up'] + slave_message['slave_floor_down'] if queue_id == slave_message['queue_id']: elevators_received_current_queue_id[slave_id-1] = 1 active_slaves = elevator_online.count(1) #print (button_orders != last_button_orders) and (active_slaves == elevators_received_current_queue_id.count(1)) if (button_orders != last_button_orders) and (active_slaves == elevators_received_current_queue_id.count(1) or timeout_active_slaves == 1): # and (0 not in elevators_queue_id): print '1111111111111111111111111111111111' queue_id += 1 if queue_id > 9999: queue_id = 1 last_button_orders = button_orders[:] print 'hei' downtime_queue_id = time.time() + 1 timeout_active_slaves = 0 downtime_elevator_online[slave_id-1] = time.time() + 3 elevator_online[slave_id-1] = 1 elevator_orders = master_handler.order_elevator(last_button_orders, elevator_positions, elevator_online) print elevator_online print elevator_orders goto_floor_up[0:4] = elevator_orders[0:4] goto_floor_down[0:4] = elevator_orders[4:8] message_handler.send_to_slave(goto_floor_up,goto_floor_down,executer_id,MY_ID,queue_id) for i in range(0,N_ELEVATORS): if downtime_elevator_online[i] < time.time(): elevator_online[i] = 0 if downtime_queue_id < time.time(): for i in range(0,N_ELEVATORS): timeout_active_slaves = 1 master_handler.update_master_button_order(button_orders) time.sleep(0.02) if master_handler.check_master_alive() != MY_ID: active_master = False
class Client(object): """Client object.""" def __init__(self): """ Initializes the client object """ super(Client, self).__init__() self.host = None self.port = '9300' self.nick = None self.name = None self.parser = Parser(self) self.message_handler = MessageHandler() self.update_callback = None self.tcp = Connection(self, 'TCP') self.udp = Connection(self, 'UDP') def register_update_callback(self, func): """ """ self.update_callback = func def set_host(self, data): """ Sets the value of a given field. Arguments: - `field`: The field to set the given `value`. - `value`: The value to set. """ host = data[2] logging.debug('Host set to {0}'.format(host)) self.host = host def set_port(self, data): """ Sets the value of a given field. Arguments: - `field`: The field to set the given `value`. - `value`: The value to set. """ port = data[2] logging.debug('Port set to {0}'.format(port)) self.port = port def connect(self, data): """ Connects to the server if both hostname and username is set. """ if self.host is None: raise Warning(' '.join(['You must set the server\'s', 'hostname and your name before', 'connecting'])) self.nick = data[2].split()[0] name = ' '.join(data[2].split()[1:]) try: self.tcp.connect((self.host, int(self.port))) except socket.error as e: return self.denied([e.strerror]) self.tcp.send( bytes('CONNECT: "{0}" "{1}" {2}\r\n'.format(self.nick, name, get_git_version())) ) self.tcp.handle.start() def pong(self, data): if not self.tcp.is_connected(): raise Warning('You are not connected!') num = data[2] self.tcp.send(bytes('PONG: {0}\r\n'.format(num))) def join_channel(self, data): if not self.tcp.is_connected(): raise Warning('You are not connected!') channel = data[2] self.tcp.send(bytes('JOIN: {0}\r\n'.format(channel))) def message(self, data): """ Client > Server: `MSG #Lobby: Hello there!' (Public message in #Lobby. Sender is assigned on server side) `MSG John: Hi John!' (Private message. Sender is assigned on server side) Server > Client: `MSG Mike #Lobby: Hello there!' (Public message in #Lobby. Sent to all clients in the room.) `MSG Mike John: Hi John' (Private message) Arguments: - `data`: Given the scenarios above, data is a list where `data[0]` may be a nickname or a channel if `data[1]` is None. If `data[1]` is not None, it can either be a channel or a nickname. In that case `data[0]` will always be a nickname. `data[2]` is always the message. """ if not self.tcp.is_connected(): raise Warning('You are not connected!') chan = None recp = None sender = None if data[1] and '#' in data[1]: chan = data[1] elif data[1] and not '#' in data[1]: recp = data[1] elif not data[1]: recp = data[0] if data[0] and data[1]: sender = data[0] chatter = sender or recp msg = data[2] if (not data[0] and data[1]) or (not data[1] and data[0]): self.tcp.send(bytes('MSG {0}: {1}\r\n'.format(chan or recp, msg))) self.message_handler.message(author=sender, recipient=recp, channel=chan, message=msg) def talk(self, data): """ Client > Server: `TALK John: REQUEST' Server > Client: `TALK Mike John: REQUEST' (Private message) Arguments: - `data`: Given the scenarios above, data is a list where `data[0]` is always a nickname. If `data[1]` is not None, this will be the receiver of the code message. `data[2]` is always the code i.e. REQUEST, ACCEPT, ACCEPTED, DENY, DENIED. """ if not self.tcp.is_connected(): raise Warning('You are not connected!') code = data[2] recp = '' if data[0] and not data[1] and code == 'REQUEST': # 1. TALK Two: REQUEST self.tcp.send(bytes('TALK %s: %s\r\n' % (data[0], code))) elif data[0] and data[1] and code == 'REQUEST': # 2. TALK Two 123: REQUEST | target = TALK One 123: REQUEST self.udp.session_key = data[1] if not data[0] == self.client.nick: self.message_handler.talk(responder=data[0], code=code) else: self.message_handler.talk(requester=data[0], code=code) elif data[0] and code == 'ACCEPT' or code == 'DENY': # 3. TALK 123: ACCEPT/DENY self.tcp.send(bytes('TALK {0}: {1}\r\n'.format(data[0], code))) elif code == 'DENIED' or code == 'ACCEPTED': # TALK 123: DENIED/ACCEPTED self.message_handler.talk(code=code) if code == 'ACCEPTED': self.udp.open_stream() elif code == 'END': self.udp.close_stream() # STRESSSSSSSS!!!!!! def accepted(self, data): self.tcp.connected = True logging.debug( 'Connection to {0} has been established!'.format(data[0]) ) def denied(self, data): logging.debug( 'Your attempt to connect failed. Reason: {0}'.format(data[0]) ) def joined_channel(self, data): self.update_callback(channel=data[2]) logging.debug('You have joined the channel: '.format(data[2])) def userlist(self, data): self.update_callback(channel=data[1], userlist=data[2]) logging.debug('Users on {0}: {1}'.format(data[1], data[2])) def close(self): """Wrapper for the sockets close function.""" if self.tcp.sock: self.tcp.sock.close() if self.udp.sock: self.udp.sock.close()
def main(): #instantiating classes message_handler = MessageHandler(MY_ID) slave_driver = SlaveDriver() slave_handler = SlaveHandler() #acknowledge = 4 #run_floor = 0 #run_button = 0 #old_f = None #old_but = None is_master = False floor_up = [0]*4 floor_down = [0]*4 master_id = 10 changing_master = True last_master_id = 0 while True: if slave_handler.check_slave_alive() == MY_ID: active_slave = True position = slave_driver.read_position() master_message = message_handler.receive_from_master() (floor,button) = slave_driver.pop_floor_panel_queue() if floor is not None: if button == 0: floor_up[floor] = 1 elif button == 1: floor_down[floor] = 1 for i in range (0,4): if (master_message['master_floor_up'][i] != 0): floor_up[i] = 0 if (master_message['master_floor_down'][i] != 0): floor_down[i] = 0 #time.sleep(0.3) message_handler.send_to_master(floor_up,floor_down,MY_ID,position[0],position[1],position[2],master_message['queue_id']) print "floor_up: " + str(floor_up) print "floor_down: " + str(floor_down) ''' (run_floor,run_button) = message_handler.get_my_master_order() print run_floor print run_button if run_floor is not None: slave_driver.queue_elevator_run(run_floor,run_button) ''' master_queue = master_message['master_floor_up'][:] + master_message['master_floor_down'][:] print "master_queue: " + str(master_queue) #if master_id == MY_ID: # is_master = True master_id = master_message['master_id'] if last_master_id != master_id: changing_master = True if changing_master: my_master_queue = slave_driver.read_saved_master_queue() print "CHANGING MASTER STATE = TRUE -> my_master_queue: " + str(my_master_queue) message_handler.send_to_master(my_master_queue[0:4],my_master_queue[4:8],MY_ID,position[0],position[1],position[2],master_message['queue_id']) orders_ok = True for floor in range(0,N_FLOORS): if ((my_master_queue[floor] > 0) and (master_message['master_floor_up'][floor] == 0)) and ((my_master_queue[floor+4] > 0) and (master_message['master_floor_down'][floor] == 0)): orders_ok = False if orders_ok: is_master = False changing_master = False if not changing_master: slave_driver.master_queue_elevator_run(master_queue) #print ['floor_up:'] + master_message['master_floor_up'] + ['floor_down:'] + master_message['master_floor_down'] #print master_message['queue_id'] time.sleep(0.1) last_master_id = master_id