コード例 #1
0
class WSGIServer(_WSGIServer):
    def initialize_websockets_manager(self):
        """
        Call thos to start the underlying websockets
        manager. Make sure to call it once your server
        is created.
        """
        self.manager = WebSocketManager()
        self.manager.start()

    def shutdown_request(self, request):
        """
        The base class would close our socket
        if we didn't override it.
        """
        pass

    def link_websocket_to_server(self, ws):
        """
        Call this from your WSGI handler when a websocket
        has been created.
        """
        self.manager.add(ws)

    def server_close(self):
        """
        Properly initiate closing handshakes on
        all websockets when the WSGI server terminates.
        """
        if hasattr(self, 'manager'):
            self.manager.close_all()
            self.manager.stop()
            self.manager.join()
            delattr(self, 'manager')
        _WSGIServer.server_close(self)
コード例 #2
0
    def test_mainloop_can_be_stopped_when_no_websocket_were_registered(self, MockSelectPoller):
        m = WebSocketManager(poller=MockSelectPoller())
        self.assertFalse(m.running)
        
        m.start()
        self.assertTrue(m.running)

        m.stop()
        self.assertFalse(m.running)
コード例 #3
0
    def test_mainloop_can_be_stopped_when_no_websocket_were_registered(
            self, MockSelectPoller):
        m = WebSocketManager(poller=MockSelectPoller())
        self.assertFalse(m.running)

        m.start()
        self.assertTrue(m.running)

        m.stop()
        self.assertFalse(m.running)
コード例 #4
0
    def test_websocket_terminated_from_mainloop(self, MockSelectPoller):
        m = WebSocketManager(poller=MockSelectPoller())
        m.poller.poll.return_value = [1]

        ws = MagicMock()
        
        ws.terminated = False
        ws.sock.fileno.return_value = 1
        ws.once.return_value = False
        
        m.add(ws)
        m.start()
        
        ws.terminate.assert_call_once_with()
        
        m.stop()
コード例 #5
0
    def test_websocket_terminated_from_mainloop(self, MockSelectPoller):
        m = WebSocketManager(poller=MockSelectPoller())
        m.poller.poll.return_value = [1]

        ws = MagicMock()

        ws.terminated = False
        ws.sock.fileno.return_value = 1
        ws.once.return_value = False

        m.add(ws)
        m.start()

        ws.terminate.assert_call_once_with()

        m.stop()
コード例 #6
0
class WebSocketPlugin(plugins.SimplePlugin):
    def __init__(self, bus):
        plugins.SimplePlugin.__init__(self, bus)
        self.manager = WebSocketManager()

    def start(self):
        self.bus.log("Starting WebSocket processing")
        self.bus.subscribe('stop', self.cleanup)
        self.bus.subscribe('handle-websocket', self.handle)
        self.bus.subscribe('websocket-broadcast', self.broadcast)
        self.manager.start()

    def stop(self):
        self.bus.log("Terminating WebSocket processing")
        self.bus.unsubscribe('stop', self.cleanup)
        self.bus.unsubscribe('handle-websocket', self.handle)
        self.bus.unsubscribe('websocket-broadcast', self.broadcast)

    def handle(self, ws_handler, peer_addr):
        """
        Tracks the provided handler.

        :param ws_handler: websocket handler instance
        :param peer_addr: remote peer address for tracing purpose
        """
        self.manager.add(ws_handler)

    def cleanup(self):
        """
        Terminate all connections and clear the pool. Executed when the engine stops.
        """
        self.manager.close_all()
        self.manager.stop()
        self.manager.join()

    def broadcast(self, message, binary=False):
        """
        Broadcasts a message to all connected clients known to
        the server.

        :param message: a message suitable to pass to the send() method
          of the connected handler.
        :param binary: whether or not the message is a binary one
        """
        self.manager.broadcast(message, binary)
