Beispiel #1
0
def main(args):
    bus = SessionBus()
    loop = GLib.MainLoop()

    def new_wallpaper():
        wg.NewWallpaper(args.type, args.subreddit, args.directory, args.output,
                        args.generate_only)

    if args.dbus:
        bus.publish('de.thm.mni.mhpp11.WallGen', WallGenDBUSService(loop))
        run(loop)
    else:
        try:
            wg = bus.get('de.thm.mni.mhpp11.WallGen')
        except GLib.Error:
            wg = WallGenDBUSService(None)
        if type(wg) != WallGenDBUSService:
            if args.monitor:
                dc = bus.get('org.gnome.Mutter.DisplayConfig')
                with wg.Closed.connect(loop.quit):
                    with dc.MonitorsChanged.connect(new_wallpaper):
                        run(loop)
            elif args.quit:
                wg.Close()
        if not args.monitor:
            new_wallpaper()
        elif type(wg) == WallGenDBUSService:
            raise Exception("Monitoring is not possible without DBus service!")
Beispiel #2
0
def main():
    win = NotificationsWindow()
    bus = SessionBus()
    bus.publish("org.freedesktop.Notifications", Notifications(win))
    loop = GLib.MainLoop()
    th = Thread(target=loop.run)
    th.start()
    win.mainloop()
Beispiel #3
0
def cli():
    loop = GLib.MainLoop()
    bus = SessionBus()
    bus.publish(INTERFACE_NAME, RofiDbus())
    try:
        loop.run()
    except KeyboardInterrupt:
        loop.quit()
Beispiel #4
0
def main():
    loop = GLib.MainLoop()
    bus = SessionBus()
    service = TestService()

    print("Publishing service")
    bus.publish("com.wdc.TestService1", service)
    loop.run()
Beispiel #5
0
def main():
    rospy.loginfo("Starting Raven[ops] ROS Bag Player")

    verbose = False
    bagfile = ""
    parser = argparse.ArgumentParser()
    parser.add_argument('-b',
                        '--bagfile',
                        required=True,
                        default="",
                        help="complete bagfile path")
    parser.add_argument('-v',
                        '--verbose',
                        default=False,
                        help="select verbose output",
                        action='store_true')
    parser.add_argument("args", nargs='+')
    args = parser.parse_args()
    if args.bagfile: bagfile = args.bagfile
    if args.verbose: verbose = True  # RVN::TODO: Not connected

    rospy.loginfo("Getting main Glib loop object")
    try:
        loop = GLib.MainLoop()
    except Exception as e:
        rospy.logerr("Unable to create GLib.MainLoop!")
        return ExitStatus.PUB_FAIL

    rospy.loginfo("Creating Publication Control Object")
    try:
        pub = PublicationControl(bagfile, loop)
    except Exception as e:
        rospy.logerr("{}".format(e))
        return ExitStatus.PUB_FAIL

    rospy.loginfo("starting d-bus service...")
    try:
        session_bus = SessionBus()
    except Exception as e:
        rospy.logerr("Unable to create the session dbus")
        return ExitStatus.PUB_FAIL

    rospy.loginfo("created the session d-bus object")

    try:
        session_bus.publish(service_name, pub)
    except Exception as e:
        rospy.logerr("Unable to set up session dbus: {}".format(e))
        return ExitStatus.PUB_FAIL

    rospy.loginfo("published to the '{}' dbus ".format(service_name))
    rospy.loginfo("running the main loop...")

    loop.run()
    rospy.loginfo("...finished d-bus service")

    return pub.exit_status
Beispiel #6
0
def run():
    bus = SessionBus()
    try:
        hidamari = HidamariService()
        bus.publish(DBUS_NAME, hidamari)
        hidamari.dbus_published_callback()
        loop.run()
    except RuntimeError:
        print("Error: Failed to create server")
Beispiel #7
0
def init():
    print('start convergence.dbus')
    print('use session.')
    session_bus = SessionBus()
    global sm
    sm = ServiceManager()
    print('published bus_name: ', SM__BUS_NAME)
    session_bus.publish(SM__BUS_NAME, (SM__OBJECT_PATH, sm))
    signal.signal(signal.SIGINT, receive_signal)
    sm.sm_start_signal()
Beispiel #8
0
def main():
    from gi.repository import GLib
    from pydbus import SessionBus

    config_home = os.environ.get("XDG_CONFIG_HOME", os.path.join(os.environ["HOME"], ".config"))
    config = read_config(config_home)

    log = PladderLog(config)
    bus = SessionBus()
    bus.publish("se.raek.PladderLog", log)
    loop = GLib.MainLoop()
    loop.run()
Beispiel #9
0
def main():
    from gi.repository import GLib
    from pydbus import SessionBus

    state_home = os.environ.get("XDG_CONFIG_HOME",
                                os.path.join(os.environ["HOME"], ".config"))
    state_dir = os.path.join(state_home, "pladder-bot")

    pladder_bot = PladderBot(state_dir)
    bus = SessionBus()
    bus.publish("se.raek.PladderBot", pladder_bot)
    loop = GLib.MainLoop()
    loop.run()
