Skip to content

Commit 090174d

Browse files
committed
adding some example: a chat simple demo and an android based sensor dispatcher
1 parent a140c16 commit 090174d

2 files changed

Lines changed: 165 additions & 0 deletions

File tree

example/droid_sensor.py

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# -*- coding: utf-8 -*-
2+
__doc__ = """
3+
WebSocket client that pushes Android sensor metrics to the
4+
websocket server it is connected to.
5+
6+
In order to set this up:
7+
8+
1. Install SL4A http://code.google.com/p/android-scripting/
9+
2. Install the Python package for SL4A
10+
3. Build ws4py and copy the package built into a directory
11+
called com.googlecode.pythonforandroid/extras/python on
12+
your Android device.
13+
4. a. Either copy the droid_sensor.py module into the directory
14+
called sl4a/scripts on your Android device.
15+
b. Or set up the remote control so that you can run the
16+
module from your computer directly on your device:
17+
http://code.google.com/p/android-scripting/wiki/RemoteControl
18+
5. Setup the device so that it has an IP address on the same
19+
network as the computer running the server.
20+
21+
Run the example:
22+
23+
1. Start the echo_cherrypy_server module:
24+
$ python example/echo_cherrypy_server.py
25+
2. From a local browser, go to:
26+
http://localhost:9000/
27+
3. Edit the droid_sensor module to set the appropriate
28+
IP address where your server is running.
29+
4. Run the droid_sensor module (from the device or
30+
your computer depending on your setup):
31+
$ python example/droid_sensor.py
32+
5. If your device isn't idled, just move ir around
33+
for the metrics to be sent to the server which
34+
will dispatch them to the browser's client.
35+
6. Profit???
36+
37+
"""
38+
import time
39+
import math
40+
41+
import android
42+
from ws4py.client.threadedclient import WebSocketClient
43+
44+
class AirPongSensor(object):
45+
def __init__(self, host):
46+
self.droid = android.Android()
47+
#self.droid.startSensingThreshold(1, 0, 7)
48+
#self.droid.startSensingThreshold(2, 1, 2)
49+
self.droid.startSensingTimed(1, 500)
50+
51+
self.running = False
52+
53+
self.client = AirPongWebSocketClient(host)
54+
self.client.connect()
55+
56+
def run(self):
57+
try:
58+
self.running = True
59+
last = [None, None, None]
60+
while self.running:
61+
azimuth, pitch, roll = self.droid.sensorsReadOrientation().result
62+
accel = x, y, z = self.droid.sensorsReadAccelerometer().result
63+
if azimuth is None:
64+
continue
65+
66+
c = lambda rad: rad * 360.0 / math.pi
67+
print c(azimuth), c(pitch), c(roll), x, y, z
68+
69+
if self.client.terminated:
70+
break
71+
72+
if accel != [None, None, None] and accel != last:
73+
last = accel
74+
self.client.send("%s %s %s %s %s %s" % (c(azimuth), c(pitch), c(roll), x, y, z))
75+
76+
time.sleep(1)
77+
finally:
78+
self.terminate()
79+
80+
def terminate(self):
81+
if not self.droid:
82+
return
83+
84+
self.running = False
85+
self.droid.stopSensing()
86+
self.droid = None
87+
88+
if not self.client.terminated:
89+
self.client.close()
90+
self.client._th.join()
91+
self.client = None
92+
93+
class AirPongWebSocketClient(WebSocketClient):
94+
def received_message(self, m):
95+
print m, len(str(m))
96+
97+
if __name__ == '__main__':
98+
aps = AirPongSensor(host='http://192.168.0.10:9000/ws')
99+
try:
100+
aps.run()
101+
except KeyboardInterrupt:
102+
aps.terminate()

example/echo_cherrypy_server.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# -*- coding: utf-8 -*-
2+
import random
3+
4+
import cherrypy
5+
6+
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
7+
from ws4py.server.handler.threadedhandler import WebSocketHandler, EchoWebSocketHandler
8+
9+
class ChatWebSocketHandler(WebSocketHandler):
10+
def received_message(self, m):
11+
cherrypy.engine.publish('websocket-broadcast', str(m))
12+
13+
class Root(object):
14+
@cherrypy.expose
15+
def index(self):
16+
return """<html>
17+
<head>
18+
<script type='application/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'> </script>
19+
<script type='application/javascript'>
20+
$(document).ready(function() {
21+
var ws = new WebSocket('ws://localhost:9000/ws');
22+
ws.onmessage = function (evt) {
23+
$('#chat').val($('#chat').val() + evt.data + '\\n');
24+
};
25+
ws.onopen = function() {
26+
ws.send("%(username)s entered the room");
27+
};
28+
$('#chatform').submit(function() {
29+
ws.send('%(username)s: ' + $('#message').val());
30+
$('#message').val("");
31+
return false;
32+
});
33+
});
34+
</script>
35+
</head>
36+
<body>
37+
<form action='/echo' id='chatform' method='get'>
38+
<textarea id='chat' cols='35' rows='10'></textarea>
39+
<br />
40+
<label for='message'>%(username)s: </label><input type='text' id='message' />
41+
<input type='submit' value='Send' />
42+
</form>
43+
</body>
44+
</html>
45+
""" % {'username': "User%d" % random.randint(0, 100)}
46+
47+
@cherrypy.expose
48+
def ws(self):
49+
cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler))
50+
51+
if __name__ == '__main__':
52+
cherrypy.config.update({'server.socket_host': '0.0.0.0',
53+
'server.socket_port': 9000})
54+
WebSocketPlugin(cherrypy.engine).subscribe()
55+
cherrypy.tools.websocket = WebSocketTool()
56+
57+
cherrypy.quickstart(Root(), '', config={
58+
'/ws': {
59+
'tools.websocket.on': True,
60+
'tools.websocket.handler_cls': ChatWebSocketHandler
61+
}
62+
}
63+
)

0 commit comments

Comments
 (0)