Example #1
0
    def Connect(self, unused_props, return_cb, raise_cb, **kwargs):
        """Connect the modem to the network.

        Args:
            unused_props: connection properties. See ModemManager documentation.
            return_cb: function to call to return result asynchronously.
            raise_cb: function to call to raise an error asynchronously.
        """
        def ConnectDone(new, why):
            logging.info('Modem: ConnectDone %s -> %s because %s',
                         str(self.state), str(new), str(why))
            if self.state == mm1.MM_MODEM_STATE_CONNECTING:
                self.ChangeState(new, why)
                # TODO(jglasgow): implement a bearer object
                bearer_path = '/Bearer/0'
                return_cb(bearer_path)
            else:
                raise_cb(mm1.ConnectionUnknownError())

        logging.info('Modem: Connect')
        if self.state != mm1.MM_MODEM_STATE_REGISTERED:
            logging.info(
                'Modem: Connect fails on unregistered modem.  State = %s',
                self.state)
            raise mm1.NoNetworkError()
        delay_ms = kwargs.get('connect_delay_ms', DEFAULT_CONNECT_DELAY_MS)
        time.sleep(delay_ms / 1000.0)
        self.ChangeState(mm1.MM_MODEM_STATE_CONNECTING)
        glib.timeout_add(
            50, lambda: ConnectDone(
                mm1.MM_MODEM_STATE_CONNECTED, mm1.
                MM_MODEM_STATE_CHANGE_REASON_USER_REQUESTED))
Example #2
0
    def callThymio(self):
        # if no loop is running, skip function
        print("running call Thymio")
        if not self.loop.is_running():
            return

        # send speed command

        motorLeftTarget = 0
        motorRightTarget = 0
        self.asebaNetwork.SendEventName('SetSpeed',
                                        [motorLeftTarget, motorRightTarget],
                                        reply_handler=self.dbusReply,
                                        error_handler=self.dbusError
                                        )

        # send color command

        self.asebaNetwork.SendEventName('SetColor',
                                        [ 6, 13, 32],
                                        reply_handler=self.dbusReply,
                                        error_handler=self.dbusError
                                        )

        # read and display horizontal sensors
        proxHorizontal = self.asebaNetwork.GetVariable(
            'thymio-II', 'prox.horizontal')

        acc = self.asebaNetwork.GetVariable(
            'thymio-II', 'acc')
        print("prox.horizontal: " + (', '.join(map(str, proxHorizontal))) + "\t acc: " + (', '.join(map(str, acc))))

        # reschedule scan of joystick
        glib.timeout_add(20, self.callThymio)
Example #3
0
	def SegmentDataResponse(self, dev, pmstore_handle, pmsegment, response):
		print
		print "SegmentDataResponse dev %s PM-Store handle %d" % (dev, pmstore_handle)
		print "=== InstNumber %d" % pmsegment
		print "=== Response %s" % getsegmentdata_response_interpret(response)
		if response != 0 and pmsegment < 7:
			dev = bus.get_object("com.signove.health", dev)
			dev = dbus.Interface(dev, "com.signove.health.device")
			glib.timeout_add(0, getSegmentData, dev, pmstore_handle, pmsegment + 1)
Example #4
0
	def Connected(self, dev, addr):
		print
		print "Connected from addr %s, dev %s" % (addr, dev)

		# Convert path to an interface
		dev = bus.get_object("com.signove.health", dev)
		dev = dbus.Interface(dev, "com.signove.health.device")

		glib.timeout_add(0, do_something, dev)
    def __init__(self, filename):
        # init the main loop and sends the ASEBA code to the Thymio bot for the on-robot computations
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        # get stub of the Aseba network
        bus = dbus.SessionBus()
        asebaNetworkObject = bus.get_object('ch.epfl.mobots.Aseba', '/')
        self.asebaNetwork = dbus.Interface(
            asebaNetworkObject, dbus_interface='ch.epfl.mobots.AsebaNetwork')

        # load the file
        self.asebaNetwork.LoadScripts(sys.argv[1],
                                      reply_handler=self.dbusReply,
                                      error_handler=self.dbusError)

        # schedules first interaction with the Robot
        glib.timeout_add(20, self.callThymio)