Beispiel #10
0
def main():
    from gi.repository import GLib
    from pydbus import SessionBus

    state_home = os.environ.get("XDG_CONFIG_HOME",
                                os.path.join(os.environ["HOME"], ".config"))
    state_dir = os.path.join(state_home, "pladder-bot")

    bus = SessionBus()
    with PladderBot(state_dir, bus) as bot:
        load_standard_plugins(bot)
        bus.publish("se.raek.PladderBot", bot)
        loop = GLib.MainLoop()
        loop.run()
Beispiel #11
0
class Mocker(object):
    def start(self):
        self._bus = SessionBus()
        self._mock = SignalCLIDBusMock()
        self._mockerservice = self._bus.publish(
            "org.signalbot.signalclidbusmock", self._mock)
        self._loop = GLib.MainLoop()
        self._thread = Thread(target=self._loop.run, daemon=True)
        self._thread.start()
        self.tosignalbot = []
        self._wait_until = 0

    def messageSignalbot(self, sender, group_id, text, attachmentfiles):
        self._mock.MessageReceived(int(time.time()), sender, group_id, text,
                                   attachmentfiles)
        self.tosignalbot.append(
            [int(time.time()), sender, group_id, text, attachmentfiles])

    def _wait_until_n_messages(self, n=1, timeout=1):
        return self._mock.wait_until_n_messages(n=n, timeout=timeout)

    def wait_for_n_messages(self, n=1, timeout=1):
        self._wait_until += n
        self._wait_until_n_messages(n=self._wait_until, timeout=timeout)

    @property
    def fromsignalbot(self):
        return self._mock._sentmessages

    def stop(self):
        self._loop.quit()
        self._thread.join()
        self._mockerservice.unpublish()
Beispiel #12
0
def start():
    args = parse_arguments()
    config = Config()
    if not config.is_supported_desktop():
        raise Exception('Desktop environment not supported.')

    bus = SessionBus()
    loop = GLib.MainLoop()

    if args.dbus:
        bus.publish('de.thm.mni.mhpp11.WallGen', WallGenDBUSService(loop))
        run(loop)
    else:
        try:
            wg = bus.get('de.thm.mni.mhpp11.WallGen')
        except GLib.Error:
            wg = WallGenDBUSService(None)
        if type(wg) != WallGenDBUSService:
            if args.monitor:

                dc = None
                if config.is_gnome():
                    dc = bus.get('org.gnome.Mutter.DisplayConfig')
                elif config.is_kde():
                    dc = bus.get('org.kde.KScreen', object_path='/backend')
                with wg.Closed.connect(loop.quit):
                    if config.is_gnome():
                        with dc.MonitorsChanged.connect(wg.NewWallpaper):
                            run(loop)
                    elif config.is_kde():

                        class KDENewWallpaper:
                            first_call = True

                            def call(self, _):
                                if (self.first_call):
                                    wg.NewWallpaper()
                                self.first_call = not self.first_call

                        with dc.configChanged.connect(KDENewWallpaper().call):
                            run(loop)
            elif args.quit:
                wg.Close()
        elif type(wg) == WallGenDBUSService and args.monitor:
            raise Exception("Monitoring is not possible without DBus service!")
        if not args.monitor and not args.quit:
            wg.NewWallpaper()
Beispiel #13
0
    def publish(self, bus=None):
        """Publish the media player to DBus."""
        if bus is None:
            bus = SessionBus()

        pub = bus.publish("org.mpris.MediaPlayer2.%s" % self.name,
                          ("/org/mpris/MediaPlayer2", self))
        return (bus, pub)
Beispiel #14
0
class DBusThread(Thread):
    def __init__(self, c, dbus_mm):
        super().__init__(name='DBus', daemon=True)
        self._c = c
        self._loop = GLib.MainLoop()
        self._bus = SessionBus()
        self._dbus_mm = dbus_mm

        self._dbus_mm.loop = self._loop
        self._dbus_mm.bus = self._bus

    def run(self):
        pub = {}
        # for t, module in self._mm.modules.items():
        #     try:
        #         pub[t] = self._bus.publish(module.name, (module))
        #     except (GLib.Error, TypeError) as e:
        #         logger.error(f'error publishing {t} because {e}')
        #         logger.error('dbus string is likely empty or doesn\'t exist, this can be safely ignored')
        self._bus.publish(self._c['DBus']['prefix'], self._dbus_mm)
        self._loop.run()
Beispiel #15
0
    def RaiseA(self, msg):
        raise ExceptionA(msg)

    def RaiseB(self, msg):
        raise ExceptionB(msg)

    def RaiseD(self, msg):
        raise ExceptionD(msg)

    def RaiseE(self, msg):
        raise ExceptionE(msg)


bus = SessionBus()

with bus.publish("net.lew21.pydbus.tests.Test", TestObject()):
    remote = bus.get("net.lew21.pydbus.tests.Test")

    def t_func():
        # Test new registered errors.
        try:
            remote.RaiseA("Test A")
        except ExceptionA as e:
            assert str(e) == "Test A"

        try:
            remote.RaiseB("Test B")
        except ExceptionB as e:
            assert str(e) == "Test B"

        # Test mapped errors.
