Using Websockets in Python NGRE, e.g. connect to Hue Bridge

Tags: #<Tag:0x00007f616b9f91c8> #<Tag:0x00007f616b9f8e58> #<Tag:0x00007f616b9f8c50>

The Staring Point
I am working on extended Hue Bridge support (Groups, Scenes, sensors, etc) and I was keen to find out what are the possibilities to use WebSockets inside JRS223 in order to connect to Hue Bridge WebSocket and get the events pushed back to my rules.

The Solution

First install websocket-client:

sudo pip install --upgrade --target=/datavol/openhab-2.5.3/openhab_conf/automation/lib/python websocket-client==0.7.0

change the path /datavol/openhab-2.5.3/openhab_conf/automation to your location of the automation directory.

Here the sample script. It is not a rule, though it can be part of a rule file.

This script sends 3 times a “Hello” to echo.websocket.org which echos this message.

from core.log import logging, LOG_PREFIX
log = logging.getLogger(LOG_PREFIX + ".hello.log")      

import websocket
try:
    import thread
except ImportError:
    import _thread as thread 
import time 

def scriptUnloaded():
    try:
        log.info("************* Unload WS test  ********* ")   
        if ws != None:  
            ws.close() 
    except Exception, e: 
        log.info("WS test __init___() scriptUnloaded: {}".format(e))

def on_message(ws, message):
    log.info(message)

def on_error(ws, error):
    log.info(error) 

def on_close(ws):
    log.info("### closed ###")

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        log.info("thread terminating...")
    thread.start_new_thread(run, ())


websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                            on_message = on_message,
                            on_error = on_error,
                            on_close = on_close)
ws.on_open = on_open
thread.start_new_thread(lambda: ws.run_forever(), ())

Just in case somebody needs a WebSocket server

Install websocket

pip install simple-websocket-server  --upgrade --target=/datavol/openhab-2.5.3/openhab_conf/automation/lib/python

And the sample code:

from simple_websocket_server import WebSocketServer, WebSocket
try:
    import thread
except ImportError:
    import _thread as thread
import time

from core.log import logging, LOG_PREFIX

log = logging.getLogger(LOG_PREFIX + ".wsserver.log") 

def scriptUnloaded():
    server.close()                    


class SimpleEcho(WebSocket):
    def handle(self):
        # echo message back to client
        self.send_message(self.data)

    def connected(self):
        log.info("Adresse: {} {}".format(self.address, 'connected'))

    def handle_close(self):
        log.info("Adresse: {} {}".format(self.address, 'closed'))


server = WebSocketServer('', 9999, SimpleEcho)

thread.start_new_thread(lambda: server.serve_forever(), ()) 

change the above WebSocket client to:

ws = websocket.WebSocketApp("ws://localhost:9999/",
                            on_message = on_message,
                            on_error = on_error,
                            on_close = on_close)

and the two will talk to each other

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.