예제 #1
0
	def callSync(self, *args, warnWhenCallIsSlow=True, **kwargs):
		"""Call a camera DBus API. First arg is the function name.
			
			This is the synchronous version of the call() method. It
			is much slower to call synchronously than asynchronously!
		
			See http://doc.qt.io/qt-5/qdbusabstractinterface.html#call for details about calling.
			See https://github.com/krontech/chronos-cli/tree/master/src/api for implementation details about the API being called.
			See README.md at https://github.com/krontech/chronos-cli/tree/master/src/daemon for API documentation.
		"""
		
		#Unwrap D-Bus errors from message.
		log.debug("%s.callSync %s", self.name, tuple(args))
		
		start = perf_counter()
		msg = QDBusReply(self.iface.call(*args, **kwargs))
		end = perf_counter()
		if warnWhenCallIsSlow and (end - start > API_SLOW_WARN_MS / 1000):
			log.warn(f'slow call: {self.name}.callSync{tuple(args)} took {(end-start)*1000:.0f}ms/{API_SLOW_WARN_MS}ms.')
		
		if msg.isValid():
			return msg.value()
		else:
			if msg.error().name() == 'org.freedesktop.DBus.Error.NoReply':
				raise DBusException(f"{self.name}.callSync{tuple(args)} timed out ({API_TIMEOUT_MS}ms)")
			else:
				raise DBusException("%s: %s" % (msg.error().name(), msg.error().message()))
예제 #2
0
    def callMethod(cls,
                   method_name: str,
                   signature: str,
                   *args,
                   service_path: str = DefaultServicePath,
                   object_path: str = DefaultObjectPath,
                   interface: str = DefaultInterface) -> Any:
        cls.__ensureDBusSetup()
        assert cls.__connection is not None

        if cls.__use_qt:
            message = QDBusMessage.createMethodCall(service_path, object_path,
                                                    interface, method_name)
            message.setArguments(args)
            result = QDBusReply(cls.__connection.call(message))
            if result.isValid():
                return result.value()
            else:
                log.warning("Did not receive a valid reply for method call %s",
                            method_name)
                log.warning(result.error().message())
                return None

        else:
            return cls.__connection.call_blocking(service_path, object_path,
                                                  interface, method_name,
                                                  signature, args)
예제 #3
0
def main():
    import sys

    app = QCoreApplication(sys.argv)  # noqa: F841

    if not QDBusConnection.sessionBus().isConnected():
        sys.stderr.write("Cannot connect to the D-Bus session bus.\n"
                         "To start it, run:\n"
                         "\teval `dbus-launch --auto-syntax`\n")
        sys.exit(1)

    iface = QDBusInterface(SERVICE_NAME, "/", "", QDBusConnection.sessionBus())

    if iface.isValid():
        msg = iface.call("ping", sys.argv[1] if len(sys.argv) > 1 else "")
        reply = QDBusReply(msg)

        if reply.isValid():
            sys.stdout.write("Reply was: %s\n" % reply.value())
            sys.exit()

        sys.stderr.write("Call failed: %s\n" % reply.error().message())
        sys.exit(1)

    sys.stderr.write("%s\n" %
                     QDBusConnection.sessionBus().lastError().message())
    sys.exit(1)
    def inhibit(self):
        msg = self.call("Inhibit", "DMovie", "Video Playing!")
        reply = QDBusReply(msg)

        if reply.isValid():
            self._inhibit_cookie = reply.value()
            return self._inhibit_cookie
        else:
            return None
예제 #5
0
    def inhibit(self):
        msg = self.call("Inhibit", "DMovie", "Video Playing!")
        reply = QDBusReply(msg)

        if reply.isValid():
            self._inhibit_cookie = reply.value()
            return self._inhibit_cookie
        else:
            return None
예제 #6
0
	def __rescan(self):
		self._connections.clear()
		for interfaces in self._networkInterfaces:
			carrier = QDBusReply(
				interfaces['Device property interface'].call('Get',
					'org.freedesktop.NetworkManager.Device.Wired', 'Carrier' ) ) #Interface, Property
			if carrier.isValid() and carrier.value():
				try:
					addr = IPv4Address(
						QDBusReply(
							interfaces['Device property interface'].call(
								'Get', #Method
								'org.freedesktop.NetworkManager.Device', #Interface
								'Ip4Address', #Property
							)
						).value()
					)
					addr = IPv4Address('.'.join(reversed(str(addr).split('.')))) #So close. Truly, if there's two ways of representing information… (note: This is actually Python's fault here, the number parses fine in a browser address bar.)
				except AddressValueError:
					try:
						#"Array of tuples of IPv4 address/prefix/gateway. All 3 elements of each tuple are in network byte order. Essentially: [(addr, prefix, gateway), (addr, prefix, gateway), ...]"
						#	-- https://developer.gnome.org/NetworkManager/0.9/spec.html
						addr = IPv6Address(bytes(
							QDBusReply(
								interfaces['Ip6Config property interface'].call(
									'Get', #Method
									'org.freedesktop.NetworkManager.IP6Config', #Interface
									'Addresses', #Property
								)
							).value()[-1][0]
						))
					except (AddressValueError, IndexError):
						addr = None
				
				interface = QDBusReply(
					interfaces['Device property interface'].call(
						'Get', #Method
						'org.freedesktop.NetworkManager.Device', #Interface
						'Interface', #Property
					)
				).value()
				
				if addr:
					self._connections.append({
						'path': interfaces['Device'].path(),
						'name': defaultdict(
							lambda: 'generic connection', 
							{'e': 'ethernet', 'u': 'usb'}
						)[interface[0]],
						'address': addr,
					})
		
		log.info(f'conns: {self._connections}')
		
		for callback in self._callbacks:
			callback(self._connections)