コード例 #7
0
class WebSocketPlugin(plugins.SimplePlugin):
    def __init__(self, bus):
        plugins.SimplePlugin.__init__(self, bus)
        self.manager = WebSocketManager()

    def start(self):
        self.bus.log("Starting WebSocket processing")
        self.bus.subscribe('stop', self.cleanup)
        self.bus.subscribe('handle-websocket', self.handle)
        self.bus.subscribe('websocket-broadcast', self.broadcast)
        self.manager.start()

    def stop(self):
        self.bus.log("Terminating WebSocket processing")
        self.bus.unsubscribe('stop', self.cleanup)
        self.bus.unsubscribe('handle-websocket', self.handle)
        self.bus.unsubscribe('websocket-broadcast', self.broadcast)

    def handle(self, ws_handler, peer_addr):
        """
        Tracks the provided handler.

        :param ws_handler: websocket handler instance
        :param peer_addr: remote peer address for tracing purpose
        """
        self.manager.add(ws_handler)

    def cleanup(self):
        """
        Terminate all connections and clear the pool. Executed when the engine stops.
        """
        self.manager.close_all()
        self.manager.stop()
        self.manager.join()

    def broadcast(self, message, binary=False):
        """
        Broadcasts a message to all connected clients known to
        the server.

        :param message: a message suitable to pass to the send() method
          of the connected handler.
        :param binary: whether or not the message is a binary one
        """
        self.manager.broadcast(message, binary)
コード例 #8
0
def run(script_options):
    global logger
    level  = logging.DEBUG if script_options.verbose else logging.INFO
    logger = configure_logger(level = level)

    mgr = WebSocketManager()

    try:
        mgr.start()
        clients = []

        # Connect
        for connection_idx in range(script_options.concurrency):
            client = EchoClient(script_options.url, mgr,
                                script_options.ca, script_options.key, script_options.cert)
            client.connect()
            clients.append(client)

        logger.info("%d clients are connected" % (connection_idx + 1))

        # Send
        msg = getMessage(script_options)
        if msg:
            msg = json.write(msg)
            logger.info("Sending messages (num=%d):\n%s", script_options.num, msg)
            for client in clients:
                for _ in range(script_options.num):
                    client.send(msg)
                    time.sleep(SEND_INTERVAL)
            logger.info("Done sending")

        # Sleep before disconnecting
        logger.info("Sleeping for %d s before disconnecting",
                    script_options.interval)
        time.sleep(script_options.interval)

    except KeyboardInterrupt:
        logger.info("Interrupted by user")
    finally:
        logger.info("Disconnecting!")
        mgr.close_all(code    = 1000,
                      message = "Client is closing the connection")
        mgr.stop()
        mgr.join()
コード例 #9
0
class PushBulletWSClient(WebSocketBaseClient):

    def init(self, interface):
        """ Initializes the PB WS Client"""

        self.logger = logging.getLogger('PAI').getChild(__name__)
        self.pb = Pushbullet(cfg.PUSHBULLET_KEY, cfg.PUSHBULLET_SECRET)
        self.manager = WebSocketManager()
        self.alarm = None
        self.interface = interface

    def stop(self):
        self.terminate()
        self.manager.stop()

    def set_alarm(self, alarm):
        """ Sets the paradox alarm object """
        self.alarm = alarm

    def handshake_ok(self):
        """ Callback trigger when connection succeeded"""
        self.logger.info("Handshake OK")
        self.manager.add(self)
        self.manager.start()
        for chat in self.pb.chats:
            self.logger.debug("Associated contacts: {}".format(chat))

        # Receiving pending messages
        self.received_message(json.dumps({"type": "tickle", "subtype": "push"}))

        self.send_message("Active")

    def received_message(self, message):
        """ Handle Pushbullet message. It should be a command """
        self.logger.debug("Received Message {}".format(message))

        try:
            message = json.loads(str(message))
        except:
            self.logger.exception("Unable to parse message")
            return

        if self.alarm is None:
            return
        if message['type'] == 'tickle' and message['subtype'] == 'push':
            now = time.time()
            pushes = self.pb.get_pushes(modified_after=int(now) - 20, limit=1, filter_inactive=True)
            self.logger.debug("got pushes {}".format(pushes))
            for p in pushes:
                self.pb.dismiss_push(p.get("iden"))
                self.pb.delete_push(p.get("iden"))

                if p.get('direction') == 'outgoing' or p.get('dismissed'):
                    continue

                if p.get('sender_email_normalized') in cfg.PUSHBULLET_CONTACTS:
                    ret = self.interface.send_command(p.get('body'))

                    if ret:
                        self.logger.info("From {} ACCEPTED: {}".format(p.get('sender_email_normalized'), p.get('body')))
                    else:
                        self.logger.warning("From {} UNKNOWN: {}".format(p.get('sender_email_normalized'), p.get('body')))
                else:
                    self.logger.warning("Command from INVALID SENDER {}: {}".format(p.get('sender_email_normalized'), p.get('body')))

    def unhandled_error(self, error):
        self.logger.error("{}".format(error))

        try:
            self.terminate()
        except Exception:
            self.logger.exception("Closing Pushbullet WS")

        self.close()

    def send_message(self, msg, dstchat=None):
        if dstchat is None:
            dstchat = self.pb.chats

        if not isinstance(dstchat, list):
            dstchat = [dstchat]

        for chat in dstchat:
            if chat.email in cfg.PUSHBULLET_CONTACTS:
                try:
                    self.pb.push_note("paradox", msg, chat=chat)
                except Exception:
                    self.logger.exception("Sending message")
                    time.sleep(5)

    def notify(self, source, message, level):
        try:
            if level.value >= EventLevel.WARN.value:
                self.send_message("{}".format(message))
        except Exception:
            logging.exception("Pushbullet notify")
