def main(reactor): PATH = '/path/to/FDObject' BUSN = 'org.example' try: bus = yield client.connect(reactor) print('connected to dbus') object = yield bus.getRemoteObject(BUSN, PATH) print('obtained remote object') except Exception as e: print('failed obtaining remote object: %s' % (e, )) defer.returnValue(None) # Open this source file. Ask remote to read it and return byte count. with open(__file__, 'rb') as f: yield call_remote_verbose(object, 'lenFD', f.fileno()) # Open this source file. Ask remote to read 10 bytes from it. with open(__file__, 'rb') as f: yield call_remote_verbose(object, 'readBytesFD', f.fileno(), 10) # Like before, now exercise passing two open UNIX FDs. # (will not be available under Twisted < 17.1.0) with open(__file__, 'rb') as f1, open(__file__, 'rb') as f2: fd1 = f1.fileno() fd2 = f2.fileno() try: yield call_remote_verbose(object, 'readBytesTwoFDs', fd1, fd2, 5) except Exception as e: print('remote call failed: %s' % (e, )) bus.disconnect() print('disconnected')
def _dbus_connect(self): assert self._conn_lock try: conn = yield txdbus_client.connect(reactor, self.dbus_addr) self._conn = conn yield self._dbus_exports() except: self.log.fatal('Exiting due to unrecoverable dbus failure') utils.stop() raise self.log.debug('Connected to DBus instance (address: %r)', self.dbus_addr) # Make sure NM is running and reachable try: delay, deadline = self.nm_wait_retry_delay, time.time() + self.nm_wait_limit while time.time() < deadline: nm_alive = yield self._dbus_test() if nm_alive: break yield utils.timeout(delay) delay *= self.nm_wait_retry_factor if not nm_alive: raise NMConnectionError('Failed to connect to NetworkManager dbus interface') except NMConnectionError as err: self.log.fatal('Exiting due to unrecoverable NM connection failure') utils.stop() raise reactor.callLater(0, self._dbus_disconnect_handler) self._conn_lock.release() self._conn_lock = None
def main(reactor): PATH = '/path/to/FDObject' BUSN = 'org.example' try: bus = yield client.connect(reactor) print('connected to dbus') object = yield bus.getRemoteObject(BUSN, PATH) print('obtained remote object') except Exception as e: print('failed obtaining remote object: %s' % (e,)) defer.returnValue(None) # Open this source file. Ask remote to read it and return byte count. with open(__file__, 'rb') as f: yield call_remote_verbose(object, 'lenFD', f.fileno()) # Open this source file. Ask remote to read 10 bytes from it. with open(__file__, 'rb') as f: yield call_remote_verbose(object, 'readBytesFD', f.fileno(), 10) # Like before, now exercise passing two open UNIX FDs. # (will not be available under Twisted < 17.1.0) with open(__file__, 'rb') as f1, open(__file__, 'rb') as f2: fd1 = f1.fileno() fd2 = f2.fileno() try: yield call_remote_verbose(object, 'readBytesTwoFDs', fd1, fd2, 5) except Exception as e: print('remote call failed: %s' % (e,)) bus.disconnect() print('disconnected')
def connect_to_dbus(self, bus_address='session', disconnect_callable=None): """ Connects to DBus and sets up DBus object name tracking. """ if not self._dbus_proto: yield self._spawn_dbus_daemon() _log.info('connecting to dbus') self._dbus_conn = yield txdbus_client.connect(self._reactor, bus_address) _log.info('connected to dbus') # Track DBus disconnections. self._dbus_conn.notifyOnDisconnect(self._dbus_disconnected) self._disconnect_callable = disconnect_callable _log.debug('tracking disconnections') # Use this to track DBus attachments. _log.debug('getting org.freedesktop.DBus') dbus_obj = yield self.dbus_conn.getRemoteObject( 'org.freedesktop.DBus', '/org/freedesktop/DBus' ) _log.debug('subscribing to NameOwnerChanged signal') yield dbus_obj.notifyOnSignal( 'NameOwnerChanged', self._dbus_signal_name_owner_changed ) _log.debug('subscribed to NameOwnerChanged signal')
def on_running(): """ called when the twisted reactor is running """ log.msg('reactor_loop Starting') try: conn = client.connect(reactor) tagnet_do = TagNetComponent(conn) conn.addCallback(tagnet_do.start) conn.addErrback(tagnet_do.on_error) conn = client.connect(reactor) si446x_do = Si446xComponent(conn, tagnet_do.report_changes) conn.addCallback(si446x_do.start) conn.addErrback(si446x_do.on_error) except error.DBusException, e: log.msg('reactor_loop Setup Error: {}'.format(e)) reactor.stop()
def callDeferredMethod(method, *args): try: conn = yield client.connect(reactor, busAddress="system") robj = yield conn.getRemoteObject(service_name, service_path) result = yield robj.callRemote(method, *args) defer.returnValue(result) except error.DBusException as e: out.err("D-Bus error: {}".format(e)) pass
def onJoin(self, details): conn = yield client.connect(reactor, "session") print("Dbus connection created") self._notifier = yield conn.getRemoteObject("org.freedesktop.Notifications", "/org/freedesktop/Notifications") print("Dbus notification object created") yield self.subscribe(self) print("Dbus notifier subscribed")
def on_running(): global robj try: cli = yield client.connect(reactor) robj = yield cli.getRemoteObject(SI446X_BUS_NAME, SI446X_OBJECT_PATH, si446x_dbus_interface) log.msg('got remote object') robj.notifyOnSignal('receive', on_receive) except error.DBusException, e: log.msg('send Failed. org.example is not available')
def run(): try: conn = yield client.connect(reactor) conn.exportObject(Rfm69DBusService(PROTOCOL_PATH)) yield conn.requestBusName(BUS_NAME) logger.debug("Object exported on bus name {} with path {}" \ .format(BUS_NAME, PROTOCOL_PATH)) except Exception: logger.exception("Failed to export object: ") reactor.stop()
def main(): root.putChild(b'', root) logging.info('Adding dbus signals') system = yield client.connect(reactor, 'system') controlApi = yield system.getRemoteObject('ca.krontech.chronos.control', '/ca/krontech/chronos/control') #videoApi = yield system.getRemoteObject('ca.krontech.chronos.video', '/ca/krontech/chronos/video') test = Test(controlApi) test.run()
def onJoin(self, details): conn = yield client.connect(reactor, 'session') print("Dbus connection created") self._notifier = yield conn.getRemoteObject( 'org.freedesktop.Notifications', '/org/freedesktop/Notifications') print("Dbus notification object created") yield self.subscribe(self) print("Dbus notifier subscribed")
def onSleep(suspended): try: cli = yield client.connect(reactor, 'session') robj = yield cli.getRemoteObject( 'org.freedesktop.systemd1', '/org/freedesktop/systemd1', ) yield robj.callRemote('StartUnit', 'sleep.target', 'replace') except Exception: logger.exception('Error starting lock.target.')
def main(): try: cli = yield client.connect(reactor) yield cli.callRemote('/AnyValidObjPath', 'Ping', interface='org.freedesktop.DBus.Peer', destination='org.example') print 'Ping Succeeded. org.example is available' except error.DBusException, e: print 'Ping Failed. org.example is not available'
def activate_notification( bus, iface, path, signal, cb): try: cli = yield client.connect(reactor, bus) robj = yield cli.getRemoteObject( iface.name, path, iface) robj.notifyOnSignal(signal, cb) except error.DBusException, e: print 'DBus Error:', e
def onNotify(self, topic, event): print topic, event con = yield client.connect(reactor, 'session') notifier = yield con.getRemoteObject('org.freedesktop.Notifications', '/org/freedesktop/Notifications') nid = yield notifier.callRemote('Notify', str(event['app']), 0, '', str(event['title']), str(event['body']), [], dict(), 1) yield delay(event['duration']) print "autoclosing notification" yield notifier.callRemote('CloseNotification', nid)
def main(): try: cli = yield client.connect(reactor, 'system') lock_obj = yield cli.getRemoteObject( 'org.freedesktop.login1', '/org/freedesktop/login1/session/c1', ) sleep_obj = yield cli.getRemoteObject( 'org.freedesktop.login1', '/org/freedesktop/login1', ) lock_obj.notifyOnSignal('Lock', onLock) sleep_obj.notifyOnSignal('PrepareForSleep', onSleep) except Exception: logger.exception('Error listening for lock events.')
def main(reactor): PATH = '/path/to/FDObject' BUSN = 'org.example' try: bus = yield client.connect(reactor) except Exception as e: print('failed connecting to dbus: %s' % (e,)) reactor.stop() defer.returnValue(None) print('connected to dbus') object = FDObject(PATH) bus.exportObject(object) yield bus.requestBusName(BUSN) print('exported %r on %r at %r' % (object.__class__.__name__, BUSN, PATH))
def update_state( bus, iface, path, property, cb): try: cli = yield client.connect(reactor, bus) robj = yield cli.getRemoteObject( iface, path) r = yield robj.callRemote('Get', '', property) cb(r) except error.DBusException, e: print 'DBus Error:', e
def listen(): service = ConfigService() # Things get messy if pdconfd is restarted with running chutes. Then it # will try to reconfigure the system. One easy solution is to unload the # configuration before exiting. reactor.addSystemEventTrigger('before', 'shutdown', ConfigService.configManager.unload) # Now load all of the configuration for the first time. ConfigService.configManager.loadConfig() try: conn = yield client.connect(reactor, busAddress="system") conn.exportObject(service) yield conn.requestBusName(service_name) except error.DBusException as e: print("Failed to export DBus object: {}".format(e))
def call_method( bus, iface, path, method, cb, *args): try: cli = yield client.connect(reactor, bus) robj = yield cli.getRemoteObject( iface.name, path, iface) r = yield robj.callRemote(method, *args) cb(r) except error.DBusException, e: print 'DBus Error:', e
def notify(systray, title, message, duration=5000): logging.debug("Sending notification: title=%s message=%s", title, message) if sys.platform.startswith('linux'): from txdbus import client # pylint: disable=import-error name = settings['application']['name'] icon = resource(settings['application']['tray_icon']) try: conn = yield client.connect(reactor) robj = yield conn.getRemoteObject( 'org.freedesktop.Notifications', '/org/freedesktop/Notifications') reply = yield robj.callRemote('Notify', name, 0, icon, title, message, [], dict(), duration) logging.debug("Got reply: %s", reply) yield conn.disconnect() except Exception: # pylint: disable=broad-except systray.showMessage(title, message, msecs=duration) else: systray.showMessage(title, message, msecs=duration)
def run(): try: conn = yield client.connect(reactor) conn.exportObject(Rfm69DBusService(PROTOCOL_PATH)) yield conn.requestBusName(BUS_NAME) logger.debug("Object exported on bus name {} with path {}" \ .format(BUS_NAME, PROTOCOL_PATH)) # Register in ProtocolManager try: manager = yield conn.getRemoteObject( "org.eclipse.agail.ProtocolManager", "/org/eclipse/agail/ProtocolManager") yield manager.callRemote("Add", "RFM69") logger.debug("Registered protocol with ProtocolManager") except Exception: logger.exception("Failed to register with ProtocolManager") except Exception: logger.exception("Failed to export object: ") reactor.stop()
def reactor_loop(): """ SI446x Driver reactor loop """ fsm = None radio = None dbus = None def onConnected(conn): fsm, radio, dbus = setup_driver() conn.exportObject(dbus) dn = conn.requestBusName(BUS_NAME) def onReady(_): start_driver(fsm, radio, dbus) dn.addCallback(onReady) return dn def onErr(err): print('Failed: ', err.getErrorMessage()) reactor.stop() def SIGINT_CustomEventHandler(num, frame): k = {1: "SIGHUP", 2: "SIGINT"} log.msg("Recieved signal - " + k[num]) if frame is not None: log.msg("SIGINT at %s:%s" % (frame.f_code.co_name, frame.f_lineno)) log.msg("In SIGINT_CustomEventHandler") if num == 2: log.msg("shutting down ....") if (radio): radio.shutdown() reactor.stop() signal.signal(signal.SIGINT, SIGINT_CustomEventHandler) signal.signal(signal.SIGHUP, SIGINT_CustomEventHandler) dc = client.connect(reactor) dc.addCallback(onConnected) dc.addErrback(onErr) reactor.run()
def setup(args): """ :type args: :class:`argparse.Namespace` """ con = yield client.connect(reactor, "system") registry = NotifierRegistry(get_enabled_notifiers(args.notifier)) try: if args.all_units: # Get the names of all units units = yield get_all_unit_paths(con) for unit in units: yield Unit.from_child_object_path(unit, registry).connect(con) systemd_ready() systemd_status("Monitoring {} units.".format(len(units))) else: for unit in args.unit: Unit.from_unit_filename(unit, registry).connect(con) systemd_ready() systemd_status("Monitoring {}.".format(args.unit)) except error.DBusException: logging.exception( "The following exception occured during the initial setup:") reactor.stop()
def set_mode_example(): cli = yield client.connect(reactor, busAddress='system') root_obj = yield cli.getRemoteObject(dbus_name, root_iface_obj_path) print "Root Object: %s" % root_obj wlan0_obj_path = yield root_obj.callRemote('GetInterface', 'wlan1') print "WLAN0 Object Path: %s" % wlan0_obj_path wlan0_obj = yield cli.getRemoteObject(dbus_name, wlan0_obj_path, interface_iface) print "WLAN0 Object: %s" % wlan0_obj # wpa_supplicant will validate keys, but does not validate values. # There are a bunch of additional configuration options for 801.11ac. network_settings = { "disabled": 0, # Not disabled # "id_str": "ExtScriptID", "ssid": "funny-ssid", # SSID # "frequency": 2412, # When IBSS only, ignored in mode=0 # "proto": "WPA", # "bssid": "Somebss", "mode": 0, # 0 = managed(default), 1 = IBSS (Ad-hoc, p2p), 2: AP (access point) # "freq_list": None, # # "bgscan": "simple:30:-45:300", # "proto": "WPA", "key_mgmt": "WPA-PSK", # "ieee80211w": 0, "auth_alg": "OPEN", "pairwise": "CCMP", # "group": None, "psk": "funnypsk", # "eapol_flags": 3, # "macsec_policy": 0, # "mixed_cell": 0, # "proactive_key_caching": 0, # "wep_key0": None, # "wep_key1": None, # "wep_key2": None, # "wep_key3": None, # "wep_tx_keyidx": None, # "peerkey": 0, # "wpa_ptk_rekey": 100000, # "eap": "MD5 MSCHAPV2 OTP GTC TLS PEAP TTLS", # "identity": "Some one", # EAP identity # "anonymous_identity": "Anonymous one", # EAP anonymous # "password": "******", # "ca_cert": "file path to CA certificates", # "ca_path": "directory path for CA certificate files (PEM)", # "client_cert": "file path to client certificate file", # "private_key": "file path to private key", # "private_key_passwd": "password for private key", # "dh_file": "file path to DH/DSA params", # "subject_match": "x", # "altsubject_match": "alt", # "phase1": "peapver=1", # See wpa_supplicant.conf for phase1 TLS details # "phase2": "auth=MSCHAPV2", # See wpa_supplicant.conf for phase2 TLS details # "ca_cert2": "file path to phase2 CA certificates", # "ca_path2": "directory path for phase2 CA certificate files (PEM)", # "client_cert2": "file path to phase2 client certificate", # "private_key2": "file path to phase2 client private key", # "private_key2_passwd": "password for phase2 private key", # "dh_file2": "file path to phase2 DH/DSA params", # "subject_match2": "x", # "altsubject_match2": "alt2", # "fragment_size": "1398", # "ocsp": 0, # "ap_max_inactivity": 300, # Seconds # "disable_ht": "0", # High Throughput 802.11n enabled # "disable_ht40": 0, # High Throughput 802.11n enabled (40 MHz channel) # "disable_sgi": 0, # short guard interval enabled # "disable_ldpc": 0, # low density parity check enabled # "ht40_intolerant": 0, # HT-40 tolerated # "ht_mcs": "", # Use all available # "disable_max_amsdu": -1, # "ampdu_factor": 3, # "ampdu_density": -1, # "disable_vht": 0, # Very High Throughput 802.11ac enabled } network_obj = yield wlan0_obj.callRemote('AddNetwork', network_settings) print "Network Object Path: %s" % network_obj yield wlan0_obj.callRemote('SelectNetwork', network_obj) time.sleep(20) yield wlan0_obj.callRemote('RemoveNetwork', network_obj) reactor.stop()
def get_conn(): self._reactor.thread_name = threading.currentThread().getName() conn = yield client.connect(self._reactor, busAddress='system') defer.returnValue(conn)
def main(): subscribe = Subscribe() webPublisher = Publish(subscribe) root.putChild(b'subscribe', subscribe) root.putChild(b'publish', webPublisher) root.putChild(b'', root) site = server.Site(root) logging.info('Adding dbus signals') system = yield client.connect(reactor, 'system') controlApi = yield system.getRemoteObject('ca.krontech.chronos.control', '/ca/krontech/chronos/control') videoApi = yield system.getRemoteObject('ca.krontech.chronos.video', '/ca/krontech/chronos/video') ringApi = None dbusSignalPublisher = dbusPublisher(subscribe, controlApi, videoApi, ringApi) logging.info('Adding methods') control = resource.Resource() root.putChild(b'control', control) GetMethod(control, controlApi, 'get') Method(control, controlApi, 'set', arguments=True) Method(control, controlApi, 'startAutoWhiteBalance', arguments=True) Method(control, controlApi, 'revertAutoWhiteBalance', arguments=False) Method(control, controlApi, 'startAutoFocus', arguments=True) Method(control, controlApi, 'startCalibration', arguments=True) Method(control, controlApi, 'startRecording', arguments=False) Method(control, controlApi, 'stopRecording', arguments=False) Method(control, controlApi, 'flushRecording', arguments=False) Method(control, controlApi, 'startFilesave', arguments=False) Method(control, controlApi, 'softTrigger', arguments=False) Method(control, controlApi, 'revertToDefaults', arguments=False) Method(control, controlApi, 'softReset', arguments=False) Method(control, controlApi, 'getResolutionTimingLimits', arguments=True) video = resource.Resource() root.putChild(b'video', video) Method(video, videoApi, 'status', arguments=False) Method(video, videoApi, 'flush', arguments=False) Method(video, videoApi, 'playback', arguments=True) Method(video, videoApi, 'configure', arguments=True) Method(video, videoApi, 'livedisplay', arguments=True) Method(video, videoApi, 'recordfile', arguments=True) Method(video, videoApi, 'stop', arguments=False) Method(video, videoApi, 'overlay', arguments=True) root.putChild(b'screenCap.jpg', previewImage(videoApi)) root.putChild(b'liveImage.jpg', previewImage(videoApi)) root.putChild(b'playbackImage.jpg', playbackImage(videoApi)) root.putChild(b'waitForTouch', waitForTouch()) root.putChild(b'waitForTouchThenBlackcal', waitForTouchThenBlackcal(controlApi)) if aimCameraResource: root.putChild(b'aimCamera', aimCameraResource()) root.putChild(b'timingControl.html', File('timingControl.html')) root.putChild(b'forceReboot', forceReboot()) reactor.listenTCP(12000, site) yield asleep(0.1) logging.info("All Systems Go")