예제 #7
0
파일: menu.py 프로젝트: zxj5470/deepin-menu
 def showRectMenu(self, x, y):
     msg = self.managerIface.registerMenu()
     reply = QDBusReply(msg)
     self.menuIface = MenuObjectInterface(reply.value())
     self.menuIface.showMenu(json.dumps({"x": x,
                                         "y": y,
                                         "isDockMenu": False,
                                         "menuJsonContent": str(self)}))
     self.menuIface.ItemInvoked.connect(self.itemInvokedSlot)
     self.menuIface.MenuUnregistered.connect(self.menuUnregisteredSlot)
예제 #8
0
파일: menu.py 프로젝트: nicklv/deepin-menu
 def showRectMenu(self, x, y):
     msg = self.managerIface.registerMenu()
     reply = QDBusReply(msg)
     self.menuIface = MenuObjectInterface(reply.value())
     self.menuIface.showMenu(json.dumps({"x": x,
                                         "y": y,
                                         "isDockMenu": False,
                                         "menuJsonContent": str(self)}))
     self.menuIface.ItemInvoked.connect(self.itemInvokedSlot)
     self.menuIface.MenuUnregistered.connect(self.menuUnregisteredSlot)
    def notify(self, summary, body, actions=[]):
        varRPlaceId = QVariant(0)
        varRPlaceId.convert(QVariant.UInt)
        varActions = QVariant(actions)
        varActions.convert(QVariant.StringList)

        msg = self.call("Notify", "Deepin Screenshot", varRPlaceId,
                        "deepin-screenshot", summary, body, varActions, {}, -1)
        reply = QDBusReply(msg)
        return reply.value()
예제 #10
0
파일: menu.py 프로젝트: zxj5470/deepin-menu
 def showDockMenu(self, x, y, cornerDirection="down"):
     msg = self.managerIface.registerMenu()
     reply = QDBusReply(msg)
     self.menuIface = MenuObjectInterface(reply.value())
     self.menuIface.showMenu(json.dumps({"x": x,
                                         "y": y,
                                         "isDockMenu": True,
                                         "cornerDirection": cornerDirection,
                                         "menuJsonContent": str(self)}))
     self.menuIface.ItemInvoked.connect(self.itemInvokedSlot)
     self.menuIface.MenuUnregistered.connect(self.menuUnregisteredSlot)
예제 #11
0
파일: menu.py 프로젝트: nicklv/deepin-menu
 def showDockMenu(self, x, y, cornerDirection="down"):
     msg = self.managerIface.registerMenu()
     reply = QDBusReply(msg)
     self.menuIface = MenuObjectInterface(reply.value())
     self.menuIface.showMenu(json.dumps({"x": x,
                                         "y": y,
                                         "isDockMenu": True,
                                         "cornerDirection": cornerDirection,
                                         "menuJsonContent": str(self)}))
     self.menuIface.ItemInvoked.connect(self.itemInvokedSlot)
     self.menuIface.MenuUnregistered.connect(self.menuUnregisteredSlot)
예제 #12
0
def video(*args, **kwargs):
    """
	Call the camera video DBus API. First arg is the function name.
	
	See http://doc.qt.io/qt-5/qdbusabstractinterface.html#call for details about calling.
	See https://github.com/krontech/chronos-cli/tree/master/src/api for implementation details about the API being called.
	See README.md at https://github.com/krontech/chronos-cli/tree/master/src/daemon for API documentation.
	"""
    msg = QDBusReply(cameraVideoAPI.call(*args, **kwargs))
    if not msg.isValid():
        raise DBusException("%s: %s" %
                            (msg.error().name(), msg.error().message()))
    return msg.value()
예제 #13
0
    def inhibitScreenlock(self):
        if not QDBusConnection.sessionBus().isConnected():
            sys.stderr.write("Cannot connect to the D-Bus session bus.\n"
                    "To start it, run:\n"
                    "\teval `dbus-launch --auto-syntax`\n");
            return

        iface = QDBusInterface('org.kde.screensaver', '/ScreenSaver', '',
                QDBusConnection.sessionBus())

        if iface.isValid():
            msg = iface.call('Inhibit', 'DisUpgradeViewKDE', 'Upgrading base OS')
            reply = QDBusReply(msg)
            self.screenLockCookie = reply.value()
    def notify(self, summary, body, actions=[]):
        varRPlaceId = QVariant(0)
        varRPlaceId.convert(QVariant.UInt)
        varActions = QVariant(actions)
        varActions.convert(QVariant.StringList)

        msg = self.call("Notify",
            "Deepin Screenshot",
            varRPlaceId,
            "deepin-screenshot",
            summary,
            body, varActions, {}, -1)
        reply = QDBusReply(msg)
        return reply.value()
