From 7f56a04919f9f81dd802a8295263f497570e7910 Mon Sep 17 00:00:00 2001 From: Walter Bender Date: Wed, 23 Feb 2011 03:28:18 +0000 Subject: unified debug output --- diff --git a/TurtleArt/tablock.py b/TurtleArt/tablock.py index 3db3e6e..463784a 100644 --- a/TurtleArt/tablock.py +++ b/TurtleArt/tablock.py @@ -40,8 +40,7 @@ from taconstants import EXPANDABLE, EXPANDABLE_BLOCKS, EXPANDABLE_ARGS, \ from tasprite_factory import SVG, svg_str_to_pixbuf import sprites -import logging -_logger = logging.getLogger('turtleart-activity') +from tautils import debug_output class Blocks: @@ -382,7 +381,8 @@ class Block: if self.name in BLOCK_NAMES: n = len(BLOCK_NAMES[self.name]) else: - _logger.debug('WARNING: unknown block name %s' % (self.name)) + debug_output('WARNING: unknown block name %s' % (self.name), + self.tw.running_sugar) n = 0 for i in range(n): if i == 1: # top @@ -483,8 +483,8 @@ class Block: self._make_portfolio_style_1x2(svg) else: self._make_basic_style(svg) - _logger.debug("WARNING: I don't know how to create a %s block" % \ - (self.name)) + debug_output("WARNING: I don't know how to create a %s block" % \ + (self.name), self.tw.running_sugar) def _set_colors(self, svg): if self.name in BOX_COLORS: diff --git a/TurtleArt/tacanvas.py b/TurtleArt/tacanvas.py index 79bdd04..cf1eb85 100644 --- a/TurtleArt/tacanvas.py +++ b/TurtleArt/tacanvas.py @@ -28,12 +28,10 @@ import base64 from sprites import Sprite from tasprite_factory import SVG -from tautils import image_to_base64, get_path, data_to_string, round_int +from tautils import image_to_base64, get_path, data_to_string, round_int, \ + debug_output from taconstants import CANVAS_LAYER, BLACK, WHITE -import logging -_logger = logging.getLogger('turtleart-activity') - def wrap100(n): """ A variant on mod... 101 -> 99; 199 -> 1 """ @@ -223,7 +221,8 @@ class TurtleGraphics: self.xcor += nn * sin(self.heading * DEGTOR) self.ycor += nn * cos(self.heading * DEGTOR) except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return if self.pendown: self.draw_line(oldx, oldy, self.xcor, self.ycor) @@ -244,7 +243,8 @@ class TurtleGraphics: try: self.heading = n except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return self.heading %= 360 self.turn_turtle() @@ -258,7 +258,8 @@ class TurtleGraphics: try: self.heading += n except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return self.heading %= 360 self.turn_turtle() @@ -277,7 +278,8 @@ class TurtleGraphics: else: self.rarc(a, rr) except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return self.move_turtle() if self.tw.sharing() and share: @@ -360,7 +362,8 @@ class TurtleGraphics: try: self.xcor, self.ycor = x, y except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return if self.pendown and pendown: @@ -380,7 +383,8 @@ class TurtleGraphics: ps = 0 self.pensize = ps except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return self.tw.active_turtle.set_pen_size(ps) self.gc.set_line_attributes(int(self.pensize * self.tw.coord_scale), @@ -397,7 +401,8 @@ class TurtleGraphics: self.color = c self.tcolor = c except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return self.tw.active_turtle.set_color(c) self.set_fgcolor() @@ -412,7 +417,8 @@ class TurtleGraphics: try: self.gray = g except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return if self.gray < 0: self.gray = 0 @@ -431,7 +437,8 @@ class TurtleGraphics: try: self.tcolor = c except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return self.set_textcolor() @@ -440,14 +447,16 @@ class TurtleGraphics: try: self.tw.textsize = c except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) def setshade(self, s, share=True): """ Set the color shade """ try: self.shade = s except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return self.tw.active_turtle.set_shade(s) self.set_fgcolor() @@ -556,7 +565,8 @@ class TurtleGraphics: try: fd.set_size(int(size * self.tw.coord_scale) * pango.SCALE) except TypeError, ValueError: - _logger.debug("bad value sent to %s" % (__name__)) + debug_output("bad value sent to %s" % (__name__), + self.tw.running_sugar) return if self.tw.interactive_mode: if type(label) == str or type(label) == unicode: diff --git a/TurtleArt/tacollaboration.py b/TurtleArt/tacollaboration.py index d4b7529..3a5bd17 100644 --- a/TurtleArt/tacollaboration.py +++ b/TurtleArt/tacollaboration.py @@ -21,14 +21,13 @@ from dbus.service import signal from dbus.gobject_service import ExportedGObject -import logging import telepathy import gtk import base64 from TurtleArt.tautils import data_to_string, data_from_string, get_path, \ - base64_to_image + base64_to_image, debug_output, error_output from TurtleArt.taconstants import DEFAULT_TURTLE_COLORS try: @@ -43,7 +42,6 @@ except: SERVICE = 'org.laptop.TurtleArtActivity' IFACE = SERVICE PATH = '/org/laptop/TurtleArtActivity' -_logger = logging.getLogger('turtleart-activity') class Collaboration(): @@ -63,7 +61,7 @@ class Collaboration(): owner = self.pservice.get_owner() self.owner = owner self._tw.buddies.append(self.owner) - self._share = "" + self._share = '' self._activity.connect('shared', self._shared_cb) self._activity.connect('joined', self._joined_cb) @@ -89,8 +87,9 @@ class Collaboration(): def _shared_cb(self, activity): self._shared_activity = self._activity._shared_activity if self._shared_activity is None: - _logger.error("Failed to share or join activity ... \ - _shared_activity is null in _shared_cb()") + debug_output('Failed to share or join activity ... \ + _shared_activity is null in _shared_cb()', + self._tw.running_sugar) return self._tw.set_sharing(True) @@ -99,7 +98,7 @@ class Collaboration(): self.waiting_for_turtles = False self.turtle_dictionary = self._get_dictionary() - _logger.debug('I am sharing...') + debug_output('I am sharing...', self._tw.running_sugar) self.conn = self._shared_activity.telepathy_conn self.tubes_chan = self._shared_activity.telepathy_tubes_chan @@ -108,7 +107,8 @@ class Collaboration(): self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( 'NewTube', self._new_tube_cb) - _logger.debug('This is my activity: making a tube...') + debug_output('This is my activity: making a tube...', + self._tw.running_sugar) id = self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube( SERVICE, {}) @@ -116,8 +116,9 @@ class Collaboration(): def _joined_cb(self, activity): self._shared_activity = self._activity._shared_activity if self._shared_activity is None: - _logger.error("Failed to share or join activity ... \ - _shared_activity is null in _shared_cb()") + debug_output('Failed to share or join activity ... \ + _shared_activity is null in _shared_cb()', + self._tw.running_sugar) return self._tw.set_sharing(True) @@ -131,7 +132,8 @@ class Collaboration(): self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( 'NewTube', self._new_tube_cb) - _logger.debug('I am joining an activity: waiting for a tube...') + debug_output('I am joining an activity: waiting for a tube...', + self._tw.running_sugar) self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes( reply_handler=self._list_tubes_reply_cb, error_handler=self._list_tubes_error_cb) @@ -144,13 +146,13 @@ class Collaboration(): self._new_tube_cb(*tube_info) def _list_tubes_error_cb(self, e): - _logger.error('ListTubes() failed: %s', e) + error_output('ListTubes() failed: %s' % (e), self._tw.running_sugar) def _new_tube_cb(self, id, initiator, type, service, params, state): """ Create a new tube. """ - _logger.debug('New tube: ID=%d initator=%d type=%d service=%s ' - 'params=%r state=%d', id, initiator, type, service, - params, state) + debug_output('New tube: ID=%d initator=%d type=%d service=%s \ + params=%r state=%d' % (id, initiator, type, service, + params, state), self._tw.running_sugar) if (type == telepathy.TUBE_TYPE_DBUS and service == SERVICE): if state == telepathy.TUBE_STATE_LOCAL_PENDING: @@ -167,11 +169,12 @@ class Collaboration(): # Now that we have the tube, we can ask for the turtle dictionary. if self.waiting_for_turtles: - _logger.debug("Sending a request for the turtle dictionary") + debug_output('Sending a request for the turtle dictionary', + self._tw.running_sugar) # we need to send our own nick and colors colors = self._get_colors() - event = "t|" + data_to_string([self._get_nick(), colors]) - _logger.debug(event) + event = 't|' + data_to_string([self._get_nick(), colors]) + debug_output(event, self._tw.running_sugar) self.send_event(event) def event_received_cb(self, event_message): @@ -188,10 +191,11 @@ class Collaboration(): save_active_turtle = self._tw.active_turtle try: - command, payload = event_message.split("|", 2) + command, payload = event_message.split('|', 2) self._processing_methods[command](payload) except ValueError: - _logger.debug("could not split event message") + debug_output('Could not split event message.', + self._tw.running_sugar) # Restore active Turtle self._tw.canvas.set_turtle(self._tw.turtles.get_turtle_key( @@ -207,7 +211,7 @@ class Collaboration(): [nick, colors] = data_from_string(payload) if nick != self._tw.nick: # There may not be a turtle dictionary. - if hasattr(self, "turtle_dictionary"): + if hasattr(self, 'turtle_dictionary'): self.turtle_dictionary[nick] = colors else: self.turtle_dictionary = {nick: colors} @@ -216,7 +220,7 @@ class Collaboration(): # Sharer should send turtle dictionary. if self.initiating: event_payload = data_to_string(self.turtle_dictionary) - self.send_event("T|" + event_payload) + self.send_event('T|' + event_payload) def _receive_turtle_dict(self, payload): if self.waiting_for_turtles: diff --git a/TurtleArt/tajail.py b/TurtleArt/tajail.py index 081248f..0ec2563 100644 --- a/TurtleArt/tajail.py +++ b/TurtleArt/tajail.py @@ -19,8 +19,6 @@ #THE SOFTWARE. # A naive approach to running myfunc in a jail -import logging -_logger = logging.getLogger('turtleart-activity') import traceback from time import * from math import * diff --git a/TurtleArt/talogo.py b/TurtleArt/talogo.py index d3b214c..8674fb3 100644 --- a/TurtleArt/talogo.py +++ b/TurtleArt/talogo.py @@ -40,7 +40,7 @@ from taconstants import TAB_LAYER, BLACK, WHITE, DEFAULT_SCALE, ICON_SIZE, \ BLOCK_NAMES, CONSTANTS, PREFIX_DICTIONARY from tajail import myfunc, myfunc_import from tautils import get_pixbuf_from_journal, convert, data_from_file, \ - text_media_type, round_int, chr_to_ord, strtype, get_path + text_media_type, round_int, chr_to_ord, strtype, get_path, debug_output from util.RtfParser import RtfTextOnly @@ -51,30 +51,7 @@ VALUE_BLOCKS = ['box1', 'box2', 'color', 'shade', 'gray', 'scale', 'pensize', MEDIA_BLOCKS_DICTIONARY = {} # new media blocks get added here PLUGIN_DICTIONARY = {} # new block primitives get added here -import logging -_logger = logging.getLogger('turtleart-activity') - -<<<<<<< HEAD -def find_device(): - """ Search for RFID devices. Return a device instance or None. """ - device = None - for i in os.listdir(os.path.join('.', 'devices')): - if not os.path.isdir(os.path.join('.', 'devices', i)): - try: - _tempmod = __import__('devices.%s' % i.split('.')[0], - globals(), locals(), ['RFIDReader'], -1) - devtemp = _tempmod.RFIDReader() - if devtemp.get_present() == True: - device = devtemp - except Exception, e: - _logger.error('FIND_DEVICE: %s: %s' % (i, e)) - pass - return device - - -======= ->>>>>>> 860754f7e871617df9d101a51dc64a69b742a0ba class noKeyError(UserDict): __missing__ = lambda x, y: 0 @@ -282,38 +259,6 @@ def _identity(x): return(x) -<<<<<<< HEAD -def _avg(array, abs_value=False): - """ Calc. the average value of an array """ - if len(array) == 0: - return 0 - array_sum = 0 - if abs_value: - for a in array: - array_sum += abs(a) - else: - for a in array: - array_sum += a - return float(array_sum) / len(array) - - -def stop_logo(tw): - """ Stop logo is called from the Stop button on the toolbar """ - tw.step_time = 0 - tw.lc.step = _just_stop() - stop_media(tw.lc) - if tw.camera_available: - if tw.lc._video_capture_device is not None: - # restore AG and then close device - tw.lc._set_ag(1) - tw.lc._video_capture_device.close() - tw.lc._video_capture_device = None - tw.lc.camera.stop_camera_input() - tw.active_turtle.show() - - -======= ->>>>>>> 860754f7e871617df9d101a51dc64a69b742a0ba def _just_stop(): """ yield False to stop stack """ yield False @@ -520,27 +465,6 @@ class LogoCode: self.scale = DEFAULT_SCALE -<<<<<<< HEAD - self.max_samples = 1500 - self.input_step = 1 - - self.ringbuffer = RingBuffer1d(self.max_samples, dtype='int16') - if self.tw.hw == XO1: - self.voltage_gain = 0.00002225 - self.voltage_bias = 1.140 - elif self.tw.hw == XO15: - self.voltage_gain = -0.0001471 - self.voltage_bias = 1.695 - - if self.tw.camera_available: - self._video_capture_device = None - if self.tw.running_sugar: - self.imagepath = get_path(self.tw.activity, - 'data/turtlepic.png') - else: - self.imagepath = '/tmp/turtlepic.png' - self.camera = Camera(self.imagepath) -======= def stop_logo(self): """ Stop logo is called from the Stop button on the toolbar """ self.tw.step_time = 0 @@ -551,7 +475,6 @@ class LogoCode: from tagplay import stop_media stop_media(self) self.tw.active_turtle.show() ->>>>>>> 860754f7e871617df9d101a51dc64a69b742a0ba def _def_prim(self, name, args, fcn, rprim=False): """ Define the primitives associated with the blocks """ @@ -601,7 +524,7 @@ class LogoCode: code = self._blocks_to_code(blk) if run_flag: - _logger.debug("running code: %s" % (code)) + debug_output("running code: %s" % (code), self.tw.running_sugar) self._start_time = time() self._setup_cmd(code) if not self.tw.hide: @@ -811,7 +734,8 @@ class LogoCode: self.arglist.append(self.iresult) if self.cfun.rprim: if type(self.cfun.fcn) == self.listtype: - _logger.debug("evalsym rprim list: %s" % (str(token))) + debug_output('evalsym rprim list: %s' % (str(token)), + self.tw.running_sugar) self._icall(self._ufuncall, self.cfun.fcn) yield True else: @@ -945,7 +869,8 @@ class LogoCode: try: y = myfunc(f, x) if str(y) == 'nan': - _logger.debug("python function returned nan") + debug_output('Python function returned NAN', + self.tw.running_sugar) self.stop_logo() raise logoerror("#notanumber") else: @@ -1106,7 +1031,8 @@ class LogoCode: try: dsobject = datastore.get(n[6:]) except: - _logger.debug("Couldn't open %s" % (n[6:])) + debug_output("Couldn't open %s" % (n[6:]), + self.tw.running_sugar) self.tw.showlabel('status', dsobject.metadata['title']) dsobject.destroy() else: @@ -1271,7 +1197,8 @@ class LogoCode: try: dsobject = datastore.get(media[6:]) except: - _logger.debug("Couldn't open skin %s" % (media[6:])) + debug_output("Couldn't open skin %s" % (media[6:]), + self.tw.running_sugar) if dsobject is not None: self.filepath = dsobject.file_path if self.filepath == None: @@ -1283,7 +1210,8 @@ class LogoCode: scale) except: self.tw.showlabel('nojournal', self.filepath) - _logger.debug("Couldn't open skin %s" % (self.filepath)) + debug_output("Couldn't open skin %s" % (self.filepath), + self.tw.running_sugar) if pixbuf is not None: self.tw.active_turtle.set_shapes([pixbuf]) pen_state = self.tw.active_turtle.get_pen_state() @@ -1328,8 +1256,8 @@ class LogoCode: try: self.dsobject = datastore.get(string[6:]) except: - _logger.debug("Couldn't find dsobject %s" % ( - string[6:])) + debug_output("Couldn't find dsobject %s" % ( + string[6:]), self.tw.running_sugar) if self.dsobject is not None: self.filepath = self.dsobject.file_path if self.filepath == None: @@ -1338,7 +1266,8 @@ class LogoCode: self.dsobject.metadata['title']) else: self.tw.showlabel('nojournal', string[6:]) - _logger.debug("Couldn't open %s" % (string[6:])) + debug_output("Couldn't open %s" % (string[6:]), + self.tw.running_sugar) elif string[0:6] == 'media_': self._insert_image(center) elif string[0:6] == 'descr_': @@ -1387,7 +1316,8 @@ class LogoCode: try: pixbuf = get_pixbuf_from_journal(self.dsobject, w, h) except: - _logger.debug("Couldn't open dsobject %s" % (self.dsobject)) + debug_output("Couldn't open dsobject %s" % (self.dsobject), + self.tw.running_sugar) if pixbuf is None and \ self.filepath is not None and \ self.filepath != '': @@ -1396,7 +1326,8 @@ class LogoCode: w, h) except: self.tw.showlabel('nojournal', self.filepath) - _logger.debug("Couldn't open filepath %s" % (self.filepath)) + debug_output("Couldn't open filepath %s" % (self.filepath), + self.tw.running_sugar) if pixbuf is not None: if center: self.tw.canvas.draw_pixbuf(pixbuf, 0, 0, @@ -1427,12 +1358,8 @@ class LogoCode: f.close() except IOError: self.tw.showlabel('nojournal', self.filepath) -<<<<<<< HEAD - _logger.debug("Couldn't open filepath %s" % \ - (self.filepath)) -======= - _logger.debug("Couldn't open %s" % (self.filepath)) ->>>>>>> 860754f7e871617df9d101a51dc64a69b742a0ba + debug_output("Couldn't open %s" % (self.filepath), + self.tw.running_sugar) else: if description is not None: text = str(description) @@ -1488,151 +1415,6 @@ class LogoCode: self.heap.append(b) self.heap.append(g) self.heap.append(r) -<<<<<<< HEAD - - def _read_camera(self, luminance_only=False): - """ Read average pixel from camera and push b, g, r to the stack """ - - if not self.tw.camera_available: - if not luminance_only: - self.heap.append(-1) - self.heap.append(-1) - self.heap.append(-1) - return -1 - - pixbuf = None - array = None - w = self._w() - if w < 1: - w = 1 - h = self._h() - if h < 1: - h = 1 - - self._video_capture_device = None - try: - self._video_capture_device = open('/dev/video0', 'rw') - except: - _logger.debug('video capture device not available') - if self._video_capture_device is not None: - self._set_ag(0) # disable autogain - - self.camera.save_camera_input_to_file() - self.camera.stop_camera_input() - - if self._video_capture_device is not None: - self._set_ag(1) # restore autogain and close device - self._video_capture_device.close() - self._video_capture_device = None - - pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.imagepath, w, h) - array = pixbuf.get_pixels() - - array_length = len(array) / 3 - r = 0 - g = 0 - b = 0 - i = 0 - for j in range(array_length): - r += ord(array[i]) - i += 1 - g += ord(array[i]) - i += 1 - b += ord(array[i]) - i += 1 - if luminance_only: - lum = int((r * 0.3 + g * 0.6 + b * 0.1) / array_length) - self.update_label_value('luminance', lum) - return lum - else: - self.heap.append(int((b / array_length))) - self.heap.append(int((g / array_length))) - self.heap.append(int((r / array_length))) - - def _set_ag(self, value): - """ set camera autogain (0==off, 1==on) """ - self._ag_control = v4l2.v4l2_control(v4l2.V4L2_CID_AUTOGAIN) - try: - ioctl(self._video_capture_device, v4l2.VIDIOC_G_CTRL, - self._ag_control) - self._ag_control.value = value - ioctl(self._video_capture_device, v4l2.VIDIOC_S_CTRL, - self._ag_control) - ioctl(self._video_capture_device, v4l2.VIDIOC_G_CTRL, - self._ag_control) - except: - _logger.debug('AUTOGAIN control not available') - - def _get_volume(self): - """ return mic in value """ - #TODO: Adjust gain for different HW - buf = self.ringbuffer.read(None, self.input_step) - if len(buf) > 0: - volume = float(_avg(buf, abs_value=True)) - self.update_label_value('volume', volume) - return volume - else: - return 0 - - def _get_sound(self): - """ return raw mic in value """ - buf = self.ringbuffer.read(None, self.input_step) - if len(buf) > 0: - sound = float(buf[0]) - self.update_label_value('sound', sound) - return sound - else: - return 0 - - def _get_pitch(self): - """ return index of max value in fft of mic in values """ - buf = [] - for i in range(4): - buf = append(buf, self.ringbuffer.read(None, self.input_step)) - if len(buf) > 0: - r = [] - for j in rfft(buf): - r.append(abs(j)) - # Convert output to Hertz - pitch = r.index(max(r)) * 48000 / len(buf) - self.update_label_value('pitch', pitch) - return pitch - else: - return 0 - - def _get_resistance(self): - """ return resistance sensor value """ - buf = self.ringbuffer.read(None, self.input_step) - if len(buf) > 0: - # See - # TODO: test this calibration on XO 1.5 - if self.tw.hw == XO1: - resistance = 2.718 ** ((float(_avg(buf)) * 0.000045788) + \ - 8.0531) - else: - avg_buf = float(_avg(buf)) - if avg_buf > 0: - resistance = (420000000 / avg_buf) - 13500 - else: - resistance = 420000000 - self.update_label_value('resistance', resistance) - return resistance - else: - return 0 - - def _get_voltage(self): - """ return voltage sensor value """ - buf = self.ringbuffer.read(None, self.input_step) - if len(buf) > 0: - # See - voltage = float(_avg(buf)) * self.voltage_gain + self.voltage_bias - self.update_label_value('voltage', voltage) - return voltage - else: - return 0 - -======= ->>>>>>> 860754f7e871617df9d101a51dc64a69b742a0ba # Depreciated block methods def _show_template1x1(self, title, media): diff --git a/TurtleArt/taturtle.py b/TurtleArt/taturtle.py index f309eef..a4bd2f4 100644 --- a/TurtleArt/taturtle.py +++ b/TurtleArt/taturtle.py @@ -23,9 +23,7 @@ from taconstants import TURTLE_LAYER, DEFAULT_TURTLE_COLORS from tasprite_factory import SVG, svg_str_to_pixbuf from tacanvas import wrap100, color_table from sprites import Sprite - -import logging -_logger = logging.getLogger('turtleart-activity') +from tautils import debug_output SHAPES = 36 @@ -159,7 +157,8 @@ class Turtle: self.shapes = shapes[:] else: if n != 1: - _logger.debug("%d images passed to set_shapes: ignoring" % (n)) + debug_output("%d images passed to set_shapes: ignoring" % (n), + self.tw.running_sugar) images = [shapes[0]] if self.heading == 0: for i in range(3): diff --git a/TurtleArt/tautils.py b/TurtleArt/tautils.py index 521637e..845d792 100644 --- a/TurtleArt/tautils.py +++ b/TurtleArt/tautils.py @@ -48,6 +48,22 @@ import logging _logger = logging.getLogger('turtleart-activity') +def debug_output(message_string, running_sugar=False): + """ unified debugging output """ + if running_sugar: + _logger.debug(message_string) + else: + print(message_string) + + +def error_output(message_string, running_sugar=False): + """ unified debugging output """ + if running_sugar: + _logger.error(message_string) + else: + print(message_string) + + class pythonerror(Exception): def __init__(self, value): @@ -338,7 +354,6 @@ def round_int(num): try: float(num) except TypeError: - _logger.debug("error trying to convert %s to number" % (str(num))) raise pythonerror("#syntaxerror") if int(float(num)) == num: diff --git a/TurtleArt/tawindow.py b/TurtleArt/tawindow.py index f12a753..eef9805 100644 --- a/TurtleArt/tawindow.py +++ b/TurtleArt/tawindow.py @@ -80,7 +80,7 @@ from tautils import magnitude, get_load_name, get_save_name, data_from_file, \ arithmetic_check, xy, find_block_to_run, find_top_block, \ find_start_stack, find_group, find_blk_below, \ dock_dx_dy, data_to_string, journal_check, chooser, \ - get_hardware + get_hardware, debug_output from tasprite_factory import SVG, svg_str_to_pixbuf, svg_from_file from sprites import Sprites, Sprite from dbus.mainloop.glib import DBusGMainLoop @@ -88,9 +88,6 @@ from dbus.mainloop.glib import DBusGMainLoop if GST_AVAILABLE: from tagplay import stop_media -import logging -_logger = logging.getLogger('turtleart-activity') - class TurtleArtWindow(): """ TurtleArt Window class abstraction """ @@ -125,7 +122,7 @@ class TurtleArtWindow(): self.running_sugar = False self.gc = self.window.new_gc() else: - _logger.debug("bad win type %s" % (type(win))) + debug_output("bad win type %s" % (type(win)), False) if self.running_sugar: self.activity = parent @@ -150,11 +147,10 @@ class TurtleArtWindow(): self.mouse_x = 0 self.mouse_y = 0 - # if self.running_sugar: try: locale.setlocale(locale.LC_NUMERIC, '') except locale.Error: - _logger.debug('unsupported locale') + debug_output('unsupported locale', self.running_sugar) self.decimal_point = locale.localeconv()['decimal_point'] if self.decimal_point == '' or self.decimal_point is None: self.decimal_point = '.' @@ -162,7 +158,7 @@ class TurtleArtWindow(): self.orientation = HORIZONTAL_PALETTE self.hw = get_hardware() - _logger.debug('running on %s hardware' % (self.hw)) + # debug_output('running on %s hardware' % (self.hw), self.running_sugar) if self.hw in (XO1, XO15): self.lead = 1.0 self.scale = 0.67 @@ -435,7 +431,8 @@ class TurtleArtWindow(): for blk in self.just_blocks(): if find_start_stack(blk): self.step_time = time - _logger.debug("running stack starting from %s" % (blk.name)) + debug_output("running stack starting from %s" % (blk.name), + self.running_sugar) self._run_stack(blk) return @@ -443,7 +440,8 @@ class TurtleArtWindow(): for blk in self.just_blocks(): if find_block_to_run(blk): self.step_time = time - _logger.debug("running stack starting from %s" % (blk.name)) + debug_output("running stack starting from %s" % (blk.name), + self.running_sugar) self._run_stack(blk) return @@ -1205,7 +1203,7 @@ class TurtleArtWindow(): def process_data(self, block_data, offset=0): """ Process block_data (from a macro, a file, or the clipboard). """ if offset != 0: - _logger.debug("offset is %d" % (offset)) + debug_output("offset is %d" % (offset), self.running_sugar) # Create the blocks (or turtle). blocks = [] for blk in block_data: @@ -1224,7 +1222,8 @@ class TurtleArtWindow(): else: cons.append(blocks[c]) else: - _logger.debug("connection error %s" % (str(block_data[i]))) + debug_output("connection error %s" % (str(block_data[i])), + self.running_sugar) cons.append(None) elif blocks[i].connections == 'check': # Convert old-style boolean and arithmetic blocks @@ -1248,7 +1247,8 @@ class TurtleArtWindow(): blocks[c].connections[3] = None else: # Connection was to a block we haven't seen yet. - _logger.debug("Warning: dock to the future") + debug_output("Warning: dock to the future", + self.running_sugar) else: if block_data[i][4][0] is not None: c = block_data[i][4][0] @@ -1262,10 +1262,12 @@ class TurtleArtWindow(): blocks[c].connections[1] = None else: # Connection was to a block we haven't seen yet. - _logger.debug("Warning: dock to the future") + debug_output("Warning: dock to the future", + self.running_sugar) else: - _logger.debug("Warning: unknown connection state %s" % \ - (str(blocks[i].connections))) + debug_output("Warning: unknown connection state %s" % \ + (str(blocks[i].connections)), + self.running_sugar) blocks[i].connections = cons[:] # Block sizes and shapes may have changed. @@ -2063,7 +2065,8 @@ class TurtleArtWindow(): oldleft, oldright = \ self.selected_blk.spr.labels[0].split(CURSOR) except ValueError: - _logger.debug("[%s]" % self.selected_blk.spr.labels[0]) + debug_output("[%s]" % self.selected_blk.spr.labels[0], + self.running_sugar) oldleft = self.selected_blk.spr.labels[0] oldright = '' else: @@ -2272,7 +2275,8 @@ class TurtleArtWindow(): f.close() id = fname except IOError: - _logger.error("Unable to read Python code from %s" % (fname)) + error_output("Unable to read Python code from %s" % (fname), + self.running_sugar) return id # if we are running Sugar, copy the file into the Journal @@ -2288,7 +2292,8 @@ class TurtleArtWindow(): datastore.write(dsobject) id = dsobject.object_id except IOError: - _logger.error("Error copying %s to the datastore" % (fname)) + error_output("Error copying %s to the datastore" % (fname), + self.running_sugar) id = None dsobject.destroy() @@ -2313,12 +2318,14 @@ class TurtleArtWindow(): """ Read the Python code from the Journal object """ self.python_code = None try: - _logger.debug("opening %s " % dsobject.file_path) + debug_output("opening %s " % dsobject.file_path, + self.running_sugar) file_handle = open(dsobject.file_path, "r") self.python_code = file_handle.read() file_handle.close() except IOError: - _logger.debug("couldn't open %s" % dsobject.file_path) + debug_output("couldn't open %s" % dsobject.file_path, + self.running_sugar) if blk is None: blk = self.selected_blk if blk is not None: @@ -2363,8 +2370,9 @@ class TurtleArtWindow(): saved_project_data = f.read() f.close() except: - _logger.debug("problem loading saved project data from %s" % \ - (self._loaded_project)) + debug_output("problem loading saved project data from %s" % \ + (self._loaded_project), + self.running_sugar) saved_project_data = "" current_project_data = data_to_string(self.assemble_data_to_save()) @@ -2462,7 +2470,8 @@ class TurtleArtWindow(): dsobject = datastore.get(value) except: # Should be IOError, but dbus error is raised dsobject = None - _logger.debug("couldn't get dsobject %s" % value) + debug_output("couldn't get dsobject %s" % value, + self.running_sugar) if dsobject is not None: self.load_python_code_from_journal(dsobject, blk) else: @@ -2528,8 +2537,8 @@ class TurtleArtWindow(): x, y = self._calc_image_offset('', blk.spr) blk.set_image(pixbuf, x, y) except: - _logger.debug("Couldn't open dsobject (%s)" % \ - (blk.values[0])) + debug_output("Couldn't open dsobject (%s)" % \ + (blk.values[0]), self.running_sugar) self._block_skin('journaloff', blk) else: if not movie_media_type(blk.values[0][-4:]): @@ -2648,7 +2657,7 @@ class TurtleArtWindow(): def showlabel(self, shp, label=''): """ Display a message on a status block """ if not self.interactive_mode: - _logger.debug(label) + debug_output(label, self.running_sugar) return if shp == 'syntaxerror' and str(label) != '': if str(label)[1:] in self.status_shapes: diff --git a/audio/audiograb.py b/audio/audiograb.py index 1240be7..84e0c8d 100644 --- a/audio/audiograb.py +++ b/audio/audiograb.py @@ -48,24 +48,19 @@ QUIT_DC_MODE_ENABLE = False QUIT_CAPTURE_GAIN = 100 QUIT_BIAS = True -import logging - -_logger = logging.getLogger('TurtleArt') -_logger.setLevel(logging.DEBUG) -logging.basicConfig() - from TurtleArt.taconstants import XO1 +from TurtleArt.tautils import debug_output class AudioGrab: """ The interface between measure and the audio device """ - def __init__(self, callable1, activity): + def __init__(self, callable1, parent): """ Initialize the class: callable1 is a data buffer; - activity is the parent class""" + parent is the parent class""" self.callable1 = callable1 - self.activity = activity + self.parent = parent self.sensor = None self.temp_buffer = [0] @@ -109,8 +104,9 @@ class AudioGrab: # Query the available controls try: # F11+ - _logger.debug('controls: %r', [t.props.untranslated_label \ - for t in self._mixer.list_tracks()]) + debug_output('controls: %r' % \ + ([t.props.untranslated_label for t in self._mixer.list_tracks()]), + self.parent.running_sugar) self._dc_control = self._find_control(['dc mode']) self._mic_bias_control = self._find_control(['mic bias', 'dc input bias', @@ -153,7 +149,7 @@ class AudioGrab: """The function that is called whenever new data is available This is the signal handler for the handoff signal""" if buffer is None: - _logger.debug('audiograb buffer is None') + debug_output('audiograb buffer is None', self.parent.running_sugar) return False temp_buffer = fromstring(buffer, 'int16') @@ -238,8 +234,9 @@ class AudioGrab: controls.sort(key=lambda e: e[1]) if controls: - _logger.debug("found control: %s" %\ - (str(controls[0][0].props.untranslated_label))) + debug_output('Found control: %s' % \ + (str(controls[0][0].props.untranslated_label)), + self.parent.running_sugar) return controls[0][0] return None @@ -266,8 +263,9 @@ class AudioGrab: return default value = bool(control.flags & gst.interfaces.MIXER_TRACK_MUTE) - _logger.debug('Getting %s (%s) mute status: %r', name, - control.props.untranslated_label, value) + debug_output('Getting %s (%s) mute status: %r' % (name, + control.props.untranslated_label, value), + self.parent.running_sugar) return value def _set_mute(self, control, name, value): @@ -276,8 +274,9 @@ class AudioGrab: return self._mixer.set_mute(control, value) - _logger.debug('Set mute for %s (%s) to %r', name, - control.props.untranslated_label, value) + debug_output('Set mute for %s (%s) to %r' % (name, + control.props.untranslated_label, value), + self.parent.running_sugar) def _get_volume(self, control, name): """Get volume of a control and convert to a scale of 0-100""" @@ -315,14 +314,14 @@ class AudioGrab: def mute_master(self): """Mutes the Master Control""" - if not self._hardwired and self.activity.hw != XO1: + if not self._hardwired and self.parent.hw != XO1: self._set_mute(self._master_control, 'Master', True) else: self.amixer_set('Master', False) def unmute_master(self): """Unmutes the Master Control""" - if not self._hardwired and self.activity.hw != XO1: + if not self._hardwired and self.parent.hw != XO1: self._set_mute(self._master_control, 'Master', True) else: self.amixer_set('Master', True) @@ -351,7 +350,7 @@ class AudioGrab: def set_bias(self, bias_state=False): """Enables / disables bias voltage.""" - if not self._hardwired and self.activity.hw != XO1: + if not self._hardwired and self.parent.hw != XO1: if self._mic_bias_control is None: return # if not isinstance(self._mic_bias_control, @@ -407,7 +406,7 @@ class AudioGrab: def set_dc_mode(self, dc_mode=False): """Sets the DC Mode Enable control pass False to mute and True to unmute""" - if not self._hardwired and self.activity.hw != XO1: + if not self._hardwired and self.parent.hw != XO1: if self._dc_control is not None: self._set_mute(self._dc_control, 'DC mode', not dc_mode) else: @@ -465,7 +464,8 @@ class AudioGrab: return self._get_mute(self._mic_boost_control, 'Mic Boost', False) current = self._mixer.get_volume(self._mic_boost_control) - _logger.debug('current: %s' % (str(current))) + debug_output('current: %s' % (str(current)), + self.parent.running_sugar) if current != self._mic_boost_control.min_volume: return True return False @@ -484,7 +484,7 @@ class AudioGrab: """Sets the Capture gain slider settings capture_val must be given as an integer between 0 and 100 indicating the percentage of the slider to be set""" - if not self._hardwired and self.activity.hw != XO1: + if not self._hardwired and self.parent.hw != XO1: if self._capture_control is not None: self._set_volume(self._capture_control, 'Capture', capture_val) else: @@ -510,7 +510,7 @@ class AudioGrab: """Sets the MIC gain slider settings mic_val must be given as an integer between 0 and 100 indicating the percentage of the slider to be set""" - if not self._hardwired and self.activity.hw != XO1: + if not self._hardwired and self.parent.hw != XO1: self._set_volume(self._mic_gain_control, 'Mic', mic_val) else: os.system("amixer set Mic " + str(mic_val) + "%") @@ -550,10 +550,9 @@ class AudioGrab: SENSOR_DC_BIAS: (True, True, 0, False) } mode, bias, gain, boost = PARAMETERS[sensor_type] - _logger.debug("====================================") - _logger.debug("Set Sensor Type to %s" % (str(sensor_type))) + debug_output('Set Sensor Type to %s' % (str(sensor_type)), + self.parent.running_sugar) self._set_sensor_type(mode, bias, gain, boost) - _logger.debug("====================================") def _set_sensor_type(self, mode=None, bias=None, gain=None, boost=None): """Helper to modify (some) of the sensor settings.""" @@ -602,11 +601,10 @@ class AudioGrab_XO15(AudioGrab): SENSOR_DC_NO_BIAS: (True, False, 80, False), SENSOR_DC_BIAS: (True, True, 90, False) } - _logger.debug("====================================") - _logger.debug("Set Sensor Type to %s" % (str(sensor_type))) + debug_output('Set Sensor Type to %s' % (str(sensor_type)), + self.parent.running_sugar) mode, bias, gain, boost = PARAMETERS[sensor_type] self._set_sensor_type(mode, bias, gain, boost) - _logger.debug("====================================") class AudioGrab_Unknown(AudioGrab): @@ -619,8 +617,7 @@ class AudioGrab_Unknown(AudioGrab): SENSOR_DC_NO_BIAS: (True, False, 80, False), SENSOR_DC_BIAS: (True, True, 90, False) } - _logger.debug("====================================") - _logger.debug("Set Sensor Type to %s" % (str(sensor_type))) + debug_output('Set Sensor Type to %s' % (str(sensor_type)), + self.parent.running_sugar) mode, bias, gain, boost = PARAMETERS[sensor_type] self._set_sensor_type(mode, bias, gain, boost) - _logger.debug("====================================") -- cgit v0.9.1