Created
January 20, 2017 21:07
-
-
Save willcharlton/2e148df68b3c666f3f8d762e4ab21eb9 to your computer and use it in GitHub Desktop.
Monitor Exosite Murano Solution Lua Websockets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
A simple client program for listening to a Murano Solution Websocket. | |
Author: Will Charlton | |
Company: Exosite | |
Date: 01/20/2017 | |
""" | |
import logging, websocket, threading, json, sys, time | |
logging.basicConfig() | |
LOG = logging.getLogger('websocket') | |
LOG.setLevel(logging.NOTSET) | |
class WSMon(threading.Thread): | |
def __init__(self, url): | |
super(WSMon, self).__init__(name = "WebsocketMonitor") | |
websocket.enableTrace(True) | |
self.url = url | |
self.wss = None | |
self.open_wss() | |
def open_wss(self): | |
self.wss = websocket.WebSocketApp( | |
self.url, | |
on_message = self.on_message, | |
on_error = self.on_error, | |
on_close = self.on_close | |
) | |
self.wss.on_open = self.on_open | |
LOG.warning("### Websocket Opened ###") | |
def on_message(self, wss, message): | |
""" | |
Dataport payload example: | |
{"payload":{"alias":"left","data":"som data that was written","did":"SOLUTION_ID.SERIAL_NUMBER","pid":"PRODUCT_ID","sn":"SERIAL_NUMBER","timestamp":"2017-01-17T20:30:29.000000000Z"},"type":"live_data"} | |
On Open example: | |
{"status":"ok","type":"open"} | |
""" | |
LOG.info("on_message: {}".format(message)) | |
data_from_solution = json.loads(message) | |
if data_from_solution.get('type') == "open": | |
LOG.debug("Nothing to do for websocket open event.") | |
elif data_from_solution.get('type') == "live_data": | |
LOG.info("VSMon: queuing {} : {}".format( | |
data_from_solution.get('payload').get('alias'), | |
data_from_solution.get('payload').get('data') | |
) | |
) | |
def on_error(self, wss, error): | |
LOG.info("on_error: {}".format(error)) | |
def on_close(self, wss): | |
LOG.warning("### Websocket Closed ###") | |
self.open_wss() | |
def on_open(self, wss): | |
LOG.warning("on_open: opened") | |
def react_to_open_event(): | |
LOG.critical("### Websocket Opened ###") | |
args=() | |
threading.Thread(name="on_open", target=react_to_open_event, args=args).start() | |
def run(self): | |
while True: | |
LOG.info("Starting...") | |
self.wss.run_forever() | |
LOG.warning("run_forever exited.") | |
time.sleep(0.5) | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
sys.stdout.write("usage: python {} <wss://murano.solution.io>\n".format(sys.argv[0])) | |
sys.exit(1) | |
sys.stdout.write("CNTL-z To Exit.\n") | |
time.sleep(1) | |
# now using websockets | |
ws_t = WSMon(sys.argv[1]) | |
ws_t.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment