def main(args=None): #integrate the GLib Mainloop with the asyncio event loop # XXX gbulb is deprecated for windows, # XXX asyncio_glib has issues with HUP and INT signals, # XXX ROS integration would probably be a lot smoother if this lib leaned on regular futures and left the GLib mainloop to mind itself asyncio.set_event_loop_policy(asyncio_glib.GLibEventLoopPolicy()) #gbulb.install() #init ROS, GObject mainloop, and Gstreamer rclpy.init() GObject.threads_init() Gst.init(None) loop = asyncio.get_event_loop() # create an empty pipeline and ros node pipe_node = Pipeline('pipeline_node') # go to the parameter server and create some stuff to put into the pipeline # your factory methods here, pull requests are encouraged. build_simple_bins_from_params(pipe_node) build_webrtc_bins(pipe_node, loop) #instruct gstreamer to begin preroll and playback pipe_node.start_pipeline() # loop over the diagnostic tasks of the pipeline and everything in it. loop.run_until_complete(pipe_node.async_task()) # diagnostics
def main(args): parser = argparse.ArgumentParser(description='ShuttleXPress key remapper') parser.add_argument('--device-name', metavar='D', default=DEFAULT_DEVICE_NAME, help='Device name shown by evtest(1)') parser.add_argument('-d', '--debug', action='store_true', help='Enable debug output') parser.add_argument('-q', '--quiet', action='store_true', help='Quet mode') parser.add_argument('-s', '--jog-multiplier', type=float, default=1, help='Multipler for cursor speed for jog') args = parser.parse_args(args=args) global debug, quiet debug = args.debug quiet = args.quiet # Open /dev/uinput. ui = UInput(name='ShuttleXPress-remapper-uinput') asyncio.set_event_loop_policy(asyncio_glib.GLibEventLoopPolicy()) run_remap(ui, args.device_name, args.jog_multiplier)
def run(self): try: AssUtil.prepareTransientDir(self.param.runDir, os.getuid(), os.getgid(), 0o755) AssUtil.prepareTransientDir(self.param.tmpDir, os.getuid(), os.getgid(), 0o755) logging.getLogger().addHandler(logging.StreamHandler(sys.stderr)) logging.getLogger().setLevel(AssUtil.getLoggingLevel(self.param.logLevel)) logging.info("Program begins.") # load configuration self._load_config() # write pid file AssUtil.writePidFile(self.param.pidFile) # create main loop DBusGMainLoop(set_as_default=True) asyncio.set_event_loop_policy(asyncio_glib.GLibEventLoopPolicy()) self.param.mainloop = asyncio.get_event_loop() # start DBUS API server # if os.getuid() == 0: # self.param.dbusMainObject = DbusObjectSystem(self.param) # else: # self.param.dbusMainObject = DbusObjectSession(self.param) # business object self.param.reflexManager = AssReflexManager(self.param) # start main loop logging.info("Mainloop begins.") GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, self._sigHandlerINT, None) GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, self._sigHandlerTERM, None) self.param.mainloop.run_forever() logging.info("Mainloop exits.") finally: if self.param.reflexManager is not None: self.param.reflexManager.dispose() self.param.reflexManager = None logging.shutdown() shutil.rmtree(self.param.runDir) shutil.rmtree(self.param.tmpDir)
def setup_mainloop(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) asyncio.set_event_loop_policy(asyncio_glib.GLibEventLoopPolicy()) return asyncio.get_event_loop()
# Copyright (c) 2020 ruundii. All rights reserved. import asyncio import sys from signal import SIGINT import asyncio_glib from dasbus.connection import SystemMessageBus from adapter import BluetoothAdapter from bluetooth_devices import * from hid_devices import * from web import Web if __name__ == "__main__": asyncio.set_event_loop_policy(asyncio_glib.GLibEventLoopPolicy()) loop = asyncio.get_event_loop() loop.add_signal_handler(SIGINT, sys.exit) bus = SystemMessageBus() bluetooth_devices = BluetoothDeviceRegistry(bus, loop) hid_devices = HIDDeviceRegistry(loop) hid_devices.set_bluetooth_devices(bluetooth_devices) bluetooth_devices.set_hid_devices(hid_devices) adapter = BluetoothAdapter(bus, loop, bluetooth_devices, hid_devices) web = Web(loop, adapter, bluetooth_devices, hid_devices) loop.run_forever() #print(proxy)
def main(): if sys.platform == "linux": clients = { "introspective": None, # assign later because of dependencies "playerctl": ForkingPlayerctlClient, "unixsocket": UnixSocketClient } default_client = "introspective" elif sys.platform == "darwin": clients = {"unixsocket": UnixSocketClient} default_client = "unixsocket" elif sys.platform == "windows": print("windows not yet supported") loop = asyncio.ProactorEventLoop() # for subprocesses on windows asyncio.set_event_loop(loop) return 1 else: print(f"Platform '{sys.platform}' not supported") return 1 def get_commit_id(): # called on every launch, but that's ok for now return subprocess.run(["git", "describe", "--always"], stdout=subprocess.PIPE, timeout=0.5).stdout.decode('utf-8').strip() # argparse setup # noinspection PyTypeChecker parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='datenight client') # optional arguments parser.add_argument('-v', action='count', help="verbosity increases with each 'v' " "| critical/error/warning/info/debug", default=0) parser.add_argument('-s', '--server', type=str, default="http://localhost", help="hostname to connect to") parser.add_argument('-p', '--port', default=None, type=int, help="port to connect to (if unspecified, defaults to " "80 for http:// and 443 for https://)") parser.add_argument('-c', '--client', default=default_client, type=str, choices=clients.keys(), help="Choice of client to use") parser.add_argument('-a', '--alias', type=str, default=None, help="Name by which this publisher will be known as") parser.add_argument('-o', '--offset', default=0, type=int, help="Offset (+/- <seconds> if any), to apply on the " "local file") parser.add_argument('-V', '--version', action='version', version="%(prog)s v{} ({})".format( '.'.join(map(str, version)), get_commit_id()), help="Show version and exit") args = parser.parse_args() if args.client not in clients: # fallback if the default_client is invalid print(f"Must choose a client (-c) from {clients.keys()}") return 1 if args.client == "introspective": try: from client.vlc.introspective import IntrospectiveVLCClient except ValueError: print("You don't have playerctl installed " "(needed for the playerctl client)\n" "Install it or use an alternative client with the -c flag") return 1 else: clients['introspective'] = IntrospectiveVLCClient try: # noinspection PyUnresolvedReferences import gbulb except ImportError: print( "You don't have the gbulb module installed. Falling back to " "asyncio_glib which has an upstream issue preventing it from " "reporting status immediately (delaying async events)") try: import asyncio_glib except ImportError: print( "You don't have the asyncio_glib module installed " "(needed for the introspective client)\n" "Install it or use an alternative client with the -c flag") return 1 else: asyncio.set_event_loop_policy( asyncio_glib.GLibEventLoopPolicy()) else: gbulb.install() # logger setup level = max(10, 50 - (10 * args.v)) print(f'Logging level is: {logging.getLevelName(level)}') logger = logging.getLogger(__name__) logger.setLevel(level) formatter = logging.Formatter('%(asctime)s: %(levelname)s:\t%(message)s') sh = logging.StreamHandler() sh.setFormatter(formatter) logger.addHandler(sh) logger = logging.getLogger('client') logger.setLevel(level) logger.addHandler(sh) if args.port is None: if args.server.startswith("https"): args.port = 443 elif args.server.startswith("http"): args.port = 80 return asyncio.run(start_loop(args, clients))
def run(self): self._loadMainCfg() try: # create directories PsUtil.preparePersistDir(PsConst.varDir, PsConst.uid, PsConst.gid, 0o755) PsUtil.preparePersistDir(PsConst.logDir, PsConst.uid, PsConst.gid, 0o755) PsUtil.prepareTransientDir(PsConst.runDir, PsConst.uid, PsConst.gid, 0o755) PsUtil.prepareTransientDir(PsConst.tmpDir, PsConst.uid, PsConst.gid, 0o755) with DropPriviledge(PsConst.uid, PsConst.gid, caps=[prctl.CAP_NET_BIND_SERVICE]): try: # initialize logging sys.stdout = StdoutRedirector( os.path.join(PsConst.logDir, "pservers.out")) sys.stderr = sys.stdout logging.getLogger().addHandler( logging.StreamHandler(sys.stderr)) logging.getLogger().setLevel(logging.INFO) logging.info("Program begins.") # create mainloop asyncio.set_event_loop_policy( asyncio_glib.GLibEventLoopPolicy()) self.param.mainloop = asyncio.get_event_loop() # write pid file PsUtil.writePidFile(PsConst.pidFile) # plugin manager self.param.pluginManager = PsPluginManager(self.param) # load servers self.serverManager = PsServerManager(self.param) self.serverManager.loadServers() if len(self.param.serverDict) == 0: raise Exception("no server loaded") logging.info( "Servers loaded: %s" % (",".join(sorted(self.param.serverDict.keys())))) # main server self.param.mainServer = PsMainHttpServer(self.param) for serverId, serverObj in self.param.serverDict.items(): if serverId.startswith("proxy-"): raise Exception( "invalid server %s" % (serverId) ) # "proxy-" prefix is reserved for external servers cfg = serverObj.startAndGetMainHttpServerConfig() self.param.mainServer.addConfig(serverId, cfg) self.param.mainServer.start() logging.info("Main server started, listening on port %d." % (PsConst.httpPort)) # register domain names self.param.avahiObj = AvahiDomainNameRegister() for serverObj in self.param.serverDict.values(): self.param.avahiObj.add_domain_name( serverObj.domainName) self.param.avahiObj.start() for serverObj in self.param.serverDict.values(): logging.info( "URL \"http://%s\" is available for access." % (serverObj.domainName)) # start api server self.param.apiServer = PsApiServer(self.param) logging.info("API server started, socket file %s." % (PsConst.apiServerFile)) # start main loop logging.info("Mainloop begins.") self.param.mainloop.add_signal_handler( signal.SIGINT, self._sigHandlerINT) self.param.mainloop.add_signal_handler( signal.SIGTERM, self._sigHandlerTERM) self.param.mainloop.run_forever() logging.info("Mainloop exits.") finally: if self.param.apiServer is not None: self.param.apiServer.dispose() if self.param.avahiObj is not None: self.param.avahiObj.stop() if self.param.mainServer is not None: self.param.mainServer.stop() logging.shutdown() finally: shutil.rmtree(PsConst.tmpDir) shutil.rmtree(PsConst.runDir)