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")
31 "--count", type=int, default=1, help="Number of messages to receive"
35 default="admin:admin",
36 help="Basic authorization username:password",
38 parser.add_argument("--logfile", default="wsreceiver.log", help="Log file name")
47 args = parser.parse_args()
51 class WSReceiver(object):
52 """Class which receives web socket messages."""
54 def __init__(self, uri, credentials):
55 """Initialise and connect to URI.
58 :uri: uri to connect to
59 :credentials: user:password used in Basic Auth Header
64 self.credentials = credentials
65 auth_string = base64.b64encode(credentials.encode("ascii"))
66 self.headers = {"Authorization": "Basic " + auth_string.decode("ascii")}
68 logger.info("Connecting to: %s", self.uri)
69 self.ws = create_connection(self.uri, header=self.headers)
72 """Close the connection.
79 logger.info("Disconnecting from: %s", self.uri)
88 :return: received data
91 logger.info("Data received:\n%s", data)
95 if __name__ == "__main__":
96 args = parse_arguments()
97 logger = logging.getLogger("logger")
98 log_formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
99 console_handler = logging.StreamHandler()
100 file_handler = logging.FileHandler(args.logfile, mode="w")
101 console_handler.setFormatter(log_formatter)
102 file_handler.setFormatter(log_formatter)
103 logger.addHandler(console_handler)
104 logger.addHandler(file_handler)
105 logger.setLevel(args.loglevel)
106 receiver = WSReceiver(args.uri, args.credentials)
108 logger.info("Expected %d message(s)", remains)
110 logger.info("Waiting for a message ...")
111 data = receiver.receive()
113 logger.info("Remaining messages to receive: %d", remains)
114 logger.info("Finished ...")