Skip to content

Commit f0db51d

Browse files
committed
Adds logging, and an install script
Adds logging to the script so that it can display the date and timestamp. Also adds an install script to copy the appropriate files to the appropriate locations. It can be started/controlled by 'sudo service mythpywii restart', and should start on bootup. Also note that it restarts bluetooth. a bit distructive, but that's the best solution to me.
1 parent 0e5cab5 commit f0db51d

File tree

2 files changed

+52
-23
lines changed

2 files changed

+52
-23
lines changed

myth_py_wii.py

+29-23
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@
1616

1717
import cwiid, time, StringIO, sys, asyncore, socket, os
1818
import subprocess
19+
import logging
1920
from math import log, floor, atan, sqrt, cos, exp
21+
logger = logging.getLogger("mythpywii")
2022

2123
# Note to self - list of good documentation:
2224
# cwiid: http://flx.proyectoanonimo.com/proyectos/cwiid/
@@ -46,18 +48,16 @@ def __init__(self, owner, host="localhost"):
4648
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
4749
self.connect((host, 6546))
4850
def handle_close(self):
49-
print "Mythfrontend connection closed"
51+
logger.info("Mythfrontend connection closed")
5052
self.owner.socket_disconnect()
5153
self.close()
5254
def handle_read(self):
5355
try:
5456
self.data = self.data + self.recv(8192)
5557
except:
56-
print """
57-
[ERROR] The connection to Mythfrontend failed - is it running?
58-
If so, do you have the socket interface enabled?
59-
Please follow the instructions at http://www.benjiegillam.com/mythpywii-installation/
60-
"""
58+
logger.error("The connection to Mythfrontend failed - is it running?")
59+
logger.error("If so, do you have the socket interface enabled?")
60+
logger.error("Please follow the instructions at http://www.benjiegillam.com/mythpywii-installation/")
6161
self.handle_close()
6262
return
6363
while len(self.data)>0:
@@ -67,12 +67,12 @@ def handle_read(self):
6767
result = self.data[:a]
6868
self.data = self.data[a+len(self.prompt):]
6969
if not self.firstData:
70-
print ">>>", result
70+
logger.debug(">>> %s" % result)
7171
cb = self.callbacks.pop(0)
7272
if cb:
7373
cb(result)
7474
else:
75-
print "Logged in to MythFrontend"
75+
logger.info("Logged in to MythFrontend")
7676
self.firstData = False
7777
else:
7878
break;
@@ -81,7 +81,7 @@ def writable(self):
8181
def handle_write(self):
8282
a = self.buffer.find("\n")
8383
sent = self.send(self.buffer[:a+1])
84-
print "<<<", self.buffer[:sent-1]
84+
logger.debug("<<< %s" % self.buffer[:sent-1])
8585
self.buffer = self.buffer[sent:]
8686
self.oktosend = False
8787
def cmd(self, data, cb = None):
@@ -124,7 +124,7 @@ def wii_rel(self, v, axis):
124124
def socket_disconnect(self):
125125
if self.wm is not None:
126126
#self.wm.led = cwiid.LED2_ON | cwiid.LED3_ON
127-
print "About to close connection to the Wiimote"
127+
logger.info("About to close connection to the Wiimote")
128128
self.wm.close()
129129
self.wm = None
130130
return
@@ -133,7 +133,7 @@ def rumble(self,delay=0.2): # rumble unit - default = 0.2 seconds
133133
time.sleep(delay)
134134
self.wm.rumble=0
135135
def wmconnect(self):
136-
print "Please open Mythfrontend and then press 1&2 on the wiimote..."
136+
logger.info("Please open Mythfrontend and then press 1&2 on the wiimote...")
137137
try:
138138
self.wm = cwiid.Wiimote()
139139
except:
@@ -144,7 +144,7 @@ def wmconnect(self):
144144
return None
145145
if self.ms is None:
146146
self.ms = MythSocket(self, self.host)
147-
print "Connected to a wiimote :)"
147+
logger.info("Connected to a wiimote")
148148
self.lastaction = time.time()
149149
self.rumble()
150150
# Wiimote calibration data (cache this)
@@ -156,7 +156,7 @@ def wmcb(self, messages, extra=None):
156156
if message[0] == cwiid.MESG_BTN:
157157
state["buttons"] = message[1]
158158
#elif message[0] == cwiid.MESG_STATUS:
159-
# print "\nStatus: ", message[1]
159+
# logger.debug("\nStatus: ", message[1])
160160
elif message[0] == cwiid.MESG_ERROR:
161161
if message[1] == cwiid.ERROR_DISCONNECT:
162162
self.wm = None
@@ -165,11 +165,11 @@ def wmcb(self, messages, extra=None):
165165
self.ms = None
166166
continue
167167
else:
168-
print "ERROR: ", message[1]
168+
logger.error(message[1])
169169
elif message[0] == cwiid.MESG_ACC:
170170
state["acc"] = message[1]
171171
else:
172-
print "Unknown message!", message
172+
logger.warn("Unknown message! %s" % message)
173173
laststate = self.laststate
174174
if ('buttons' in laststate) and (laststate['buttons'] <> state['buttons']):
175175
if state['buttons'] == 0:
@@ -216,7 +216,7 @@ def wmcb(self, messages, extra=None):
216216
if (X>0): roll += 3.14159
217217
else: roll -= 3.14159
218218
pitch = atan(Y/Z*cos(roll))
219-
#print "X: %f, Y: %f, Z: %f; R: %f, P: %f; B: %d \r" % (X, Y, Z, roll, pitch, state["buttons"]),
219+
#logger.debug( "X: %f, Y: %f, Z: %f; R: %f, P: %f; B: %d \r" % (X, Y, Z, roll, pitch, state["buttons"])),
220220
sys.stdout.flush()
221221
if state["buttons"] & cwiid.BTN_B and state["buttons"] & cwiid.BTN_LEFT:
222222
self.ms.cmd('play seek beginning')
@@ -256,7 +256,7 @@ def wmcb(self, messages, extra=None):
256256
cmd += "key ,\n"
257257
if speed <> 0:
258258
cmd += "key "+str(abs(speed)-1)+"\n"
259-
#print cmd
259+
#logger.debug(cmd)
260260
elif laststate['BTN_B']<>speed:
261261
self.rumble(.05)
262262
if speed == 0:
@@ -297,20 +297,20 @@ def main(self):
297297
try:
298298
subprocess.call(['xset dpms force on'.split(' ')])
299299
except:
300-
print "Subrocess failed to call xset"
300+
logger.error("Subrocess failed to call xset")
301301
else:
302-
print "Forcing on the display"
302+
logger.info("Forcing on the display")
303303
else:
304-
print "Retrying... "
305-
print
304+
logger.warn("Retrying...")
305+
306306
asyncore.loop(timeout=0, count=1)
307307
if self.lastaction < time.time() - 2100:
308308
#2100 seconds is 35 minutes
309309
#1200 seconds is 20 minutes
310310
self.socket_disconnect()
311-
print "35 minutes has passed since last action, disconnecting Wiimote"
311+
logger.info("35 minutes has passed since last action, disconnecting Wiimote")
312312
time.sleep(0.05)
313-
print "Exited Safely"
313+
logger.info("Exited Safely")
314314