コード例 #10
0
ファイル: pushbullet.py プロジェクト: lsta/pai
class PushBulletWSClient(WebSocketBaseClient):
    name = "pushbullet"

    def __init__(self, interface, url):
        """ Initializes the PB WS Client"""
        super().__init__(url)

        self.pb = Pushbullet(cfg.PUSHBULLET_KEY)
        self.manager = WebSocketManager()
        self.interface = interface

        self.device = None
        for i, device in enumerate(self.pb.devices):
            if device.nickname == 'pai':
                logger.debug("Device found")
                self.device = device
                break
        else:
            logger.exception("Device not found. Creating 'pai' device")
            self.device = self.pb.new_device(nickname='pai', icon='system')

    def stop(self):
        self.terminate()
        self.manager.stop()

    def handshake_ok(self):
        """ Callback trigger when connection succeeded"""
        logger.info("Handshake OK")
        self.manager.add(self)
        self.manager.start()
        for chat in self.pb.chats:
            logger.debug("Associated contacts: {}".format(chat))

        # Receiving pending messages
        self.received_message(json.dumps({
            "type": "tickle",
            "subtype": "push"
        }))

        self.send_message("Active")

    def received_message(self, message):
        """ Handle Pushbullet message. It should be a command """
        logger.debug("Received Message {}".format(message))

        try:
            message = json.loads(str(message))
        except:
            logger.exception("Unable to parse message")
            return

        if message['type'] == 'tickle' and message['subtype'] == 'push':
            now = time.time()
            pushes = self.pb.get_pushes(modified_after=int(now) - 20,
                                        limit=1,
                                        filter_inactive=True)
            for p in pushes:

                # Ignore messages send by us
                if p.get('direction') == 'self' and p.get('title') == 'pai':
                    #logger.debug('Ignoring message sent')
                    continue

                if p.get('direction') == 'outgoing' or p.get('dismissed'):
                    #logger.debug('Ignoring outgoing dismissed')
                    continue

                if p.get('sender_email_normalized'
                         ) in cfg.PUSHBULLET_CONTACTS or p.get(
                             'direction') == 'self':
                    ret = self.interface.handle_command(p.get('body'))

                    m = "PB {}: {}".format(p.get('sender_email_normalized'),
                                           ret)
                    logger.info(m)
                else:
                    m = "PB {} (UNK): {}".format(
                        p.get('sender_email_normalized'), p.get('body'))
                    logger.warning(m)

                self.send_message(m)
                ps.sendNotification(
                    Notification(sender=self.name,
                                 message=m,
                                 level=EventLevel.INFO))

    def unhandled_error(self, error):
        logger.error("{}".format(error))

        try:
            self.terminate()
        except Exception:
            logger.exception("Closing Pushbullet WS")

        self.close()

    def send_message(self, msg, dstchat=None):
        if dstchat is None:
            dstchat = self.pb.chats

        if not isinstance(dstchat, list):
            dstchat = [dstchat]
        # Push to self
        self.device.push_note("pai", msg)

        for chat in dstchat:
            if chat.email in cfg.PUSHBULLET_CONTACTS:
                try:
                    self.pb.push_note("pai", msg, chat=chat)
                except Exception:
                    logger.exception("Sending message")
                    time.sleep(5)
