HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Websocket-based server for Raspberry Pi

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
raspberryforbasedwebsocketserver

Problem

I am trying to build a websocket server to run on the Raspberry Pi. The websocket server has to push periodic realtime update to a browser. Here is a sample code that I am planning to use. The example code here sends the current time instead of sensor data.

Most of the code is built form an example. However, what I need feedback on is

  • The way stpoll is coded (sensor status poll)



  • The global variable that passes the message to terminate the thread. I don't like it. Is there a better way to terminate a task that runs forever?



  • The way the time (sensor data) is broadcasted to all connected clients. (another global variable)



I had to code this without much documentation.

```
# -- coding: utf-8 --
import argparse
import random
import os
import time
import threading
import signal
import sys

import cherrypy

from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import WebSocket
from ws4py.messaging import TextMessage

class ChatWebSocketHandler(WebSocket):
def received_message(self, m):
cherrypy.engine.publish('websocket-broadcast', m)

def closed(self, code, reason="A client left the room without a proper explanation."):
cherrypy.engine.publish('websocket-broadcast', TextMessage(reason))

class Root(object):
def __init__(self, host, port, ssl=False):
self.host = host
self.port = port
self.scheme = 'wss' if ssl else 'ws'

@cherrypy.expose
def index(self):
return """



$(document).ready(function() {
websocket = '%(scheme)s://%(host)s:%(port)s/ws';
if (window.WebSocket) {
ws = new WebSocket(websocket);
}
else if (window.MozWebSocket) {
ws = MozWebSocket(websocket);
}
else {
console.log('WebSocket Not Supported');
return;
}
window.onbeforeunload = function(e) {
$('#chat').val($('#chat').val() +

Solution

Your code is nice, but it could use a few changes:

  • % {}: rather than using that formatting method, you should use the string.format() method, involving {0} {1} instead of % as it is recommended by PEP8, Python's official style guide.



  • print "exitting therad": both exiting and thread are spelt incorrectly



  • global pollStatus: you shouldn't be naming your variables like camelCase, rather snake_case instead, as also expressed by PEP8



  • tm=time.localtime(): you should have whitespace between your binary operators, and also you shouldn't abbreviate your variables like tm: local_time would be much better.



Other than that, your code looks nice, well done!

Context

StackExchange Code Review Q#79161, answer score: 2

Revisions (0)

No revisions yet.