315315

316316
def readcfg(config):
@@ -348,6 +348,12 @@ def readcfg(config):
348348
dest="config", default=defaults['config'])
349349
(options, args) = parser.parse_args()
350350

351+
logger.setLevel(logging.DEBUG)
352+
handler = logging.StreamHandler()
353+
formatter = logging.Formatter("%(asctime)s - [%(levelname)s] %(funcName)s:%(lineno)s[%(process)d] - %(message)s")
354+
handler.setFormatter(formatter)
355+
logger.addHandler(handler)
356+
351357
myth_buttons = readcfg(options.config)
352358
inst = WiiMyth(options.mythtv, myth_buttons)
353359
inst.main()

mythpywii.conf

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# mythpywii - Start the daemon for the wii to connect to
2+
#
3+
4+
description "Start the daemon for the wii to connect to"
5+
6+
start on (local-filesystems
7+
and started dbus)
8+
stop on stopping dbus
9+
10+
script
11+
bluetooth_devices=$(lsusb |
12+
grep "Broadcom Corp. BCM2046B1 USB 2.0 Hub" |
13+
cut -d ':' -f 1 |
14+
sed -e 's/^Bus \([0-9]\{3\}\) Device \([0-9]\{3\}\)$/\/dev\/bus\/usb\/\1\/\2/')
15+
16+
for usb in $bluetooth_devices; do
17+
usbreset "$usb" | tee -a /var/log/mythpywii.log | logger
18+
done
19+
20+
# It takes a second for the bluetooth devices come back up. I wonder if there's a better way to watch them, and start the job then, instead.
21+
sleep 5
22+
python /usr/local/bin/myth_py_wii.py >> /var/log/mythpywii.log 2>&1
23+
end script

0 commit comments

Comments
 (0)