コード例 #11
0
def start_data_collection(conn_info):
	for (ip, port) in conn_info:
		ws_url = "ws://{}:{}/geophone".format(ip, port)
		print("Connecting to '{}'...".format(ws_url))

		try:
			ws = DataReceiver(ws_url)
			ws.connect()
		except Exception as e:
			print("Unable to connect to '{}' (it probably timed out after {}s). Reason: {}".format(ws_url, WS_TIMEOUT, e))


if __name__ == '__main__':
	try:
		ws_manager.start()
		# start_data_collection([('10.0.0.110', 81)])
		start_data_collection([('192.168.0.99', 81),('192.168.0.100', 81),('192.168.0.105', 81),('192.168.0.108', 81),('192.168.0.109', 81),('192.168.0.114', 81),('192.168.0.115', 81),('192.168.0.116', 81),('192.168.0.117', 81),('192.168.0.118', 81)])

		while True:
			for ws in ws_manager.websockets.itervalues():
				if not ws.terminated:
					break
			else:
				break
			time.sleep(3)
	except KeyboardInterrupt:
		ws_manager.close_all()
		ws_manager.stop()
		ws_manager.join()
コード例 #12
0
if __name__ == '__main__':
    import time
    Instant_Pending = json.dumps(CreateData())
    count = 0
    try:
        m.start()
        start_time = time.time()
        for i in user_list:
            payload = json.dumps({"Type": 7, "Data": i})
            print(type(payload))
            client = EchoClient(api_url)
            client.connect()
            count += 1
        logger.info("%s clients are connected" % count)

        while True:
            for ws in m.websockets.values():
                if not ws.terminated:
                    dur_time = time.time() - start_time
                    print(dur_time)
                    break
            else:
                break
            time.sleep(3)

    except KeyboardInterrupt:
        m.close_all()
        m.stop()
        m.join()
コード例 #13
0
            #PORTFOLIO DISPLAY
            print("Total Portfolio in USD : ${0:>.4f}".format(
                total_portfolio_val))

            print()
            print("Next High Alert Text: {}".format(ALERT_PRICE_HIGH))
            print("Next Low Alert Text: {}".format(ALERT_PRICE_LOW))

            if ALERT_PRICE_HIGH is not -1 and total_val >= ALERT_PRICE_HIGH:
                sms_client.send_sms(
                    "\nYour portfolio has reached {0}.\nNext high text notification set to: {1}"
                    .format(ALERT_PRICE_HIGH,
                            ALERT_UPDATE_VAL + ALERT_PRICE_HIGH))
                ALERT_PRICE_HIGH += ALERT_UPDATE_VAL
                ALERT_PRICE_LOW += ALERT_UPDATE_VAL
            elif ALERT_PRICE_LOW is not -1 and abs(
                    total_val - ALERT_PRICE_LOW
            ) >= (1.2 * ALERT_UPDATE_VAL) and ALERT_PRICE_LOW >= total_val:
                sms_client.send_sms(
                    "\nYour portfolio has dropped to {0}.\nNext low text notification set to: {1}"
                    .format(ALERT_PRICE_LOW,
                            ALERT_PRICE_LOW - ALERT_UPDATE_VAL))
                ALERT_PRICE_HIGH -= ALERT_UPDATE_VAL
                ALERT_PRICE_LOW -= ALERT_UPDATE_VAL
            time.sleep(1)

    except KeyboardInterrupt:
        MANAGER.close_all()
        MANAGER.stop()
        MANAGER.join()
コード例 #14
0
ファイル: client.py プロジェクト: Tairy/zaihuitou
        for pin in pins:
            gpio.pinMode(pin, gpio.OUTPUT)
            gpio.digitalWrite(pin,int(pins[pin]))

def tempread(pin):
    value = analog_read(pin)
    tempr = (value * 3.3)/4096*100
    return tempr

if __name__ == '__main__':
    import time

    try:
        m.start()
        client = EchoClient('ws://tairy.me:8888/ws')
        client.connect()

        sendmes = {"userid":userid}
        while True:
            for ws in m.websockets.itervalues():
                if not ws.terminated:
                    sendmes["data"] = {"temp":tempread(2)}
                    ws.send(json.JSONEncoder().encode(sendmes))
                    break
            else:
                break
            time.sleep(3)
    except KeyboardInterrupt:
        m.close_all()
        m.stop()
        m.join()