Example #6
0
 def Enable(self, on, *args, **kwargs):
     """Enables the Modem."""
     logging.info('Modem: Enable %s', str(on))
     if on:
         if self.state <= mm1.MM_MODEM_STATE_ENABLING:
             self.ChangeState(mm1.MM_MODEM_STATE_ENABLING)
         if self.state <= mm1.MM_MODEM_STATE_ENABLED:
             self.ChangeState(mm1.MM_MODEM_STATE_ENABLED)
         if self.state <= mm1.MM_MODEM_STATE_SEARCHING:
             self.ChangeState(mm1.MM_MODEM_STATE_SEARCHING)
         glib.timeout_add(250, self.OnRegistered)
     else:
         if self.state >= mm1.MM_MODEM_STATE_DISABLING:
             self.ChangeState(mm1.MM_MODEM_STATE_DISABLING)
         if self.state >= mm1.MM_MODEM_STATE_DISABLED:
             self.ChangeState(mm1.MM_MODEM_STATE_DISABLED)
             self.ChangeRegistrationState(
                 mm1.MM_MODEM_3GPP_REGISTRATION_STATE_IDLE)
     return None
    def callThymio(self):
        # if no loop is running, skip function
        print("calling Thymio")
        if not self.loop.is_running():
            return

        distanceCM = int(input("Distance in CM: "))
        thymioSpeed = int(input("Speed: "))

        print("executing DriveCM with parameter CM= " + str(distanceCM) +
              " and speed= " + str(thymioSpeed))

        self.asebaNetwork.SendEventName('DriveCM', [distanceCM, thymioSpeed],
                                        reply_handler=self.dbusReply,
                                        error_handler=self.dbusError)
        if input("Play again? y/n") == "n":
            self.loop.quit()

        # reschedule scan of joystick
        glib.timeout_add(20, self.callThymio)
Example #8
0
    def Connected(self, dev, addr):
        global devAddr
        print
        print "Connected from addr %s, dev %s" % (addr, dev)

        # H&C
        devAddr = addr
        if devAddr == NONIN_PULSEOXYMETER_BT_ADDR:
            print "*** Nonin PulseOxymeter"
        elif devAddr == OMRON_SCALE_BT_ADDR:
            print "*** Omron Scale"
        elif devAddr == OMRON_SPHYGMOMANOMETER_BT_ADDR:
            print "*** Omron SphygmoManometer"
        else:
            device = "Unknown device"

            # Convert path to an interface
        dev = bus.get_object("com.signove.health", dev)
        dev = dbus.Interface(dev, "com.signove.health.device")

        glib.timeout_add(0, do_something, dev)
Example #9
0
    def Disconnect(self, bearer, return_cb, raise_cb, **kwargs):
        """Disconnect the modem from the network."""
        def DisconnectDone(old, new, why):
            logging.info('Modem: DisconnectDone %s -> %s because %s', str(old),
                         str(new), str(why))
            if self.state == mm1.MM_MODEM_STATE_DISCONNECTING:
                logging.info('Modem: State is DISCONNECTING, changing to %s',
                             str(new))
                self.ChangeState(new)
                return_cb()
            elif self.state == mm1.MM_MODEM_STATE_DISABLED:
                logging.info('Modem: State is DISABLED, not changing state')
                return_cb()
            else:
                raise_cb(mm1.ConnectionUnknownError())

        logging.info('Modem: Disconnect')
        self.ChangeState(mm1.MM_MODEM_STATE_DISCONNECTING)
        glib.timeout_add(
            500, lambda: DisconnectDone(
                self.state, mm1.MM_MODEM_STATE_REGISTERED, mm1.
                MM_MODEM_STATE_CHANGE_REASON_USER_REQUESTED))
