def _joined_cb(self, activity): self._shared_activity = self._activity.get_shared_activity() if self._shared_activity is None: 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) self.initiating = False self.conn = self._shared_activity.telepathy_conn self.tubes_chan = self._shared_activity.telepathy_tubes_chan self.text_chan = self._shared_activity.telepathy_text_chan # call back for "NewTube" signal self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( 'NewTube', self._new_tube_cb) 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) # Joiner should request current state from sharer. self.waiting_for_turtles = True self._enable_share_button()
def _joined_cb(self, activity): self._shared_activity = self._activity.get_shared_activity() if self._shared_activity is None: 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) self.initiating = False self.conn = self._shared_activity.telepathy_conn self.tubes_chan = self._shared_activity.telepathy_tubes_chan self.text_chan = self._shared_activity.telepathy_text_chan # call back for "NewTube" signal self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( 'NewTube', self._new_tube_cb) 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) # Joiner should request current state from sharer. self.waiting_for_turtles = True self._enable_share_button()
def _joined_cb(self, collab): # Now that we have the tube, we can ask for the turtle dictionary. debug_output('Sending a request for the turtle dictionary', self._tw.running_sugar) # We need to send our own nick, colors, and turtle position colors = self._get_colors() event = data_to_string([self._get_nick(), colors]) debug_output(event, self._tw.running_sugar) self.send_event('t', event)
def bobot_poll(self): if self.pollrun: time = 6 if self.tw.get_init_complete(): if self.can_refresh: time = 3 self.check_for_device_change(False) self.pollthread = threading.Timer(time, self.bobot_poll) self.pollthread.start() else: debug_output(_("Ending Butia polling"))
def _splitter_pad_added(self, element, pad): ''' Seems to be the case that ring is right channel 0, tip is left channel 1''' ''' debug_output('splitter pad %d added' % (self._pad_count), self.parent.running_sugar) ''' self.pads.append(pad) if self._pad_count < self.channels: pad.link(self.queue[self._pad_count].get_pad('sink')) self.queue[self._pad_count].get_pad('src').link( self.fakesink[self._pad_count].get_pad('sink')) self._pad_count += 1 else: debug_output('ignoring channels > %d' % (self.channels), self.parent.running_sugar)
def _set_autogain(self, state, camera=0): ''' 0 is off; 1 is on ''' if self._ag_control is not None and self._ag_control.value == state: return try: video_capture_device = open(self.devices[camera], 'rw') except: video_capture_device = None debug_output('video capture device not available', self._parent.running_sugar) return self._ag_control = v4l2_control(V4L2_CID_AUTOGAIN) try: ioctl(video_capture_device, VIDIOC_G_CTRL, self._ag_control) self._ag_control.value = state ioctl(video_capture_device, VIDIOC_S_CTRL, self._ag_control) except: pass video_capture_device.close()
def _set_autogain(self, state, camera=0): ''' 0 is off; 1 is on ''' if self._ag_control is not None and self._ag_control.value == state: return try: video_capture_device = open(self.devices[camera], 'rw') except BaseException: video_capture_device = None debug_output('video capture device not available', self._parent.running_sugar) return self._ag_control = v4l2_control(V4L2_CID_AUTOGAIN) try: ioctl(video_capture_device, VIDIOC_G_CTRL, self._ag_control) self._ag_control.value = state ioctl(video_capture_device, VIDIOC_S_CTRL, self._ag_control) except BaseException: pass video_capture_device.close()
def check_output(command, warning, running_sugar=True): ''' Workaround for old systems without subprocess.check_output''' if hasattr(subprocess, 'check_output'): try: output = subprocess.check_output(command) except subprocess.CalledProcessError: debug_output(warning, running_sugar) return None else: import commands cmd = '' for c in command: cmd += c cmd += ' ' (status, output) = commands.getstatusoutput(cmd) if status != 0: debug_output(warning, running_sugar) return None return output
def _shared_cb(self, activity): self._shared_activity = self._activity.get_shared_activity() if self._shared_activity is None: 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) self.initiating = True self.waiting_for_turtles = False self._tw.remote_turtle_dictionary = self._get_dictionary() 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 self.text_chan = self._shared_activity.telepathy_text_chan self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( 'NewTube', self._new_tube_cb) debug_output('This is my activity: making a tube...', self._tw.running_sugar) self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube( SERVICE, {}) self._enable_share_button()
def _receive_turtle_dict(self, payload): ''' Any time there is a new joiner, an updated turtle dictionary is circulated. Everyone must report their turtle positions so that we are in sync. ''' if self.waiting_for_turtles: if len(payload) > 0: # Grab the new remote turtles dictionary. remote_turtle_dictionary = data_from_string(payload) # Add see what is new. for nick in remote_turtle_dictionary: if nick == self._tw.nick: debug_output('skipping my nick %s' % (nick), self._tw.running_sugar) elif nick != self._tw.remote_turtle_dictionary: # Add new the turtle. colors = remote_turtle_dictionary[nick] self._tw.remote_turtle_dictionary[nick] = colors self._tw.turtles.set_turtle(nick, colors) # Label the remote turtle. self._tw.label_remote_turtle(nick, colors) debug_output('adding %s to remote turtle dictionary' % (nick), self._tw.running_sugar) else: debug_output('%s already in remote turtle dictionary' % (nick), self._tw.running_sugar) self.waiting_for_turtles = False self.send_my_xy()
def _new_tube_cb(self, id, initiator, type, service, params, state): """ Create a new tube. """ 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: self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES]\ .AcceptDBusTube(id) self.collab = CollabWrapper(self) self.collab.message.connect(self.event_received_cb) self.collab.setup() # Now that we have the tube, we can ask for the turtle dictionary. if self.waiting_for_turtles: # A joiner must wait for turtles. debug_output('Sending a request for the turtle dictionary', self._tw.running_sugar) # We need to send our own nick, colors, and turtle position colors = self._get_colors() event = data_to_string([self._get_nick(), colors]) debug_output(event, self._tw.running_sugar) self.send_event("t", {"payload": event})
def _new_tube_cb(self, id, initiator, type, service, params, state): """ Create a new tube. """ 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: self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES]\ .AcceptDBusTube(id) tube_conn = TubeConnection( self.conn, self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], id, group_iface=self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP]) # We'll use a chat tube to send serialized stacks back and forth. self.chattube = ChatTube(tube_conn, self.initiating, self.event_received_cb) # Now that we have the tube, we can ask for the turtle dictionary. if self.waiting_for_turtles: # A joiner must wait for turtles. debug_output('Sending a request for the turtle dictionary', self._tw.running_sugar) # We need to send our own nick, colors, and turtle position colors = self._get_colors() event = 't|' + data_to_string([self._get_nick(), colors]) debug_output(event, self._tw.running_sugar) self.send_event(event)
def _shared_cb(self, activity): self._shared_activity = self._activity.get_shared_activity() if self._shared_activity is None: 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) self.initiating = True self.waiting_for_turtles = False self._tw.remote_turtle_dictionary = self._get_dictionary() 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 self.text_chan = self._shared_activity.telepathy_text_chan self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( 'NewTube', self._new_tube_cb) debug_output('This is my activity: making a tube...', self._tw.running_sugar) self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube( SERVICE, {}) self._enable_share_button()
def _receive_turtle_dict(self, payload): ''' Any time there is a new joiner, an updated turtle dictionary is circulated. Everyone must report their turtle positions so that we are in sync. ''' if self.waiting_for_turtles: if len(payload) > 0: # Grab the new remote turtles dictionary. remote_turtle_dictionary = data_from_string(payload) # Add see what is new. for nick in remote_turtle_dictionary: if nick == self._tw.nick: debug_output('skipping my nick %s' % (nick), self._tw.running_sugar) elif nick != self._tw.remote_turtle_dictionary: # Add new the turtle. colors = remote_turtle_dictionary[nick] self._tw.remote_turtle_dictionary[nick] = colors self._tw.turtles.set_turtle(nick, colors) # Label the remote turtle. self._tw.label_remote_turtle(nick, colors) debug_output( 'adding %s to remote turtle dictionary' % (nick), self._tw.running_sugar) else: debug_output( '%s already in remote turtle dictionary' % (nick), self._tw.running_sugar) self.waiting_for_turtles = False self.send_my_xy()
def calc_luminance(self, camera=0): array = self.cameras[camera].pixbuf.get_pixels() width = self.cameras[camera].pixbuf.get_width() height = self.cameras[camera].pixbuf.get_height() if array is not None: length = int(len(array) / 3) if length != width * height: debug_output('array length != width x height (%d != %dx%d)' % (length, width, height), self._parent.running_sugar) # Average the 100 pixels in the center of the screen r, g, b = 0, 0, 0 row_offset = int((height / 2 - 5) * width * 3) column_offset = int(width / 2 - 5) * 3 for y in range(10): i = row_offset + column_offset for x in range(10): r += ord(array[i]) i += 1 g += ord(array[i]) i += 1 b += ord(array[i]) i += 1 row_offset += width * 3 if self.luminance_only: self.luminance = int((r * 0.3 + g * 0.6 + b * 0.1) / 100) else: self.r = int(r / 100) self.g = int(g / 100) self.b = int(b / 100) else: if self.luminance_only: self.luminance = -1 else: self.r = -1 self.g = -1 self.b = -1
def calc_luminance(self, camera=0): array = self.cameras[camera].pixbuf.get_pixels() width = self.cameras[camera].pixbuf.get_width() height = self.cameras[camera].pixbuf.get_height() if array is not None: length = int(len(array) / 3) if length != width * height: debug_output('array length != width x height (%d != %dx%d)' % \ (length, width, height), self._parent.running_sugar) # Average the 100 pixels in the center of the screen r, g, b = 0, 0, 0 row_offset = int((height / 2 - 5) * width * 3) column_offset = int(width / 2 - 5) * 3 for y in range(10): i = row_offset + column_offset for x in range(10): r += ord(array[i]) i += 1 g += ord(array[i]) i += 1 b += ord(array[i]) i += 1 row_offset += width * 3 if self.luminance_only: self.luminance = int((r * 0.3 + g * 0.6 + b * 0.1) / 100) else: self.r = int(r / 100) self.g = int(g / 100) self.b = int(b / 100) else: if self.luminance_only: self.luminance = -1 else: self.r = -1 self.g = -1 self.b = -1
def event_received_cb(self, event_message): """ Events are sent as a tuple, nick|cmd, where nick is a turle name and cmd is a turtle event. Everyone gets the turtle dictionary from the sharer and watches for 't' events, which indicate that a new turtle has joined. """ if len(event_message) == 0: return # Save active Turtle save_active_turtle = self._tw.active_turtle try: command, payload = event_message.split('|', 2) self._processing_methods[command](payload) except ValueError: 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(save_active_turtle))
def event_received_cb(self, event_message): """ Events are sent as a tuple, nick|cmd, where nick is a turle name and cmd is a turtle event. Everyone gets the turtle dictionary from the sharer and watches for 't' events, which indicate that a new turtle has joined. """ if len(event_message) == 0: return # Save active Turtle save_active_turtle = self._tw.turtles.get_active_turtle() try: command, payload = event_message.split('|', 2) except ValueError: debug_output('Could not split event message [%s]' % event_message, self._tw.running_sugar) self._processing_methods[command](payload) # Restore active Turtle self._tw.turtles.set_turtle( self._tw.turtles.get_turtle_key(save_active_turtle))
def pybot_launch(self): res = self.butia.reconnect() if res == ERROR: try: debug_output(_('Creating PyBot server')) self.bobot = subprocess.Popen(['python', 'pybot_server.py'], cwd='./plugins/butia/pybot') time.sleep(1) self.butia.reconnect() except: debug_output(_('ERROR creating PyBot server')) else: debug_output(_('PyBot is alive!'))
def pybot_launch(self): res = self.butia.reconnect() if res == ERROR: try: debug_output(_('Creating PyBot server')) self.bobot = subprocess.Popen( ['python', 'pybot_server.py'], cwd=os_path.join(os_path.dirname(__file__),'pybot')) time.sleep(1) self.butia.reconnect() except: debug_output(_('ERROR creating PyBot server')) else: debug_output(_('PyBot is alive!')) self.pollthread=threading.Timer(1, self.bobot_poll) self.pollthread.start()
def _prim_add_food(self, name, media, calories, protein, carbohydrates, fiber, fat): # Add a new food item to the palette palette = make_palette('food', colors=["#FFFFFF", "#A0A0A0"], help_string=_('Palette of foods')) # We need to convert the media into two svgs, one for the # palette and one for the block. filepath = None if media is not None and os.path.exists(media.value): filepath = media.value elif self.tw.running_sugar: # datastore object from sugar.datastore import datastore try: dsobject = datastore.get(media.value) except: debug_output("Couldn't find dsobject %s" % (media.value), self.tw.running_sugar) if dsobject is not None: filepath = dsobject.file_path if filepath is None: self.tw.showlabel('nojournal', filepath) return pixbuf = None try: pixbufsmall = gtk.gdk.pixbuf_new_from_file_at_size( filepath, 40, 40) pixbufoff = gtk.gdk.pixbuf_new_from_file_at_size(filepath, 40, 40) except: self.tw.showlabel('nojournal', filepath) debug_output("Couldn't open food image %s" % (filepath), self.tw.running_sugar) return def _draw_pixbuf(cr, pixbuf, x, y, w, h): # Build a gtk.gdk.CairoContext from a cairo.Context to access # the set_source_pixbuf attribute. cc = gtk.gdk.CairoContext(cr) cc.save() # center the rotation on the center of the image cc.translate(x + w / 2., y + h / 2.) cc.translate(-x - w / 2., -y - h / 2.) cc.set_source_pixbuf(pixbuf, x, y) cc.rectangle(x, y, w, h) cc.fill() cc.restore() if self.tw.running_sugar: path = os.path.join(get_path(self.tw.activity, 'instance'), 'output.svg') else: path = TMP_SVG_PATH svg_surface = cairo.SVGSurface(path, 40, 40) cr_svg = cairo.Context(svg_surface) _draw_pixbuf(cr_svg, pixbufsmall, 0, 0, 40, 40) cr_svg.show_page() svg_surface.flush() svg_surface.finish() destination = os.path.join(self.tw.path, 'plugins', 'food', 'images', name.encode('ascii') + 'small.svg') check_output(['mv', path, destination], 'problem moving %s to %s' % (path, destination)) pixbufsmall = gtk.gdk.pixbuf_new_from_file_at_size(destination, 40, 40) self.tw.media_shapes[name.encode('ascii') + 'small'] = pixbufsmall svg_surface = cairo.SVGSurface(path, 40, 40) cr_svg = cairo.Context(svg_surface) _draw_pixbuf(cr_svg, pixbufoff, 0, 0, 40, 40) cr_svg.show_page() svg_surface.flush() svg_surface.finish() destination = os.path.join(self.tw.path, 'plugins', 'food', 'images', name.encode('ascii') + 'off.svg') check_output(['mv', path, destination], 'problem moving %s to %s' % (path, destination)) # Now that we have the images, we can make the new block self._make_polynominal(palette, name.encode('ascii'), name, [calories, protein, carbohydrates, fiber, fat], expand=(15, 15)) pixbufoff = gtk.gdk.pixbuf_new_from_file_at_size(destination, 40, 40) self.tw.media_shapes[name.encode('ascii') + 'off'] = pixbufoff # Show the new block self.tw.show_toolbar_palette(palette_name_to_index('food'), regenerate=True) # Finally, we need to save new food item to a database so it # loads next time. food = name.encode('ascii') self.food_dictionary[food] = {} self.food_dictionary[food]['name'] = name self.food_dictionary[food]['calories'] = calories self.food_dictionary[food]['protein'] = protein self.food_dictionary[food]['carbohydrates'] = carbohydrates self.food_dictionary[food]['fiber'] = fiber self.food_dictionary[food]['fat'] = fat path = os.path.join(self.tw.path, 'plugins', 'food', 'food.db') data_to_file(self.food_dictionary, path) return
def _status_report(self): debug_output('Reporting camera status: %s' % (str(self._status)), self._parent.running_sugar) return self._status
def _status_report(self): debug_output('Reporting accelerator status: %s' % (str(self._status))) return self._status
def _status_report(self): debug_output('Reporting RFID status: %s' % (str(self._status))) return self._status
def _status_report(self): debug_output('Reporting light-sensor status: %s' % (str(self._status))) return self._status
def __init__(self, callable1, parent, mode=None, bias=None, gain=None, boost=None): """ Initialize the class: callable1 is a data buffer; parent is the parent class""" self.callable1 = callable1 self.parent = parent self.sensor = None self.temp_buffer = [0] self.rate = RATE # Force XO1 and XO4 to use just 1 channel if self.parent.hw in [XO1, XO4]: self.channels = 1 else: self.channels = None self._dc_control = None self._mic_bias_control = None self._capture_control = None self._mic_boost_control = None self._labels_available = True # Query controls for device names self._query_mixer() # If Channels was not found in the Capture controller, guess. if self.channels is None: debug_output('Guessing there are 2 channels', self.parent.running_sugar) self.channels = 2 # Set mixer to known state self.set_dc_mode(DC_MODE_ENABLE) self.set_bias(BIAS) self.set_capture_gain(CAPTURE_GAIN) self.set_mic_boost(MIC_BOOST) self.master = self.get_master() self.dc_mode = self.get_dc_mode() self.bias = self.get_bias() self.capture_gain = self.get_capture_gain() self.mic_boost = self.get_mic_boost() # Set mixer to desired state self._set_sensor_type(mode, bias, gain, boost) self.dc_mode = self.get_dc_mode() self.bias = self.get_bias() self.capture_gain = self.get_capture_gain() self.mic_boost = self.get_mic_boost() # Set up gstreamer pipeline self._pad_count = 0 self.pads = [] self.queue = [] self.fakesink = [] self.pipeline = gst.Pipeline('pipeline') self.alsasrc = gst.element_factory_make('alsasrc', 'alsa-source') self.pipeline.add(self.alsasrc) self.caps1 = gst.element_factory_make('capsfilter', 'caps1') self.pipeline.add(self.caps1) caps_str = 'audio/x-raw-int,rate=%d,channels=%d,depth=16' % ( RATE, self.channels) self.caps1.set_property('caps', gst.caps_from_string(caps_str)) if self.channels == 1: self.fakesink.append(gst.element_factory_make('fakesink', 'fsink')) self.pipeline.add(self.fakesink[0]) self.fakesink[0].connect('handoff', self.on_buffer, 0) self.fakesink[0].set_property('signal-handoffs', True) gst.element_link_many(self.alsasrc, self.caps1, self.fakesink[0]) else: if not hasattr(self, 'splitter'): self.splitter = gst.element_factory_make('deinterleave') self.pipeline.add(self.splitter) self.splitter.set_properties('keep-positions=true', 'name=d') self.splitter.connect('pad-added', self._splitter_pad_added) gst.element_link_many(self.alsasrc, self.caps1, self.splitter) for i in range(self.channels): self.queue.append(gst.element_factory_make('queue')) self.pipeline.add(self.queue[i]) self.fakesink.append(gst.element_factory_make('fakesink')) self.pipeline.add(self.fakesink[i]) self.fakesink[i].connect('handoff', self.on_buffer, i) self.fakesink[i].set_property('signal-handoffs', True) self.dont_queue_the_buffer = False # Timer for interval sampling and switch to indicate when to capture self.capture_timer = None self.capture_interval_sample = False
def _status_report(self): debug_output( 'Reporting audio sensor status: %s' % (str(self._status)), self._parent.running_sugar) return self._status
def init_gconf(self): try: self.gconf_client = gconf.client_get_default() except Exception, err: debug_output(_('ERROR: cannot init GCONF client: %s') % err) self.gconf_client = None