1 """WebSocket data receiver.
3 The tool receives and logs data from specified URI"""
5 # Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
7 # This program and the accompanying materials are made available under the
8 # terms of the Eclipse Public License v1.0 which accompanies this distribution,
9 # and is available at http://www.eclipse.org/legal/epl-v10.html
14 from websocket import create_connection
16 __author__ = "Radovan Sajben"
17 __copyright__ = "Copyright(c) 2016, Cisco Systems, Inc."
18 __license__ = "Eclipse Public License v1.0"
19 __email__ = "rsajben@cisco.com"
22 def parse_arguments():
23 """Use argparse to get arguments,
28 parser = argparse.ArgumentParser()
29 parser.add_argument("--uri", default="ws://127.0.0.1:8185/", help="URI to connect")
30 parser.add_argument("--count", type=int, default=1, help="Number of messages to receive")
31 parser.add_argument("--credentials", default="admin:admin", help="Basic authorization username:password")
32 parser.add_argument("--logfile", default="wsreceiver.log", help="Log file name")
33 parser.add_argument("--debug", dest="loglevel", action="store_const",
34 const=logging.DEBUG, default=logging.INFO, help="Log level")
35 args = parser.parse_args()
39 class WSReceiver(object):
40 """Class which receives web socket messages."""
42 def __init__(self, uri, credentials):
43 """Initialise and connect to URI.
46 :uri: uri to connect to
47 :credentials: user:password used in Basic Auth Header
52 self.credentials = credentials
53 auth_string = base64.b64encode(credentials.encode('ascii'))
55 'Authorization': 'Basic ' + auth_string.decode('ascii')
58 logger.info("Connecting to: %s", self.uri)
59 self.ws = create_connection(self.uri, header=self.headers)
62 """Close the connection.
69 logger.info("Disconnecting from: %s", self.uri)
78 :return: received data
81 logger.info("Data received:\n%s", data)
85 if __name__ == "__main__":
86 args = parse_arguments()
87 logger = logging.getLogger("logger")
88 log_formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
89 console_handler = logging.StreamHandler()
90 file_handler = logging.FileHandler(args.logfile, mode="w")
91 console_handler.setFormatter(log_formatter)
92 file_handler.setFormatter(log_formatter)
93 logger.addHandler(console_handler)
94 logger.addHandler(file_handler)
95 logger.setLevel(args.loglevel)
96 receiver = WSReceiver(args.uri, args.credentials)
98 logger.info("Expected %d message(s)", remains)
100 logger.info("Waiting for a message ...")
101 data = receiver.receive()
103 logger.info("Remaining messages to receive: %d", remains)
104 logger.info("Finished ...")