Example #10
0
    def __init__(self, encoder, recorder, metadata, tmp_name):
        """Recording the stream.

        :encoder:  lame encoding subprocess
        :recorder: pulse audio recording subprocess
        :metadata: track information from dbus event
        :tmp_name: temporary file name for the recording

        """
        self.encoder = encoder
        self.recorder = recorder
        self.metadata = metadata
        self.tmp_name = tmp_name

        length = metadata['Metadata']["mpris:length"]
        # avoid recording the beginning of the next track
        milli_secs = length * 1E-3 - 750
        self.finished_ts = time.time() + length / 1E6

        # handler that stops recording of track
        self.timeout_handler = glib.timeout_add(int(milli_secs),
                                                   self.stop_recording_cb)
Example #11
0
        output_file = sys.argv[2]
        input_file  = sys.argv[4]
        path_output  = os.path.abspath(output_file)
        path_input   = os.path.abspath(input_file)
  
        if not os.path.isfile(path_output):
            print_usage()
  
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        a = EvinceWindowProxy('file://' + path_output, True )
    
        def sync_view(ev_window, path_input, line_number):
            ev_window.SyncView (path_input, (line_number, 1))
            exit(0)

        glib.timeout_add(400, sync_view, a, path_input, line_number)
        loop = gobject.MainLoop()
        loop.run() 

    elif sys.argv[1] == 'GVIM':
        gvim_server_name = sys.argv[2]
        output_file = sys.argv[3]
        input_file  = sys.argv[4]
        path_output  = os.path.abspath(output_file)
        path_input   = os.path.abspath(input_file)
  
        if not os.path.isfile(path_input):
            print_usage()

        def source_view_handler(input_file, source_link):
            if input_file[:7] == "file://":
    def run(self, test):
        # Init ini files.
        if not os.path.exists(self.data_newest_id_path):
            self.newest_data_id_config = Config(self.data_newest_id_path)
            self.newest_data_id_config.load()
            self.newest_data_id_config.set("newest", "data_id", "")
            self.newest_data_id_config.set("newest", "update_date", "")
            self.newest_data_id_config.write()
        else:
            self.newest_data_id_config = Config(self.data_newest_id_path)
            self.newest_data_id_config.load()
            
        try:
            update_date = self.newest_data_id_config.get("newest", "update_date")
        except Exception:
            update_date = ""

        if self.newest_data_id_config.get("newest", "data_id") == "" or update_date != UPDATE_DATE:
            self.clean()
            newest_data_id = self.get_unique_id()
            newest_data_dir = os.path.join(DATA_DIR, "update", newest_data_id)
            
            print "进行第一次数据解压..."
            log("进行第一次数据解压...")
            for data_file in os.listdir(self.data_origin_dir):
                with tarfile.open(os.path.join(self.data_origin_dir, data_file), "r:gz") as tar_file:
                    tar_file.extractall(newest_data_dir)
            print "进行第一次数据解压完成"
            log("进行第一次数据解压完成")
            
            self.newest_data_id_config.set("newest", "data_id", newest_data_id)
            self.newest_data_id_config.set("newest", "update_date", UPDATE_DATE)
            self.newest_data_id_config.write()
            
        if not os.path.exists(self.data_patch_config_filepath):
            self.patch_status_config = Config(self.data_patch_config_filepath)
            self.patch_status_config.load()
            for space_name in DATA_SPACE_NAME:
                self.patch_status_config.set("data_md5", space_name, "")
            self.patch_status_config.write()
        else:
            self.patch_status_config = Config(self.data_patch_config_filepath)
            self.patch_status_config.load()
        
        self.have_update = []
        # Download update data.
        for data_file in os.listdir(self.data_origin_dir):
            self.download_data(data_file, test)
            
        if self.have_update:
            # Apply update data.
            for space_name in self.have_update:
                self.apply_data(space_name)
                
            # Extra data.
            newest_data_id = self.get_unique_id()
            newest_data_dir = os.path.join(DATA_DIR, "update", newest_data_id)

            for space_name in DATA_SPACE_NAME:
                data_filename = "%s.tar.gz" % space_name
                origin_data_file = os.path.join(self.data_origin_dir, data_filename)
                newest_data_file = os.path.join(self.data_newest_dir, data_filename)
                if not os.path.exists(newest_data_file):
                    os.system('cp %s %s' % (origin_data_file, newest_data_file))
            
            print "解压最新数据..."
            log("解压最新数据...")
            for data_file in os.listdir(self.data_newest_dir):
                newest_file = os.path.join(self.data_newest_dir, data_file)
                with tarfile.open(newest_file, "r:gz") as tar_file:
                    tar_file.extractall(newest_data_dir)
            print "解压最新数据完成"
            log("解压最新数据完成")
            
            self.previous_data_id = self.newest_data_id_config.get("newest", "data_id")
            self.newest_data_id_config.set("newest", "data_id", newest_data_id)
            self.newest_data_id_config.write()

        if self.is_fontend_running():
            print 'Frontend is running, clear data next time!'
            log('Frontend is running, clear data next time!')
        else:
            print 'Clear unused data.'
            log('Clear unused data.')
            self.clear_data_folder()

        print 'Done!'
        log("Done!")
        glib.timeout_add(200, self.mainloop.quit)
