def evaluate(self, evaluee): self.frame_rate_counter = 0 self.step_time = time.time() global ctrl_client if ctrl_client and not self.ctrl_thread_started: thread.start_new_thread(check_stop, (self, )) self.ctrl_thread_started = True self.evaluations_taken = 0 self.energy = INITIAL_ENERGY self.fitness = 0 self.presence = self.prev_presence = (None, None) self.loop = gobject.MainLoop() def update_energy(task, energy): task.energy += energy def main_lambda(task): if task.energy <= 0 or task.evaluations_taken >= MAX_STEPS: self.motorLock.acquire() stopThymio(thymioController) self.motorLock.release() task.loop.quit() if task.energy <= 0: print 'Energy exhausted' else: print 'Time exhausted' return False callback = lambda (psvalues): self.cameraCallback( evaluee, lambda (energy): update_energy(task, energy), psvalues) if not self.camera.isAlive(): print "starting camera" #Call the camera asynchroniously. Call the callback when the presence values are ready. self.camera.start_camera(callback, self.cameraErrorCallback) print "camera started" else: self.camera.update_callback(callback) self.cameraWait() return True gobject.timeout_add(int(self.timeStep * 1000), lambda: main_lambda(self)) print 'Starting loop...' self.loop.run() fitness = self.getFitness() print 'Fitness at end: %d' % fitness if self.camera.isAlive(): # self.camera.stop() self.camera.pause() # self.camera.join() self.motorLock.acquire() stopThymio(self.thymioController) self.motorLock.release() time.sleep(1) self.individuals_evaluated += 1 return {'fitness': fitness}
def main(): # Argument parsing parser = argparse.ArgumentParser(description='dummy dbus service') parser.add_argument("-n", "--name", help="the D-Bus service you want me to claim", type=str, default="com.victronenergy.battery.socketcan_can0") parser.add_argument("parent", help="battery service to proxy for", type=str, default="com.victronenergy.battery.ttyO0") args = parser.parse_args() logging.basicConfig(level=logging.INFO) # Have a mainloop, so we can send/receive asynchronous calls to and from dbus DBusGMainLoop(set_as_default=True) s = DbusDummyService(servicename=args.name, deviceinstance=0, paths={ '/Alarms/CellImbalance': { 'initial': 0 }, '/Alarms/HighChargeCurrent': { 'initial': 0 }, '/Alarms/HighChargeTemperature': { 'initial': 0 }, '/Alarms/HighDischargeCurrent': { 'initial': 0 }, '/Alarms/HighTemperature': { 'initial': 0 }, '/Alarms/HighVoltage': { 'initial': 0 }, '/Alarms/InternalFailure': { 'initial': 0 }, '/Alarms/LowChargeTemperature': { 'initial': 0 }, '/Alarms/LowTemperature': { 'initial': 0 }, '/Alarms/LowVoltage': { 'initial': 0 }, '/Soc': { 'initial': None }, '/Dc/0/Voltage': { 'initial': None }, '/Dc/0/Current': { 'initial': None }, '/Dc/0/Power': { 'initial': None }, '/Dc/0/Temperature': { 'initial': 23.8 }, '/Info/BatteryLowVoltage': { 'initial': None }, '/Info/MaxChargeCurrent': { 'initial': None }, '/Info/MaxChargeVoltage': { 'initial': None }, '/Info/MaxDischargeCurrent': { 'initial': None }, }, productname='ACME BMS battery', connection='CAN-bus') logger.info('Connected to dbus') # Track some items and reflect them conn = s._dbusservice._dbusconn track(conn, args.parent, '/Dc/0/Voltage', partial(_set_value, s, '/Dc/0/Voltage')) track(conn, args.parent, '/Dc/0/Current', partial(_set_value, s, '/Dc/0/Current')) track(conn, args.parent, '/Dc/0/Power', partial(_set_value, s, '/Dc/0/Power')) track(conn, args.parent, '/Soc', partial(_set_value, s, '/Soc')) logger.info('Switching over to gobject.MainLoop() (= event based)') mainloop = gobject.MainLoop() mainloop.run()
#!/usr/bin/env python2 # Replace gnome-screensaver or light-locker DBus service to call xscreensaver # http://ubuntuforums.org/showthread.php?t=1865593&s=1c7f28c50a3f258e1d3404e41f098a0b&p=11418175#post11418175 import dbus import dbus.service import dbus.glib import gobject import subprocess class ScreenDbusObj(dbus.service.Object): def __init__(self): session_bus = dbus.SessionBus() #bus_name=dbus.service.BusName("org.freedesktop.ScreenSaver",bus=session_bus) bus_name = dbus.service.BusName("org.gnome.ScreenSaver", bus=session_bus) #dbus.service.Object.__init__(self,bus_name, '/org/freedesktop/ScreenSaver') dbus.service.Object.__init__(self, bus_name, '/org/gnome/ScreenSaver') #@dbus.service.method("org.freedesktop.ScreenSaver") @dbus.service.method("org.gnome.ScreenSaver") def Lock(self): subprocess.Popen(['xscreensaver-command', '-lock']) if __name__ == '__main__': object = ScreenDbusObj() gobject.MainLoop().run()
def wait_for_property_in(self, dbus_object, property_name, expected_values, timeout_seconds): """Wait till a property is in a list of expected values. Block until the property |property_name| in |dbus_object| is in |expected_values|, or |timeout_seconds|. @param dbus_object DBus proxy object as returned by self.get_dbus_object. @param property_name string property key in dbus_object. @param expected_values iterable set of values to return successfully upon seeing. @param timeout_seconds float number of seconds to return if we haven't seen the appropriate property value in time. @return tuple(successful, final_value, duration) where successful is True iff we saw one of |expected_values| for |property_name|, final_value is the member of |expected_values| we saw, and duration is how long we waited to see that value. """ start_time = time.time() duration = lambda: time.time() - start_time update_queue = collections.deque() signal_receiver = lambda key, value: update_queue.append((key, value)) receiver_ref = self._bus.add_signal_receiver( signal_receiver, signal_name='PropertyChanged', dbus_interface=dbus_object.dbus_interface, path=dbus_object.object_path) try: # Check to make sure we're not already in a target state. try: properties = self.dbus2primitive( dbus_object.GetProperties(utf8_strings=True)) last_value = properties.get(property_name, '(no value found)') if last_value in expected_values: return True, last_value, duration() except dbus.exceptions.DBusException: return False, '(object reference became invalid)', duration() context = gobject.MainLoop().get_context() while duration() < timeout_seconds: # Dispatch all pending events. while context.iteration(False): pass while update_queue: updated_property, value = map(self.dbus2primitive, update_queue.popleft()) if property_name != updated_property: continue last_value = value if not last_value in expected_values: continue return True, last_value, duration() time.sleep(0.2) # Give that CPU a break. CPUs love breaks. finally: receiver_ref.remove() return False, last_value, duration()
if menu_id == "New Task": self.gtg.open_new_task() elif menu_id == "Open Tasks List": self.gtg.show_task_browser() class GTGSink(DockManagerSink): def item_path_found(self, pathtoitem, item): if item.Get(DOCKITEM_IFACE, "DesktopFile", dbus_interface="org.freedesktop.DBus.Properties").endswith( "gtg.desktop"): self.items[pathtoitem] = GTGItem(self, pathtoitem) gtgsink = GTGSink() def cleanup(): gtgsink.dispose() if __name__ == "__main__": mainloop = gobject.MainLoop(is_running=True) atexit.register(cleanup) signal(SIGTERM, lambda signum, stack_frame: exit(1)) mainloop.run()
def get_mainloop(cls): """ Override this method to use another event loop than the default one. Should not be needed most of the time, apart if the node is part of a GUI application. """ return gobject.MainLoop()
self.player.set_state(gst.STATE_NULL) self.is_playing = False self.error_msg = message.parse_error() elif msgType == gst.MESSAGE_EOS: self.player.set_state(gst.STATE_NULL) self.is_playing = False def printFinalStatus(self, starttime, endtime): """ Print the final status message. """ if self.error_msg: print self.error_msg else: print "\n Done!" print "\n Audio and video tracks separated and saved as "\ "following files" print "\n audio:%s \n video:%s" % (self.audioOutLocation, self.videoOutLocation) print "\n Approximate time required : \ %.4f seconds" % (endtime - starttime) # Run the program player = AudioSeparator() thread.start_new_thread(player.play, ()) gobject.threads_init() evt_loop = gobject.MainLoop() evt_loop.run()
if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('--device', '-d', default='/dev/ttyHS1') group.add_argument('--file', '-f', default=None) parser.add_argument('--output', '-o', default=None) parser.add_argument('--raw', action='store_true') args = parser.parse_args() logging.basicConfig(level=logging.WARNING) if args.output is not None: outputFile = open(args.output, 'wb') if args.device: t = ubx.Parser(callback, device=args.device, rawCallback=rawCallback) try: gobject.MainLoop().run() except KeyboardInterrupt: gobject.MainLoop().quit() if outputFile is not None: outputFile.close() else: t = ubx.Parser(callback, device=False) binFile = args.file data = open(binFile, 'r').read() t.parse(data)
import time import gobject gobject.threads_init() try: import evdev except ImportError: evdev = False if evdev: from mopidy_evtdev import agent from mopidy.core import PlaybackState context = gobject.MainLoop().get_context() def iterate_main(): while context.pending(): context.iteration(False) class EvtDevAgentTestCorners(unittest.TestCase): def setUp(self): self.core = mock.Mock() self.path = '/dev/input' self.dev = 'event0' self.refresh_period = 0.1 self.vol_step_size = 10
def main(): logging.basicConfig(level=logging.INFO) config = ConfigParser.ConfigParser() config.read('config.ini') api_key = get_api_key(config) city_id = get_city_id(config) useweather = int(get_weather_active(config)) if useweather == 1: weather = get_weather(api_key, city_id) else: weather = None #print(weather) INTERVAL = int(get_interval(config)) PVOUTPUT = get_pvoutput(config) APIKEY = get_pvoutput_api(config) SYSTEMID = get_pvoutput_systemid(config) DBusGMainLoop(set_as_default=True) conn = dbus.SystemBus() generators = smart_dict() consumers = smart_dict() stats = smart_dict() voltages = smart_dict() # Set the user timezone if 'TZ' not in os.environ: tz = query(conn, "com.victronenergy.settings", "/Settings/System/TimeZone") if tz is not None: os.environ['TZ'] = tz # Find solarcharger services solarchargers = find_services(conn, 'solarcharger') logger.info("Found solarchargers at %s", ', '.join(solarchargers)) # Find grid meters meters = find_services(conn, 'grid') logger.info("Found grid meters at %s", ', '.join(meters)) # Find vebus service vebus = str(query(conn, "com.victronenergy.system", "/VebusService")) logger.info("Found vebus at %s", vebus) # Track solarcharger yield for charger in solarchargers: track(conn, generators, charger, "/Yield/User", charger) # Track grid consumption for meter in meters: track(conn, consumers, meter, "/Ac/L1/Energy/Forward", meter) # Track vebus consumption, from battery to input and output track(conn, consumers, vebus, "/Energy/InverterToAcOut", "c1") track(conn, consumers, vebus, "/Energy/InverterToAcIn1", "c2") # Track power values track(conn, stats, "com.victronenergy.system", "/Ac/Consumption/L1/Power", "pc") track(conn, stats, "com.victronenergy.system", "/Dc/Pv/Power", "pg") track(conn, voltages, vebus, "/Ac/Out/L1/V", "vo") # Periodic work def _upload(): if useweather == 1: try: weather = get_weather(api_key, city_id) except: weather = None pass else: weather = None energy_generated = sum(filter(None, generators.itervalues())) energy_consumed = sum(filter(None, consumers.itervalues())) logger.info("EG: %.2f, EC: %.2f, PG: %.2f, PC: %.2f, VO: %.2f", energy_generated, energy_consumed, stats.pg, stats.pc, voltages.vo) # Post the values to pvoutput now = datetime.now() if (weather is not None): payload = { "d": now.strftime("%Y%m%d"), "t": now.strftime("%H:%M"), "v1": int(energy_generated * 1000), "v2": int(stats.pg), "v3": int(energy_consumed * 1000), "v4": int(stats.pc), "v5": float(weather['main']['temp']), "v6": float(voltages.vo), "c1": 1 } else: payload = { "d": now.strftime("%Y%m%d"), "t": now.strftime("%H:%M"), "v1": int(energy_generated * 1000), "v2": int(stats.pg), "v3": int(energy_consumed * 1000), "v4": int(stats.pc), "v6": float(voltages.vo), "c1": 1 } try: requests_retry_session().post(PVOUTPUT, headers={ "X-Pvoutput-Apikey": APIKEY, "X-Pvoutput-SystemId": SYSTEMID }, data=payload) except: print("Fail on Post") pass return True _upload() gobject.timeout_add(INTERVAL, _upload) gobject.MainLoop().run()
def _setup_loop(self): self._loop = gobject.MainLoop() self._thread = threading.Thread(target=self._loop.run) self._thread.start()
def processArguments(): '''init process arguments ''' parser = OptionParser(usage="Usage: deepin-screenshot [options] [arg]", version="deepin-screenshot v2.1") parser.add_option("-f", "--full", action="store_true", dest="fullscreen", help=_("Take a screenshot of full screen")) parser.add_option("-w", "--window", action="store_true", dest="window", help=_("Take a screenshot of the window")) parser.add_option("-d", "--delay", dest="delay", type="int", help=_("Take a screenshot after NUM seconds"), metavar="NUM") parser.add_option("-s", "--save", dest="save_file", help=_("save screenshot to FILE"), metavar="FILE") parser.add_option("--sub", action="store_true", dest="sub", help=_("run as a subprocess")) parser.add_option("-n", "--new", action="store_true", dest="new", help=_("run a new process")) parser.add_option("-I", "--icon", action="store_true", dest="icon") #parser.add_option("-a", "--area", help="Grab an area of the screen instead of the entire screen", action="store_true") #parser.add_option("-e", "--border-effect", action="store_true", dest="border_effect", help="Effect to add to the border") #parser.add_option("-i", "--interactive", action="store_true", help="Interactively set options") #parser.add_option("-b", "--include-border", action="store_true", help="Include the window border with the screenshot") #parser.add_option("-B", "--remove-border", action="store_true", help="Remove the window border from the screenshot") #parser.add_option("-c", "--clipboard", help="Send the grab directly to the clipboard", action="store_true") parser.get_option('-h').help = _("show this help message and exit") parser.get_option('--version').help = _( "show program's version number and exit") import sys if '-h' in sys.argv or '--help' in sys.argv: parser.remove_option("-I") (options, args) = parser.parse_args() if not options.new and IS_EXISTS: print "deepint-screenshot has run" exit(1) if options.fullscreen and options.window: parser.error("options -f and -w are mutually exclusive") config.OPTION_ICON = options.icon config.OPTION_FULLSCREEN = options.fullscreen config.OPTION_WINDOWN = options.window config.OPTION_NEW = options.new config.OPTION_FILE = options.save_file config.OPTION_SUB = options.sub if options.delay: notify("Deepin Screenshot", 0, summary=_("DScreenshot"), body=_("Deepin Screenshot will start in %d seconds.") % options.delay, timeout=(options.delay - 0.5) * 1000) loop = gobject.MainLoop() gobject.timeout_add_seconds(options.delay, loop.quit) loop.run() if options.save_file: parserFile = parser_path(str(options.save_file)) if options.fullscreen: pixbuf = get_screenshot_pixbuf(True) pixbuf.save(parserFile[0], parserFile[1]) elif options.window: pixbuf = get_screenshot_pixbuf(False) pixbuf.save(parserFile[0], parserFile[1]) else: main() elif options.fullscreen: open_file_dialog() elif options.window: open_file_dialog(False) else: main()
return True def connection_ready(self, sock, condition): while True: try: logger.info("connection ready") conn, remote = self.socket.accept() #sock.listen(1) logger.info("accepted") self.handle_connection(conn, remote) except sk.error, e: logger.error(e) if e[0] not in (errno.EWOULDBLOCK, errno.EAGAIN): raise return True if __name__ == '__main__': from time import time b = StreamServer('', 10000) b.create_server_socket() def say_hello(b): print "saying hello" b.send_to_all("%s Hello world\n" % time()) return True gobject.timeout_add(1000, say_hello, b) b = gobject.MainLoop() b.run()
def __init__(self): super(MainLoopThread, self).__init__() self.loop = gobject.MainLoop() self.daemon = True
event_secondary_if_down.clear() dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) # Use Glib's mainloop as the default loop for all subsequent code try: bus = dbus.SystemBus() proxy = bus.get_object(DBUS_NAME, DBUS_OBJECT_ROOT) extremity_if = proxy.GetInterface(dbus_interface=DBUS_SERVICE_INTERFACE) logger.debug('Read extremity network interface ' + extremity_if + ' from D-Bus call') # If we got a D-Bus extremity interface, carry on watching D-Bus signals for interface removal def dBusInterfaceRemovedHandler(ifname, **kwargs): logger.info('Received InterfaceRemoved D-Bus signal for interface ' + ifname) if ifname == extremity_if: event_secondary_if_down.set() termination_event.set() dbus_loop = gobject.MainLoop() # Allow secondary threads to run during the mainloop gobject.threads_init() # Allow the mainloop to run as an independent thread dbus.mainloop.glib.threads_init() # Run the D-Bus thread in background dbus_loop_thread = threading.Thread(target=dbus_loop.run) dbus_loop_thread.setDaemon(True) # dbus loop should be forced to terminate when main program exits dbus_loop_thread.start() proxy.connect_to_signal('InterfaceRemoved', dBusInterfaceRemovedHandler, dbus_interface=DBUS_SERVICE_INTERFACE, message_keyword='dbus_message') # Set a callback for the InterfaceRemoved D-Bus signal
tee_audio_pad.get_name())) queue_audio_pad = data.audio_queue.get_static_pad("sink") tee_video_pad = data.tee.get_request_pad("src%d") print("Obtained request pad {0} for video branch".format( tee_video_pad.get_name())) queue_video_pad = data.video_queue.get_static_pad("sink") tee_app_pad = data.tee.get_request_pad("src%d") print("Obtained request pad {0} for app branch".format(tee_app_pad.get_name())) queue_app_pad = data.app_queue.get_static_pad("sink") if (tee_audio_pad.link(queue_audio_pad) != gst.PAD_LINK_OK or tee_video_pad.link(queue_video_pad) != gst.PAD_LINK_OK or tee_app_pad.link(queue_app_pad) != gst.PAD_LINK_OK): print >> sys.stderr, "Tee could not be linked." exit(-1) # Instruct the bus to emit signals for each received message, and connect to the interesting signals bus = data.pipeline.get_bus() bus.add_signal_watch() bus.connect("message::error", error_cb, data) #Start playing the pipeline data.pipeline.set_state(gst.STATE_PLAYING) #Create a GLib Mainloop and set it to run data.main_loop = gobject.MainLoop() data.main_loop.run() # Free resources data.pipeline.set_state(gst.STATE_NULL)
def go(): ## I think we need an object here which will poll until told to stop. ## Register some callbacks to spit out servers print "Here" import sys import time import dbus, gobject, avahi from dbus.mainloop.glib import DBusGMainLoop import string serviceType = "_wfut._tcp" servicePort = 0; serviceTXT = "" domain = "" host = "" ## Map of discovered servers servers = {} def service_add(interface, protocol, name, type, domain, flags): print "found server" ## Find out more info obj_path = server.ServiceResolverNew(interface, protocol, name, type, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0)) resolver = dbus.Interface(bus.get_object(avahi.DBUS_NAME, obj_path), avahi.DBUS_INTERFACE_SERVICE_RESOLVER) ## Hook up callbacks to 'Found' resolver.connect_to_signal('Found', found) def found(interface, protcol, name, type, domain, host, aprotocol, address, port, txt, flags): ## Construct a server url from address and port number. ## Uses '[' ']' incase of IPv6 addresses. servers[name] = "".join([ "http://", "[" , address, "]", ":", str(port)]) ## Look for a "url" txt field to override the one constructed above. txt_arr = avahi.txt_array_to_string_array(txt) for rec in txt_arr: (key, value) = rec.split("=") if key == "url": servers[name] = value print "Found server: " + servers[name] if True: print "Here" DBusGMainLoop( set_as_default=True ) main_loop = gobject.MainLoop() bus = dbus.SystemBus() ## TODO: Hook up service added / removed global server server = dbus.Interface( bus.get_object( avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER ), avahi.DBUS_INTERFACE_SERVER ) ## Find services from any interface and protocol interface = avahi.IF_UNSPEC protocol = avahi.PROTO_UNSPEC ## Use local domain. domain = "local" ## Call method to create new browser, and get back an object ## path for it. obj_path = server.ServiceBrowserNew(interface, protocol, serviceType, domain, dbus.UInt32(0)) ## Create browser interface for the new object browser = dbus.Interface(bus.get_object(avahi.DBUS_NAME, obj_path), avahi.DBUS_INTERFACE_SERVICE_BROWSER) ## Hook up signal for new found services browser.connect_to_signal('ItemNew', service_add) try: context = main_loop.get_context() ## TODO: loop for short time period while (context.pending()): print "tick" time.sleep(0.5) # Handle commands here context.iteration(True) ## TODO: Turn off avahi ## Offer choices to user index = 0; options = []; for (key, value) in servers.iteritems(): index = index + 1; print(string.join(["Found (", str(index), ") ", key, " -> ", value])) options.append(key) while True: try: print "Pick Server: ", opt = sys.stdin.readline(); opt = int(opt) - 1; break; except Exception as e: print e ## get selected server option choice = options[opt] server = servers[choice]; return server ## Fall back to original code with new server choice except KeyboardInterrupt: pass
def __init__(self, name, service_type='_ros-master._tcp', host=socket.gethostname(), port=11311, domain='local', txt_array=[]): ''' Initialization method of the Zeroconf class. :param name: the name of the local ROS master :type name: str :param service_type: the avahi service type :type service_type: str :param host: the host of the local ROS master :type host: str :param port: the port of the local ROS master :type port: int :param domain: the domain name :type domain: str :param txt_array: (optional) additional information :type txt_array: list of strings ''' self.masterInfo = MasterInfo(name, service_type, domain, host, port, txt_array) # FIXME Review thread locking as needed. # init thread threading.Thread.__init__(self) self._lock = threading.RLock() # Gobjects are an event based model of evil, do not trust them, DBusGMainLoop(set_as_default=True) # Magic? Yes, don't start threads without it. # Why? I'm sure thats documented somewhere. gobject.threads_init() dbus.mainloop.glib.threads_init() self.__main_loop = gobject.MainLoop() self.__bus = dbus.SystemBus() # Initialize iterface to DBUS Server self.__server = dbus.Interface( self.__bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) # The DBUS entry group self.__group = None # Monitor server state changes self.__server.connect_to_signal("StateChanged", self.__avahi_callback_state_changed) # the browser to register the updates and new services self.__browser = dbus.Interface( self.__bus.get_object( avahi.DBUS_NAME, self.__server.ServiceBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, self.masterInfo.stype, self.masterInfo.domain, dbus.UInt32(0))), avahi.DBUS_INTERFACE_SERVICE_BROWSER) self.__browser.connect_to_signal( "ItemNew", self.__avahi_callback_service_browser_new) self.__browser.connect_to_signal( "ItemRemove", self.__avahi_callback_service_browser_remove)
def main_loop(self): return gobject.MainLoop()
def main(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) GstyleFulgens() mainloop = gobject.MainLoop() mainloop.run()
def pair_legacy_device(self, address, pin, trusted, timeout=60): """Pairs a device with a given pin code. Registers a agent who handles pin code request and pairs a device with known pin code. Note that the adapter does not automatically connnect to the device when pairing is done. The connect_device() method has to be invoked explicitly to connect to the device. This provides finer control for testing purpose. @param address: Address of the device to pair. @param pin: The pin code of the device to pair. @param trusted: indicating whether to set the device trusted. @param timeout: The timeout in seconds for pairing. @returns: True on success. False otherwise. """ device = self._find_device(address) if not device: logging.error('Device not found') return False if self._is_paired(device): logging.info('Device is already paired') return True device_path = device.object_path logging.info('Device %s is found.' % device.object_path) self._setup_pairing_agent(pin) mainloop = gobject.MainLoop() def pair_reply(): """Handler when pairing succeeded.""" logging.info('Device paired: %s', device_path) if trusted: self._set_trusted_by_path(device_path, trusted=True) logging.info('Device trusted: %s', device_path) mainloop.quit() def pair_error(error): """Handler when pairing failed. @param error: one of errors defined in org.bluez.Error representing the error in pairing. """ try: error_name = error.get_dbus_name() if error_name == 'org.freedesktop.DBus.Error.NoReply': logging.error('Timed out after %d ms. Cancelling pairing.', timeout) device.CancelPairing() else: logging.error('Pairing device failed: %s', error) finally: mainloop.quit() device.Pair(reply_handler=pair_reply, error_handler=pair_error, timeout=timeout * 1000) mainloop.run() return self._is_paired(device)
def evaluate(self, evaluee): self.frame_rate_counter = 0 self.step_time = time.time() global ctrl_client if ctrl_client and not self.ctrl_thread_started: thread.start_new_thread(check_stop, (self, )) self.ctrl_thread_started = True self.evaluations_taken = 0 self.energy = INITIAL_ENERGY self.fitness = 0 self.presence = self.prev_presence = (None, None) gobject.threads_init() dbus.mainloop.glib.threads_init() self.loop = gobject.MainLoop() def update_energy(task, energy): task.energy += energy def main_lambda(task): if task.energy <= 0 or task.evaluations_taken >= MAX_STEPS: task.motorLock.acquire() stopThymio(thymioController) task.motorLock.release() task.loop.quit() if task.energy <= 0: print 'Energy exhausted' else: print 'Time exhausted' return False if not self.goalReached: callback = lambda (psvalues): task.cameraCallback(evaluee, lambda (energy): update_energy(task, energy), psvalues) else: callback = self.goal_reach_camera_callback self.camera.update_callback(callback) print '===== Goal reached!' self.goalReachedCounter += 1 self.motorLock.acquire() stopThymio(self.thymioController) self.motorLock.release() self.camera.update_callback(self.goal_reach_camera_callback) self.conditionGoalReached.acquire() self.puckRemoved = False while not self.puckRemoved: self.thymioController.SendEventName('PlayFreq', [700, 0], reply_handler=dbusReply, error_handler=dbusError) time.sleep(.3) self.thymioController.SendEventName('PlayFreq', [0, -1], reply_handler=dbusReply, error_handler=dbusError) self.conditionGoalReached.wait(0.7) self.conditionGoalReached.release() time.sleep(15) print "finished puck wait loop" self.goalReached = False self.prev_presence = list(self.prev_presence) if len(self.prev_presence) >= 3: self.prev_presence[0] = self.prev_presence[2] = self.camera.MAX_DISTANCE time.sleep(2) if not self.camera.isAlive(): print "starting camera" #Call the camera asynchroniously. Call the callback when the presence values are ready. self.camera.start_camera(callback, task.cameraErrorCallback) print "camera started" else: self.camera.update_callback(callback) self.cameraWait() return True gobject.timeout_add(int(self.timeStep * 1000), lambda: main_lambda(self)) print 'Starting loop...' self.loop.run() fitness = self.getFitness() print 'Fitness at end: %d' % fitness if self.camera.isAlive(): # self.camera.stop() self.camera.pause() # self.camera.join() self.motorLock.acquire() stopThymio(self.thymioController) self.motorLock.release() time.sleep(1) self.individuals_evaluated += 1 return {'fitness': fitness}
def setUp(self): self.__ml = gobject.MainLoop() self.__pi = PlayerInfo("xxx", 0, 0, None, ["1", "2"]) self.__config = Config("unittest")
def __init__(self): _log.info('Initializing VideoTranscoder...') self.progress_percentage = None self.loop = gobject.MainLoop()
def main(): parser = argparse.ArgumentParser( description='Publishes values from the D-Bus to an MQTT broker') parser.add_argument('-d', '--debug', help='set logging level to debug', action='store_true') parser.add_argument('-q', '--mqtt-server', nargs='?', default=None, help='name of the mqtt server') parser.add_argument('-u', '--mqtt-user', default=None, help='mqtt user name') parser.add_argument('-P', '--mqtt-password', default=None, help='mqtt password') parser.add_argument( '-c', '--mqtt-certificate', default=None, help='path to CA certificate used for SSL communication') parser.add_argument('-b', '--dbus', default=None, help='dbus address') parser.add_argument('-k', '--keep-alive', default=60, help='keep alive interval in seconds', type=int) parser.add_argument( '-i', '--init-broker', action='store_true', help='Tries to setup communication with VRM MQTT broker') args = parser.parse_args() print("-------- dbus_mqtt, v{} is starting up --------".format( SoftwareVersion)) logger = setup_logging(args.debug) # This allows us to use gobject code in new threads gobject.threads_init() mainloop = gobject.MainLoop() # Have a mainloop, so we can send/receive asynchronous calls to and from dbus DBusGMainLoop(set_as_default=True) keep_alive_interval = args.keep_alive if args.keep_alive > 0 else None handler = DbusMqtt(mqtt_server=args.mqtt_server, ca_cert=args.mqtt_certificate, user=args.mqtt_user, passwd=args.mqtt_password, dbus_address=args.dbus, keep_alive_interval=keep_alive_interval, init_broker=args.init_broker) # Handle SIGUSR1 and dump a stack trace signal.signal(signal.SIGUSR1, dumpstacks) # Start and run the mainloop try: mainloop.run() except KeyboardInterrupt: pass
def run(self): """Start the BluePlayer by running the gobject Mainloop()""" gobject.threads_init() self.mainloop = gobject.MainLoop() self.mainloop.run()
def main(): from xpra.platform import init, clean init("Sound-Play") try: import os.path if len(sys.argv) not in (2, 3): print("usage: %s filename [codec]" % sys.argv[0]) return 1 filename = sys.argv[1] if os.path.exists(filename): print("file %s already exists" % filename) return 2 codec = None if len(sys.argv) == 3: codec = sys.argv[2] if codec not in CODECS: print("invalid codec: %s, codecs supported: %s" % (codec, CODECS)) return 2 else: parts = filename.split(".") if len(parts) > 1: extension = parts[-1] if extension.lower() in CODECS: codec = extension.lower() print("guessed codec %s from file extension %s" % (codec, extension)) if codec is None: codec = MP3 print("using default codec: %s" % codec) log.enable_debug() from threading import Lock f = open(filename, "wb") from xpra.sound.pulseaudio_util import get_pa_device_options monitor_devices = get_pa_device_options(True, False) log.info("found pulseaudio monitor devices: %s", monitor_devices) if len(monitor_devices) == 0: log.warn( "could not detect any pulseaudio monitor devices - will use a test source" ) ss = SoundSource("audiotestsrc", src_options={ "wave": 2, "freq": 100, "volume": 0.4 }, codec=codec) else: monitor_device = monitor_devices.items()[0][0] log.info("using pulseaudio source device: %s", monitor_device) ss = SoundSource("pulsesrc", {"device": monitor_device}, codec) lock = Lock() def new_buffer(ss, data, metadata): log.info("new buffer: %s bytes, metadata=%s" % (len(data), metadata)) try: lock.acquire() if f: f.write(data) finally: lock.release() ss.connect("new-buffer", new_buffer) ss.start() gobject_mainloop = gobject.MainLoop() gobject.threads_init() import signal def deadly_signal(*args): gobject.idle_add(gobject_mainloop.quit) signal.signal(signal.SIGINT, deadly_signal) signal.signal(signal.SIGTERM, deadly_signal) gobject_mainloop.run() f.flush() log.info("wrote %s bytes to %s", f.tell(), filename) try: lock.acquire() f.close() f = None finally: lock.release() return 0 finally: clean()
os.chdir( os.path.dirname(os.path.realpath(__file__)) ) SCREEN_SIZE = (Width,Height) screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) pygame.event.set_allowed(None) pygame.event.set_allowed([pygame.KEYDOWN,pygame.KEYUP,GMEVT,RUNEVT,RUNSYS]) pygame.key.set_repeat(DT+DT*6+DT/2, DT+DT*3+DT/2) MyIconPool.Init() setup_dbus() gobject.threads_init() gobject_main_loop = gobject.MainLoop() # if pygame.display.get_active() == True: # print("I am actived") if pygame.image.get_extended() == False: print("This pygame does not support PNG") exit() big_loop()
def Exit(self): mainloop.quit() @dbus.service.signal("com.example.SampleInterface", signature='') def exampleSignal(self): pass @dbus.service.signal("com.example.SampleInterface", signature='') def exampleSignal2(self): pass @dbus.service.signal("com.example.SampleInterface", signature='') def exampleSignal3(self): pass @dbus.service.signal("com.example.SampleInterface", signature='') def exampleSignal4(self): pass if __name__ == '__main__': dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) session_bus = dbus.SessionBus() name = dbus.service.BusName("com.example.SampleService", session_bus) object = SomeObject(session_bus, '/PythonServerObject') mainloop = gobject.MainLoop() print "DBUSTL test service is running." mainloop.run()
def run(self): loop = gobject.MainLoop() loop.run()