Beispiel #16
0
    def __init__(self, iid):
        self.id = iid

    def HelloWorld(self, a, b):
        res = self.id + ": " + a + str(b)
        global done
        done += 1
        if done == 2:
            loop.quit()
        print("server side: " + res)
        return res


bus = SessionBus()

with bus.publish("net.lew21.pydbus.Test", TestObject("Main"),
                 ("Lol", TestObject("Lol"))):
    remoteMain = bus.get("net.lew21.pydbus.Test")
    remoteLol = bus.get("net.lew21.pydbus.Test", "Lol")

    def t1_func():
        print(remoteMain.HelloWorld("t", 1))

    def t2_func():
        print(remoteLol.HelloWorld("t", 2))

    t1 = Thread(None, t1_func)
    t2 = Thread(None, t2_func)
    t1.daemon = True
    t2.daemon = True

    def handle_timeout():
Beispiel #17
0
		<arg name="request" type="s" direction="in"/>
		<arg name="resp_result" type="b" direction="out"/>
	    <arg name="resp_data" type="s" direction="out"/>
	</method>

	<signal name="UpdateInfo">
	    	<arg type="s" name="info"/>
	</signal>

	</interface>
	</node>
	"""
	UpdateInfo = signal()
	def Get(self, s):
		print("com.ssangyong.AutomotiveProxy.LocationManager " + "Get : " + s)
		return (True, "{\"Data\":null,\"Result\":{\"Message\":\"Success\",\"Status\":true}}")
	def Set(self, s):
		print("com.ssangyong.AutomotiveProxy.LocationManager " + "Set : " + s)
		return "Location Manager - Set"

	def AddListener(self, s):
		print("com.ssangyong.AutomotiveProxy.LocationManager " + "AddListener : " + s)
		self.UpdateInfo("{\"Cmd\":\"PTTEvent\",\"Data\":{\"Action\":\"VrStartEvent123\"}}")
		return (True, "{\"Data\":null,\"Result\":{\"Message\":\"Success\",\"Status\":true}}")

bus = SessionBus()
bus.publish("com.ssangyong.AutomotiveProxy", VrService(),
	("VrManager", VrService()), ("LocationManager", LocationService()))

loop.run()
Beispiel #18
0
		global done
		done += 1
		if done == 2:
			loop.quit()
		return "M1"

	def Method2(self):
		global done
		done += 1
		if done == 2:
			loop.quit()
		return "M2"

bus = SessionBus()

with bus.publish("net.lew21.pydbus.tests.expose_multiface", TestObject()):
	remote = bus.get("net.lew21.pydbus.tests.expose_multiface")

	def t1_func():
		print(remote.Method1())
		print(remote.Method2())

	t1 = Thread(None, t1_func)
	t1.daemon = True

	def handle_timeout():
		print("ERROR: Timeout.")
		sys.exit(1)

	GLib.timeout_add_seconds(2, handle_timeout)
Beispiel #19
0
def setup_mpris(app):
    from pydbus import SessionBus, Variant
    from pydbus.generic import signal

    class MPRIS:
        """
<node>
<interface name="org.mpris.MediaPlayer2">
<property name="CanQuit" type="b" access="read" />
<property name="CanRaise" type="b" access="read" />
<property name="HasTrackList" type="b" access="read" />
<property name="Identity" type="s" access="read" />
<property name="SupportedMimeTypes" type="as" access="read" />
<property name="SupportedUriSchemes" type="as" access="read" />
<method name="Quit" />
<method name="Raise" />
</interface>
<interface name="org.mpris.MediaPlayer2.Player">
<property name="PlaybackStatus" type="s" access="read" />
<property name="Rate" type="d" access="readwrite" />
<property name="Metadata" type="a{sv}" access="read"/>
<property name="Volume" type="d" access="readwrite" />
<property name="Position" type="x" access="read" />
<property name="MinimumRate" type="d" access="readwrite" />
<property name="MaximumRate" type="d" access="readwrite" />
<property name="CanGoNext" type="b" access="read" />

<property name="CanGoPrevious" type="b" access="read" />
<property name="CanPlay" type="b" access="read" />
<property name="CanPause" type="b" access="read" />
<property name="CanSeek" type="b" access="read" />
<property name="CanControl" type="b" access="read" />

<method name="Next" />
<method name="Previous" />
<method name="Pause" />
<method name="PlayPause" />
<method name="Stop" />
<method name="Play" />
<method name="Seek">
  <arg type="x" direction="in" />
</method>
<method name="SetPosition">
  <arg type="o" direction="in" />
  <arg type="x" direction="in" />
</method>
<method name="OpenUri">
  <arg type="s" direction="in" />