Example #13
0
    import dbus.mainloop.glib, gobject, glib, sys, os

    def print_usage():
        print '''
The usage is evince_dbus output_file line_number input_file from the directory of output_file. 
'''
        sys.exit(1)

    if len(sys.argv) != 4:
        print_usage()
    try:
        line_number = int(sys.argv[2])
    except ValueError:
        print_usage()

    output_file = sys.argv[1]
    input_file = sys.argv[3]
    path_output = os.getcwd() + '/' + output_file
    path_input = os.getcwd() + '/' + input_file

    if not os.path.isfile(path_output):
        print_usage()

    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    bus = dbus.SessionBus()

    a = EvinceWindowProxy(bus, 'file://' + path_output, True)
    glib.timeout_add(1000, a.SyncView, path_input, (line_number, 1))
    loop = gobject.MainLoop()
    loop.run()
        output_file = sys.argv[2]
        input_file = sys.argv[4]
        path_output = os.path.abspath(output_file)
        path_input = os.path.abspath(input_file)

        if not os.path.isfile(path_output):
            print_usage()

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        a = EvinceWindowProxy('file://' + path_output, True)

        def sync_view(ev_window, path_input, line_number):
            ev_window.SyncView(path_input, (line_number, 1))
            exit(0)

        glib.timeout_add(400, sync_view, a, path_input, line_number)
        loop = gobject.MainLoop()
        loop.run()

    elif sys.argv[1] == 'GVIM':
        gvim_server_name = sys.argv[2]
        output_file = sys.argv[3]
        input_file = sys.argv[4]
        path_output = os.path.abspath(output_file)
        path_input = os.path.abspath(input_file)

        if not os.path.isfile(path_input):
            print_usage()

        def source_view_handler(input_file, source_link):
            if input_file[:7] == "file://":