예제 #15
0
        def __onAsyncCallFinished(self, watcher):
            assert watcher in self.__pending_async_calls

            success_callback = self.__pending_async_calls[watcher][0]
            error_callback = self.__pending_async_calls[watcher][1]
            del self.__pending_async_calls[watcher]

            reply = QDBusReply(watcher)
            if reply.isValid():
                if success_callback:
                    success_callback(reply.value())
            else:
                if error_callback:
                    error_callback(reply.error().message())
예제 #16
0
    def notify(self, summary, body, actions=[], hints={}):
        varRPlaceId = QVariant(0)
        varRPlaceId.convert(QVariant.UInt)
        varActions = QVariant(actions)
        varActions.convert(QVariant.StringList)
        varHints = QVariant(hints)
        varHints.convert(QVariant.Map)

        msg = self.call("Notify", "Deepin Screenshot", varRPlaceId,
                        "deepin-screenshot", summary, body, varActions,
                        varHints, -1)

        reply = QDBusReply(msg)
        if reply.isValid():
            return reply.value()
        else:
            return None
예제 #17
0
 def getPropertyValue(self, interfaceName, propertyName):
     msg = self.call("Get", interfaceName, propertyName)
     reply = QDBusReply(msg) 
     return reply.value()
예제 #18
0
 def getPrimaryRect(self):
     msg = self.call("Get", "com.deepin.daemon.Display", "PrimaryRect")
     reply = QDBusReply(msg)
     return reply.value()
예제 #19
0
 def inhibit(self):
     msg = self.call("Inhibit", "DMovie", "Video Playing!")
     reply = QDBusReply(msg)
     self._inhibit_cookie = reply.value()
     return self._inhibit_cookie
예제 #20
0
 def getPrimaryRect(self):
     msg = self.call("Get", "com.deepin.daemon.Display", "PrimaryRect")
     reply = QDBusReply(msg)
     return reply.value()
예제 #21
0
 def registerArea(self, x1, x2, y1, y2, flag):
     msg = self.call("RegisterArea", x1, x2, y1, y2, flag)
     print msg.errorName(), msg.errorMessage()
     reply = QDBusReply(msg)
     return reply.value()
예제 #22
0
파일: ping.py 프로젝트: Axel-Erfurt/pyqt5
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtDBus import QDBusConnection, QDBusInterface, QDBusReply


if __name__ == '__main__':
    app = QCoreApplication(sys.argv)

    if not QDBusConnection.sessionBus().isConnected():
        sys.stderr.write("Cannot connect to the D-Bus session bus.\n"
                "To start it, run:\n"
                "\teval `dbus-launch --auto-syntax`\n");
        sys.exit(1)

    iface = QDBusInterface('org.example.QtDBus.PingExample', '/', '',
            QDBusConnection.sessionBus())

    if iface.isValid():
        msg = iface.call('ping', sys.argv[1] if len(sys.argv) > 1 else "")
        reply = QDBusReply(msg)

        if reply.isValid():
            sys.stdout.write("Reply was: %s\n" % reply.value())
            sys.exit()

        sys.stderr.write("Call failed: %s\n" % reply.error().message())
        sys.exit(1)

    sys.stderr.write("%s\n" % QDBusConnection.sessionBus().lastError().message())
    sys.exit(1)
예제 #23
0
 def registerArea(self, x1, x2, y1, y2, flag):
     msg = self.call("RegisterArea", x1, x2, y1, y2, flag)
     print msg.errorName(), msg.errorMessage()
     reply = QDBusReply(msg)
     return reply.value()
예제 #24
0
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtDBus import QDBusConnection, QDBusInterface, QDBusReply

if __name__ == "__main__":
    app = QCoreApplication(sys.argv)

    if not QDBusConnection.sessionBus().isConnected():
        sys.stderr.write("Cannot connect to the D-Bus session bus.\n"
                         "To start it, run:\n"
                         "\teval `dbus-launch --auto-syntax`\n")
        sys.exit(1)

    iface = QDBusInterface("org.example.QtDBus.PingExample", "/", "",
                           QDBusConnection.sessionBus())

    if iface.isValid():
        msg = iface.call("ping", sys.argv[1] if len(sys.argv) > 1 else "")
        reply = QDBusReply(msg)

        if reply.isValid():
            sys.stdout.write("Reply was: %s\n" % reply.value())
            sys.exit()

        sys.stderr.write("Call failed: %s\n" % reply.error().message())
        sys.exit(1)

    sys.stderr.write("%s\n" %
                     QDBusConnection.sessionBus().lastError().message())
    sys.exit(1)
예제 #25
0
 def inhibit(self):
     msg = self.call("Inhibit", "DMovie", "Video Playing!")
     reply = QDBusReply(msg)
     self._inhibit_cookie = reply.value()
     return self._inhibit_cookie