Looks quite nice!
I've been working on something similar, though I have been focusing more on getting the specific things I need for my project working and not on creating a complete wrapper like you have. I did things a bit differently--I created classes HeartThread and ListenerThread, for example, instead of functions that need to be called as the target of a thread.
I've been sort of hacking this code together with no regard for style guidelines, but in the next few weeks I intend to clean it up and post it here.
In the mean time, I'm curious--why don't you use the json.dumps function in your connection.create_json method? I have this function, for example:
- Code: Select all
def send_message(self, category, request=None, values=None):
'''returns the reply in a dict'''
to_send = {}
to_send[u'category'] = category
if request is not None:
to_send[u'request'] = request
if values is not None:
to_send[u'values'] = values
to_send = json.dumps(to_send)
with self.lock:
self.socket.send(to_send)
reply = self.socket.recv(BUFSIZE)
return json.loads(reply)
I'm also using a threading.Lock() object, which is self.lock in the code above, for thread safety. I kept receiving heartbeat replies when I was trying to retrieve frame data before I added that. here's my HeartThread class (excuse the lack of documentation--will add it soon):
- Code: Select all
class HeartThread(threading.Thread):
def __init__(self, et_socket, socket_lock):
super(HeartThread, self).__init__()
self._stop = threading.Event()
self.socket = et_socket
self.lock = socket_lock
def stop(self):
self._stop.set()
def run(self, interval=0.250):
while not self._stop.is_set():
with self.lock:
self.socket.send('{"category":"heartbeat"}')
logging.debug('Heartbeat reply: {}'.format(self.socket.recv(BUFSIZE)))
sleep(interval)
# example call
heart_thr = HeartThread(self.socket, self.lock)
heart_thr.run()