Example #15
0
	def make_notif(self, title, body, time, icon=None, urgency="Normal", first=False, timeout=None):
		#if not first:
		#	hsep = gtk.HSeparator()
		#	self.vb.pack_start(hsep, False, False)

		# HBox needs an eventbox to draw a background
		hbox = gtk.HBox()
		hbox.set_border_width(4)
		eb = gtk.EventBox()
		eb.add(hbox)
		eb.set_border_width(1)
		stroke = gtk.EventBox()
		stroke.add(eb)

		cmap = self.get_colormap()
		#error_bg_color = gtk.gdk.color_parse("#0f0")
		gtk.info_bg_color = cmap.alloc_color("#00ff00", True, False)

		# adjust colors
		if urgency == "critical" :
			eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color("#ed3333"))
			stroke.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color("#822b2b"))
		else :
			eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color("#ffffff"))
			stroke.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color("#828282"))

		# create image
		image = gtk.Image()
		if( icon ):
			image.set_from_file(icon)
			hbox.pack_start(image, False, False, 8)
		else:
			if urgency == "critical" :
				image.set_from_stock(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_DIALOG)
			else:
				image.set_from_stock(gtk.STOCK_DIALOG_INFO, gtk.ICON_SIZE_DIALOG)
			hbox.pack_start(image, False, False, 13)

		# for text boxes
		vbox = gtk.VBox()

		# make some labels
		title_label = gtk.Label()
		title_label.set_markup("<b>" +title +"</b>")
		body_label = gtk.Label(body)

		# adjust alignment
		title_label.set_alignment(0, 1)
		body_label.set_alignment(0, 0)
		body_label.set_line_wrap(True)

		# pack the text views
		vbox.pack_start(title_label, True, True)
		vbox.pack_start(body_label, True, True)

		# pack the textview combos
		hbox.pack_start(vbox, True, True)

		# new vbox
		vbox = gtk.VBox(False)

		# make time label
		time_label = gtk.Label()
		time_label.set_markup("<small>" +time +"</small>")
		time_label.set_alignment(1, 1)

		# add time
		vbox.pack_end(time_label, True, True)

		# button
		button = gtk.Button("", gtk.STOCK_CLOSE)
		button.connect( "clicked", self._on_close_clicked, stroke)

		stroke.connect( "event", self._on_bar_doubleclicked, body_label.get_text())

		# dead space
		alignment = gtk.Alignment(1.0, 1.0, 0.0, 0.0)
		alignment.add(button)
		vbox.pack_start(alignment)

		hbox.pack_start(vbox, True, True)


		# add to bar, then main window
		self.vb.pack_start(stroke, False, False)
		#self.vb.pack_start(bar, False, False)
		self.vb.show_all()

		if timeout:
			print "got notification with timeout", timeout
			glib.timeout_add(int(timeout), self._invalidate_notification, stroke)
	
	def print_usage():
	        print '''
The usage is evince_dbus output_file line_number input_file from the directory of output_file. 
'''
		sys.exit(1)

	
	if len(sys.argv)!=4:
		print_usage()
	try:
		line_number = int(sys.argv[2])
	except ValueError:
		print_usage()
	
	output_file = sys.argv[1]
	input_file  = sys.argv[3]
	path_output  = os.getcwd() + '/' + output_file
	path_input   = os.getcwd() + '/' + input_file

	if not os.path.isfile(path_output):
		print_usage()

	dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
	bus = dbus.SessionBus()

 	a = EvinceWindowProxy(bus, 'file://' + path_output, True )
	glib.timeout_add(1000, a.SyncView, path_input, (line_number,1))
	loop = gobject.MainLoop()
	loop.run() 
Example #17
0
	def Associated(self, dev, xmldata):
		print
		print "Associated dev %s: XML with %d bytes" % (dev, len(xmldata))

		print "System ID: %s" % get_system_id(dev, xmldata)
		dump(dev, "associated", xmldata)
		
		# Convert path to an interface
		devpath = dev
		dev = bus.get_object("com.signove.health", dev)
		dev = dbus.Interface(dev, "com.signove.health.device")

		glib.timeout_add(0, getConfiguration, dev, devpath)
		if clear_segment == 1:
			glib.timeout_add(1000, clearSegment, dev, pmstore_handle, pmsegment_instance)
			return
		elif clear_segment == 2:
			glib.timeout_add(1000, clearAllSegments, dev, pmstore_handle)
			return

		if get_mds:
			glib.timeout_add(1000, requestMdsAttributes, dev)
		if set_time:
			glib.timeout_add(800, setTime, dev)
		if get_pmstore:
			glib.timeout_add(2000, getPMStore, dev, pmstore_handle)
			glib.timeout_add(3000, getSegmentInfo, dev, pmstore_handle)
		if get_segment:
			glib.timeout_add(5000, getSegmentData, dev, pmstore_handle, pmsegment_instance)