</method>
</interface>
</node>
        """

        PropertiesChanged = signal()

        def __init__(self, app):
            self.app = app

        def emit_property_changed(self, attr):
            self.PropertiesChanged("org.mpris.MediaPlayer2.Player",
                                   {attr: getattr(self, attr)}, [])

        @property
        def CanQuit(self):
            return False

        @property
        def CanRaise(self):
            return False

        @property
        def HasTrackList(self):
            return False

        @property
        def Identity(self):
            return "TUIJam"

        @property
        def SupportedMimeTypes(self):
            return []

        @property
        def SupportedUriSchemes(self):
            return []

        def Raise(self):
            pass

        def Quit(self):
            pass

        @property
        def PlaybackStatus(self):
            return {
                "play": "Playing",
                "pause": "Paused",
                "stop": "Stopped"
            }[self.app.play_state]

        @property
        def Rate(self):
            return 1.0

        @Rate.setter
        def Rate(self, rate):
            pass

        @property
        def Metadata(self):
            song = self.app.current_song

            if type(song) == Song:

                logging.info("New song ID: " + str(song.id))

                return {
                    "mpris:trackid":
                    Variant("o", "/org/tuijam/GM_" +
                            str(song.id).replace("-", "_")),
                    "mpris:artUrl":
                    Variant("s", song.albumArtRef),
                    "xesam:title":
                    Variant("s", song.title),
                    "xesam:artist":
                    Variant("as", [song.artist]),
                    "xesam:album":
                    Variant("s", song.album),
                    "xesam:url":
                    Variant("s", song.stream_url),
                }

            elif type(song) == YTVideo:

                return {
                    "mpris:trackid":
                    Variant("o", "/org/tuijam/YT_" +
                            str(song.id).replace("-", "_")),
                    "mpris:artUrl":
                    Variant("s", song.thumbnail),
                    "xesam:title":
                    Variant("s", song.title),
                    "xesam:artist":
                    Variant("as", [song.channel]),
                    "xesam:album":
                    Variant("s", ""),
                    "xesam:url":
                    Variant("s", song.stream_url),
                }

            else:
                return {}

        @property
        def Volume(self):
            return self.app.volume / 8.0

        @Volume.setter
        def Volume(self, volume):
            volume = max(0, min(volume, 1))
            self.app.volume = int(volume * 8)
            self.app.player.volume = volume * 100
            self.emit_property_changed("Volume")

        @property
        def Position(self):
            try:
                return int(1000000 * self.app.player.time_pos)

            except TypeError:
                return 0

        @property
        def MinimumRate(self):
            return 1.0

        @property
        def MaximumRate(self):
            return 1.0

        @property
        def CanGoNext(self):
            return len(self.app.queue_panel.queue) > 0

        @property
        def CanGoPrevious(self):
            return False

        @property
        def CanPlay(self):
            return (len(self.app.queue_panel.queue) > 0
                    or self.app.current_song is not None)

        @property
        def CanPause(self):
            return self.app.current_song is not None

        @property
        def CanSeek(self):
            return self.app.current_song is not None

        @property
        def CanControl(self):
            return True

        def Next(self):
            self.app.queue_panel.play_next()

        def Previous(self):
            pass

        def Pause(self):
            if self.app.play_state == "play":
                self.app.toggle_play()

        def PlayPause(self):
            self.app.toggle_play()

        def Stop(self):
            self.app.stop()

        def Play(self, song_id):
            self.app.toggle_play()

        def Seek(self, offset):
            pass

        def SetPosition(self, track_id, position):
            pass

        def OpenUri(self, uri):
            pass

    mpris = MPRIS(app)
    bus = SessionBus()
    try:
        bus.publish("org.mpris.MediaPlayer2.tuijam",
                    ("/org/mpris/MediaPlayer2", mpris))
        return mpris
    except RuntimeError as e:
        logging.exception(e)
        return None
    def Progress(self, value):
        self._progress = value
        self.PropertiesChanged(Installer.interface, {'Progress': self.Progress}, [])

    @property
    def LastError(self):
        return self._last_error

    @LastError.setter
    def LastError(self, value):
        self._last_error = value
        self.PropertiesChanged(Installer.interface, {'LastError': self.LastError}, [])


if __name__ == '__main__':
    import argparse
    from pydbus import SessionBus

    parser = argparse.ArgumentParser()
    parser.add_argument('bundle', help='Expected RAUC bundle')
    parser.add_argument('--completed-code', type=int, default=0,
                        help='Code to emit as D-Bus Completed signal')
    args = parser.parse_args()

    loop = GLib.MainLoop()
    bus = SessionBus()
    installer = Installer(args.bundle, args.completed_code)
    with bus.publish('de.pengutronix.rauc', ('/', installer)):
        print('Interface published')
        loop.run()
Beispiel #21
0
	"""
		<node>
			<interface name='net.lew21.pydbus.ClientServerExample'>
				<method name='Hello'>
					<arg type='s' name='response' direction='out'/>
				</method>
				<method name='EchoString'>
					<arg type='s' name='a' direction='in'/>
					<arg type='s' name='response' direction='out'/>
				</method>
				<method name='Quit'/>
			</interface>
		</node>
	"""

	def Hello(self):
		"""returns the string 'Hello, World!'"""
		return "Hello, World!"

	def EchoString(self, s):
		"""returns whatever is passed to it"""
		return s

	def Quit(self):
		"""removes this object from the DBUS connection and exits"""
		loop.quit()

bus = SessionBus()
bus.publish("net.lew21.pydbus.ClientServerExample", MyDBUSService())
loop.run()
Beispiel #22
0
    """
		<node>
			<interface name='net.lew21.pydbus.ClientServerExample'>
				<method name='Hello'>
					<arg type='s' name='response' direction='out'/>
				</method>
				<method name='EchoString'>
					<arg type='s' name='a' direction='in'/>
					<arg type='s' name='response' direction='out'/>
				</method>
				<method name='Quit'/>
			</interface>
		</node>
	"""
    def Hello(self):
        """returns the string 'Hello, World!'"""
        return "Hello, World!"

    def EchoString(self, s):
        """returns whatever is passed to it"""
        return s

    def Quit(self):
        """removes this object from the DBUS connection and exits"""
        loop.quit()


bus = SessionBus()
bus.publish("net.lew21.pydbus.ClientServerExample", MyDBUSService())
loop.run()
Beispiel #23
0
            self._timer = threading.Timer(self.next_call - time.time(),
                                          self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False


if __name__ == "__main__":
    # Launch the server
    # Use pydbus to establish a session gdbus. Rather than system gdbus
    # TODO: Use try/except, etc. in case bus already exists. e.g. bus.get(BUS)
    bus = SessionBus()
    bus.publish(BUS, DBusService())

    # Start the repeating timer. It auto-starts, no need of rt.start()
    # RepeatedTimer(period between function calls, function())
    rt = RepeatedTimer(period, timer_event)

    # Enable R-Pi channel to perform callbacks on detection of a pulse.
    if not simulated_pulse:
        #GPIO.add_event_detect(channel, GPIO.RISING, callback=pulse_callback,
        #                      bouncetime=1)
        GPIO.add_event_detect(channel,
                              GPIO.FALLING,
                              callback=pulse_callback,
                              bouncetime=1)
    print("server running...")
    try:
Beispiel #24
0
    class GlibT:
        receive_queue = attr.ib()
        send_queue = attr.ib()
        data_dir = attr.ib()
        server_list = attr.ib()
        config = attr.ib()

        loop = attr.ib(init=False)
        store = attr.ib(init=False)
        users = attr.ib(init=False)
        devices = attr.ib(init=False)
        bus = attr.ib(init=False)
        control_if = attr.ib(init=False)
        device_if = attr.ib(init=False)
        notifications = attr.ib(type=bool, default=False, init=False)

        def __attrs_post_init__(self):
            self.loop = None

            id_counter = IdCounter()

            self.control_if = Control(self.send_queue, self.server_list,
                                      id_counter)
            self.device_if = Devices(self.send_queue, id_counter)

            self.bus = SessionBus()
            self.bus.publish("org.pantalaimon1", self.control_if,
                             self.device_if)

        def unverified_notification(self, message):
            notificaton = notify2.Notification(
                "Unverified devices.",
                message=(f"There are unverified devices in the room "
                         f"{message.room_display_name}."),
            )
            notificaton.set_category("im")

            def send_cb(notification, action_key, user_data):
                message = user_data
                self.control_if.SendAnyways(message.pan_user, message.room_id)

            def cancel_cb(notification, action_key, user_data):
                message = user_data
                self.control_if.CancelSending(message.pan_user,
                                              message.room_id)

            if "actions" in notify2.get_server_caps():
                notificaton.add_action("send", "Send anyways", send_cb,
                                       message)
                notificaton.add_action("cancel", "Cancel sending", cancel_cb,
                                       message)

            notificaton.show()

        def sas_invite_notification(self, message):
            notificaton = notify2.Notification(
                "Key verification invite",
                message=(
                    f"{message.user_id} via {message.device_id} has started "
                    f"a key verification process."),
            )
            notificaton.set_category("im")

            def accept_cb(notification, action_key, user_data):
                message = user_data
                self.device_if.AcceptKeyVerification(message.pan_user,
                                                     message.user_id,
                                                     message.device_id)

            def cancel_cb(notification, action_key, user_data):
                message = user_data
                self.device_if.CancelKeyVerification(message.pan_user,
                                                     message.user_id,
                                                     message.device_id)

            if "actions" in notify2.get_server_caps():
                notificaton.add_action("accept", "Accept", accept_cb, message)
                notificaton.add_action("cancel", "Cancel", cancel_cb, message)

            notificaton.show()

        def sas_show_notification(self, message):
            emojis = [x[0] for x in message.emoji]

            emoji_str = "   ".join(emojis)

            notificaton = notify2.Notification(
                "Short authentication string",
                message=(
                    f"Short authentication string for the key verification of"
                    f" {message.user_id} via {message.device_id}:\n"
                    f"{emoji_str}"),
            )
            notificaton.set_category("im")

            def confirm_cb(notification, action_key, user_data):
                message = user_data
                self.device_if.ConfirmKeyVerification(message.pan_user,
                                                      message.user_id,
                                                      message.device_id)

            def cancel_cb(notification, action_key, user_data):
                message = user_data
                self.device_if.CancelKeyVerification(message.pan_user,
                                                     message.user_id,
                                                     message.device_id)

            if "actions" in notify2.get_server_caps():
                notificaton.add_action("confirm", "Confirm", confirm_cb,
                                       message)
                notificaton.add_action("cancel", "Cancel", cancel_cb, message)

            notificaton.show()

        def sas_done_notification(self, message):
            notificaton = notify2.Notification(
                "Device successfully verified.",
                message=(
                    f"Device {message.device_id} of user {message.user_id} "
                    f"successfully verified."),
            )
            notificaton.set_category("im")
            notificaton.show()

        def message_callback(self):
            try:
                message = self.receive_queue.get_nowait()
            except Empty:
                return True

            logger.debug(f"UI loop received message {message}")

            if isinstance(message, UpdateDevicesMessage):
                self.device_if.update_devices(message)

            elif isinstance(message, UpdateUsersMessage):
                self.control_if.update_users(message)

            elif isinstance(message, UnverifiedDevicesSignal):
                self.control_if.UnverifiedDevices(message.pan_user,
                                                  message.room_id,
                                                  message.room_display_name)

                if self.notifications:
                    self.unverified_notification(message)

            elif isinstance(message, InviteSasSignal):
                self.device_if.VerificationInvite(
                    message.pan_user,
                    message.user_id,
                    message.device_id,
                    message.transaction_id,
                )

                if self.notifications:
                    self.sas_invite_notification(message)

            elif isinstance(message, ShowSasSignal):
                self.device_if.VerificationString(
                    message.pan_user,
                    message.user_id,
                    message.device_id,
                    message.transaction_id,
                    message.emoji,
                )

                if self.notifications:
                    self.sas_show_notification(message)

            elif isinstance(message, SasDoneSignal):
                self.device_if.VerificationDone(
                    message.pan_user,
                    message.user_id,
                    message.device_id,
                    message.transaction_id,
                )

                if self.notifications:
                    self.sas_done_notification(message)

            elif isinstance(message, DaemonResponse):
                self.control_if.Response(
                    message.message_id,
                    message.pan_user,
                    {
                        "code": message.code,
                        "message": message.message
                    },
                )

            elif isinstance(message, KeyRequestMessage):
                self.device_if.update_key_requests(message)

            self.receive_queue.task_done()
            return True

        def run(self):
            self.loop = GLib.MainLoop()

            if self.config.notifications:
                try:
                    notify2.init("pantalaimon", mainloop=self.loop)
                    self.notifications = True
                except dbus.DBusException:
                    logger.error(
                        "Notifications are enabled but no notification "
                        "server could be found, disabling notifications.")
                    self.notifications = False

            GLib.timeout_add(100, self.message_callback)
            if not self.loop:
                return

            self.loop.run()

        def stop(self):
            if self.loop:
                self.loop.quit()
                self.loop = None
Beispiel #25
0
class DeviceManagerAPI(object):
    """
    <node>
        <interface name='org.chemlab.UChroma.DeviceManager'>
            <method name='GetDevices'>
                <arg direction='out' type='ao' />
            </method>

            <signal name='DevicesChanged'>
                <arg direction='out' type='s' name='action' />
                <arg direction='out' type='o' name='device' />
            </signal>
        </interface>
    </node>
    """
    def __init__(self, device_manager, logger):
        self._dm = device_manager
        self._logger = logger
        self._bus = None
        self._dm.callbacks.append(self._dm_callback)
        self._devs = OrderedDict()

    def GetDevices(self):
        """
        Get the list of object paths associated with discovered devices
        """
        if self._dm.devices is None:
            return []
        return tuple([x.bus_path for x in self._devs.values()])

    DevicesChanged = signal()

    def _publish_device(self, device):
        devapi = DeviceAPI(device, self._bus)
        devapi.publish()

        self._devs[device.key] = devapi

        return devapi.bus_path

    def _unpublish_device(self, device):
        devapi = self._devs.pop(device.key, None)
        if devapi is not None:
            devapi.unpublish()
            return devapi.bus_path

        return None

    async def _dm_callback(self, action, device):
        self._logger.info('%s: %s', action, device)

        path = None

        if action == 'add':
            path = self._publish_device(device)
            device.fire_restore_prefs()

        elif action == 'remove':
            path = self._unpublish_device(device)

        else:
            return

        if path is not None:
            self.DevicesChanged(action, path)

    def run(self):
        """
        Publish the service
        """
        self._bus = SessionBus()
        self._bus.publish('org.chemlab.UChroma', self)
Beispiel #26
0
player = Mpvplayer()
player.start()


class DBUSPlayerService(object):
    """
        <node>
            <interface name='github.zhangn1985.dbplay'>
                <method name='play'>
                    <arg type='s' name='playinfo' direction='in'/>
                </method>
				<method name='stop'/>
				<method name='exit'/>
            </interface>
        </node>
    """
    def play(self, playinfo):
        player.play(playinfo)

    def stop(self):
        player.stop()

    def exit(self):
        player.exit()
        loop.quit()


bus = SessionBus()
bus.publish("github.zhangn1985.dbplay", DBUSPlayerService())
loop.run()
Beispiel #27
0
        "From Cleint 3. Return Hello and the persons name"
        print("From Client 3: Hello {}".format(name))
        return

    def get_time_stamp(self):
        "From Client 2. Return a Unix time. Seconds since epoch"
        return time.time()  # 1511326564.8677926

    def server_no_args(self):
        "From Client 1. No arguments, Server has a message on the console."
        global message_count
        print("From Client 1: This is message {}".format(message_count))
        message_count += 1
        return


def timer():
    "Emit a random integer each call."
    random_integer = random.randint(0, 100)
    print("Random integer emitted: {}".format(random_integer))
    emit.integer_signal(random_integer)
    return True


if __name__ == "__main__":
    emit = DBusService_XML()
    bus.publish(BUS, emit)

    GLib.timeout_add_seconds(interval=INTERVAL, function=timer)
    loop.run()
Beispiel #28
0
bus = SessionBus()  # SystemBus
BUS = "org.example.demo.test"
loop = GLib.MainLoop()


class DBusService_XML():
    """
    DBus Service XML definition. 
    type="i" for integer, "s" string, "d" double, "as" list of string data.
    """
    dbus = """
    <node>
        <interface name="{}">
            <method name="get_time_stamp">
                <arg type="d" name="response" direction="out">
                </arg>
            </method>
        </interface>
    </node>
    """.format(BUS)

    def get_time_stamp(self):
        "Return a Unix time. Seconds since epoch"
        return time.time()  # 1511326564.8677926


if __name__ == "__main__":
    print("Starting Server Demo 2...")
    bus.publish(BUS, DBusService_XML())
    loop.run()
Beispiel #29
0
        self._who = "human"
        self._state = "good"

    def hello(self):
        return "Hello %s!" % self._who

    def quit(self):
        loop.quit()

    def whatsup(self):
        return "@!#$*&@!, %s!" % self._who

    @property
    def State(self):
        return self._state

    @property
    def Who(self):
        return self._who

    @Who.setter
    def Who(self, value):
        self._who = value
        self.PropertiesChanged("org.me.test1", {"Who": self._who}, [])

    PropertiesChanged = signal()

bus = SessionBus()
bus.publish("org.me.test", MyDBUSService())
loop.run()
Beispiel #30
0
    """
    <?xml version="1.0" encoding="UTF-8" ?>
    <node xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">

    <interface name="com.lge.car.micom.can">
        <method name="TriggerTest"/>

        <signal name="NotifyKeyFrontPannelEvent">
            <arg name="front" direction="out" type="ay"/>
        </signal>
    </interface>
    </node>
    """

    NotifyKeyFrontPannelEvent = signal()

    def TriggerTest(self):
        keyEvent = [0x16, 0x01]
        print(
            "LG AVN Can DBus Server - method name: TriggerTest, key value: " +
            str(keyEvent[0]) + ", type1: " + str(keyEvent[1]))
        self.NotifyKeyFrontPannelEvent(keyEvent)
        pass


bus = SessionBus()
bus.publish("com.lge.car.micom", LgAvnCanService(),
            ("/Can", LgAvnCanService()))
loop = GLib.MainLoop()
loop.run()
Beispiel #31
0
    builder.connect_signals(Handler())

    main_window = builder.get_object("main_window")
    # add_app_dialog = builder.get_object("add_app_dialog")
    # edit_app_dialog = builder.get_object("edit_app_dialog")
    # app_list_treeview = builder.get_object("app_list_treeview")
    server_status_label = builder.get_object("server_status_label")
    assistant_listbox = builder.get_object("assistant_listbox")

    # select = app_list_treeview.get_selection()
    # select.connect("changed", Handler.on_tree_selection_changed)

    # draw_table()

    client_bus = SessionBus()
    client_bus.publish("org.LinuxAssistantClient", DBusService())

    server_bus = SessionBus()
    is_server_running = False

    try:
        server = server_bus.get("org.LinuxAssistantServer")
        is_server_running = server.client_init()
    except:
        print("Server is not running")

    if is_server_running is True:
        server_status_label.set_text("Server is running")
    else:
        server_status_label.set_text("Server is not running")
Beispiel #32
0
from playthread import Mpvplayer

loop = GLib.MainLoop()
player = Mpvplayer()
player.start()

class DBUSPlayerService(object):
    """
        <node>
            <interface name='github.zhangn1985.dbplay'>
                <method name='play'>
                    <arg type='s' name='playinfo' direction='in'/>
                </method>
				<method name='stop'/>
				<method name='exit'/>
            </interface>
        </node>
    """

    def play(self, playinfo):
        player.play(playinfo)
    def stop(self):
        player.stop()
    def exit(self):
        player.exit()
        loop.quit()

bus = SessionBus()
bus.publish("github.zhangn1985.dbplay", DBUSPlayerService())
loop.run()
        print('TestCharacteristic Read: ' + repr(self.Value))
        return self.Value

    def WriteValue(self, value, options):
        valueString = ""
        for i in range(0, len(value)):
            valueString += str(value[i])
        print('TestCharacteristic on was written : ' + valueString)

        self.Value = value
        self.ValueString = valueString


sessionBus = SessionBus()
sessionBus.publish(
    'org.bluez.example.advertisement',
    Advertisement())  # we are only allowed to publish on the Session Bus

sessionBus.publish('org.bluez.example.service0', Service())
sessionBus.publish('org.bluez.example.service0.characteristic0',
                   Characteristic())

#sessionBus.request_name('org.bluez.example.application',"/")

sessionBus.publish('org.bluez.example.application', Application())

appBus = systemBus.get('org.freedesktop.DBus',
                       '/org/bluez/example/application')
advBus = sessionBus.get('org.freedesktop.DBus',
                        '/org/bluez/example/advertisement')
# help(advBus)
Beispiel #34
0
        if not self.is_running:
          self.next_call += self.interval
          self._timer = threading.Timer(self.next_call - time.time(), self._run)
          self._timer.start()
          self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

if __name__=="__main__":
    # Launch the server
    # Use pydbus to establish a session gdbus. Rather than system gdbus
    # TODO: Use try/except, etc. in case bus already exists. e.g. bus.get(BUS)
    bus = SessionBus()
    bus.publish(BUS, DBusService())

    # Start the repeating timer. It auto-starts, no need of rt.start()
    # RepeatedTimer(period between function calls, function())
    rt = RepeatedTimer(period, timer_event)

    # Enable R-Pi channel to perform callbacks on detection of a pulse.
    if not simulated_pulse:
        #GPIO.add_event_detect(channel, GPIO.RISING, callback=pulse_callback, 
        #                      bouncetime=1)
        GPIO.add_event_detect(channel, GPIO.FALLING, callback=pulse_callback, 
                              bouncetime=1)
    print("server running...")
    try:
        loop.run()
    except KeyboardInterrupt:
Beispiel #35
0
		<property name="Foo" type="s" access="read"/>
		<property name="Bar" type="s" access="write"/>
		<method name='Quit'/>
	</interface>
</node>
	'''
	def __init__(self):
		self.Foo = "foo"
		self.Foobar = "foobar"

	def Quit(self):
		loop.quit()

bus = SessionBus()

with bus.publish("net.lew21.pydbus.tests.publish_properties", TestObject()):
	remote = bus.get("net.lew21.pydbus.tests.publish_properties")
	remote_iface = remote['net.lew21.pydbus.tests.publish_properties']

	def t1_func():
		for obj in [remote, remote_iface]:
			assert(obj.Foo == "foo")
			assert(obj.Foobar == "foobar")
			obj.Foobar = "barfoo"
			assert(obj.Foobar == "barfoo")
			obj.Foobar = "foobar"
			assert(obj.Foobar == "foobar")
			obj.Bar = "rab"

		remote.Foobar = "barfoo"
Beispiel #36
0
	'''
	def __init__(self, id):
		self.id = id

	def HelloWorld(self, a, b):
		res = self.id + ": " + a + str(b)
		global done
		done += 1
		if done == 2:
			loop.quit()
		print(res)
		return res

bus = SessionBus()

with bus.publish("net.lew21.pydbus.Test", TestObject("Main"), ("Lol", TestObject("Lol"))):
	remoteMain = bus.get("net.lew21.pydbus.Test")
	remoteLol = bus.get("net.lew21.pydbus.Test", "Lol")

	def t1_func():
		print(remoteMain.HelloWorld("t", 1))

	def t2_func():
		print(remoteLol.HelloWorld("t", 2))

	t1 = Thread(None, t1_func)
	t2 = Thread(None, t2_func)
	t1.daemon = True
	t2.daemon = True

	def handle_timeout():
Beispiel #37
0
            <arg type="n" name="connectionState" direction="out"/>
        </signal>
        <signal name="SourceNotification">
            <arg type="q" name="sourceID" direction="out"/>
            <arg type="n" name="type" direction="out"/> <!-- am_notification_e type; int16_t value; -->
            <arg type="n" name="value" direction="out"/> <!-- am_notification_e type; int16_t value; -->
        </signal>
    </interface>
    </node>
    """

    MainConnectionStateChanged = signal()
    SourceNotification = signal()

    def Connect(self, sourceId, sinkId):
        print("LG AVN DBus Server - method name: Connect, sourceId: " + str(sourceId) + ", sinkId: " + str(sinkId))
        self.MainConnectionStateChanged(1, 1)
        self.SourceNotification(123, 0, 1)
        return (0, 1)

    def Disconnect(self, s):
        print("LG AVN DBus Server - method name: Disconnect" + ", parameters: " + s)
        return (0)

bus = SessionBus()
bus.publish("org.genivi.audiomanager",
    LgAvnAudioManagerService(),
    ("commandinterface", LgAvnAudioManagerService()))
loop = GLib.MainLoop()
loop.run()