// Attaches to the running Skype instance. // Client must already be logged-in. // More than one Skype client is unsupported. func Attach() (*Connection, error) { conn, err := dbus.SessionBus() if err != nil { return nil, err } c := &Connection{} c.Events = make(chan Event, 10) c.conn = conn c.obj = conn.Object("com.Skype.API", "/com/Skype") l := Listener{conn: c} if err := conn.Export(l, "/com/Skype/Client", "com.Skype.API.Client"); err != nil { return nil, err } if err := c.SetName("skype4go"); err != nil { return nil, err } if err := c.SetProtocol(7); err != nil { return nil, err } return c, nil }
// Show sends the information in the notification object to the server to be // displayed. func (n Notification) Show() (id uint32, err error) { conn, err := dbus.SessionBus() if err != nil { return } // We need to convert the interface type of the map to dbus.Variant as // people dont want to have to import the dbus package just to make use // of the notification hints. hints := map[string]dbus.Variant{} for k, v := range n.Hints { hints[k] = dbus.MakeVariant(v) } obj := conn.Object(interfacePath, objectPath) call := obj.Call( notify, 0, n.AppName, n.ReplacesID, n.AppIcon, n.Summary, n.Body, n.Actions, hints, n.Timeout) if err = call.Err; err != nil { return } err = call.Store(&id) return }
// GetClient return a connection to the active instance of the internal Dbus // service if any. Return nil, nil if none found. // InterfacePath is an optional string to provide if the object use an interface // path different from SrvObj // func GetClient(SrvObj, SrvPath string, InterfacePath ...string) (*Client, error) { conn, ec := dbus.SessionBus() if ec != nil { return nil, ec } reply, e := conn.RequestName(SrvObj, dbus.NameFlagDoNotQueue) if e != nil { return nil, e } conn.ReleaseName(SrvObj) if reply == dbus.RequestNameReplyPrimaryOwner { // no active instance. return nil, errors.New("no service found") } if len(InterfacePath) == 0 { // Set default interface path = object name. InterfacePath = []string{SrvObj} } // Found active instance, return client. return &Client{ BusObject: conn.Object(SrvObj, dbus.ObjectPath(SrvPath)), srvObj: InterfacePath[0], testErr: func(e error, method string) {}, }, nil }
// getAddgetAddressBookContactsFromDBus gets the phone contacts via the address-book DBus service func getAddressBookContactsFromDBus() ([]textsecure.Contact, error) { var o dbus.ObjectPath var vcardContacts []string conn, err := dbus.SessionBus() if err != nil { return nil, err } obj := conn.Object("com.canonical.pim", "/com/canonical/pim/AddressBook") err = obj.Call("com.canonical.pim.AddressBook.query", 0, "", "", []string{}).Store(&o) if err != nil { return nil, err } obj2 := conn.Object("com.canonical.pim", o) err = obj2.Call("com.canonical.pim.AddressBookView.contactsDetails", 0, []string{}, int32(0), int32(-1)).Store(&vcardContacts) if err != nil { return nil, err } obj.Call("com.canonical.pim.AddressBook.close", 0) if err != nil { return nil, err } return parseVCards(vcardContacts) }
func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) flag.Parse() conn, err := dbus.SessionBus() if err != nil { log.Fatal(err) } o := conn.Object("org.gnome.SessionManager", "/org/gnome/SessionManager") inhibit(o, "inhibitor", "inhibiting", inhibitIdle) inhibit(o, "inhibitor", "inhibiting", inhibitSuspend) if *pid == 0 { fmt.Fprint(os.Stderr, "Inhibiting until this process is killed\n") select {} } fmt.Fprintf(os.Stderr, "Inhibiting until this process or PID %d is killed\n", *pid) for { _, err := os.Stat(fmt.Sprintf("/proc/%d", *pid)) if os.IsNotExist(err) { break } if err != nil { log.Fatal(err) } time.Sleep(*d) } }
func NewdbusWrapper(path string, iface string) (*dbusWrapper, error) { d := new(dbusWrapper) conn, err := dbus.SystemBus() if err != nil { conn, err = dbus.SessionBus() if err != nil { log.Panic(err) } } d.handlers = make(map[string]signalHandler) d.conn = conn d.path = path d.iface = iface d.queue = &signalQueue{cond: &sync.Cond{L: &sync.Mutex{}}} heap.Init(d.queue) filter := fmt.Sprintf("type='signal',path='%[1]s',interface='%[2]s',sender='%[2]s'", path, iface) log.Printf("Filter: %s", filter) conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus").Call("org.freedesktop.DBus.AddMatch", 0, filter) go func() { ch := make(chan *dbus.Signal, 2*QueueCapacity) conn.Signal(ch) for signal := range ch { if !((strings.Index(signal.Name, iface) == 0) && (string(signal.Path) == path)) { continue } if val, ok := d.handlers[signal.Name]; ok { for d.queue.Len() > QueueCapacity-1 { item := heap.Remove(d.queue, d.queue.Len()-1) log.Printf("Removing %+v from queue", item) } heap.Push(d.queue, signalItem{handler: val, signal: signal, timestamp: uint64(time.Now().Unix())}) } else { log.Printf("Unhandled signal: %s", signal.Name) } } }() go func() { for { d.queue.cond.L.Lock() for d.queue.Len() == 0 { d.queue.cond.Wait() } d.queue.cond.L.Unlock() item := heap.Pop(d.queue).(signalItem) item.handler.handler(item.signal.Body...) } }() return d, nil }
// SessionBus creates a Dbus session with a listening chan. // func SessionBus() (*dbus.Conn, chan *dbus.Signal, error) { conn, e := dbus.SessionBus() if e != nil { return nil, nil, e } c := make(chan *dbus.Signal, 10) conn.Signal(c) return conn, c, nil }
func newDesktopNotifications() *desktopNotifications { if _, err := dbus.SessionBus(); err != nil { log.Printf("Error enabling dbus based notifications! %+v\n", err) return createDesktopNotifications() } dn := createDesktopNotifications() dn.supported = true dn.notifications = make(map[string]uint32) return dn }
// SessionBus is part of Interface func (db *dbusImpl) SessionBus() (Connection, error) { if db.sessionBus == nil { bus, err := godbus.SessionBus() if err != nil { return nil, err } db.sessionBus = &connImpl{bus} } return db.sessionBus, nil }
// CloseNotification closes the notification if it exists using its id. func CloseNotification(id uint32) (err error) { conn, err := dbus.SessionBus() if err != nil { return } obj := conn.Object(interfacePath, objectPath) call := obj.Call(closeNotification, 0, id) err = call.Err return }
func NewService() (*Service, error) { conn, err := dbus.SessionBus() if err != nil { return &Service{}, err } return &Service{ conn: conn, dbus: conn.Object(DBusServiceName, DBusPath), }, nil }
func connDbus() *dbus.Object { conn, err := dbus.SessionBus() // couldnt connect to session bus if err != nil { panic(err) } return conn.Object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2") }
func main() { conn, err := dbus.SessionBus() if err != nil { panic(err) } node, err := introspect.Call(conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus")) if err != nil { panic(err) } data, _ := json.MarshalIndent(node, "", " ") os.Stdout.Write(data) }
func ConnectToDBus(bus string) (*DBusClient, error) { c := new(DBusClient) var err error switch bus { case "session": c.bus, err = dbus.SessionBus() case "system": c.bus, err = dbus.SystemBus() default: c.bus, err = dbus.Dial(bus) } if err != nil { return nil, err } if !c.bus.SupportsUnixFDs() { return nil, errors.New("DBus connection does not support file descriptors") } c.path = dbus.ObjectPath("/com/firelizzard/teasvc/Client") err = c.bus.Export(c, c.path, "com.firelizzard.teasvc.Client") if err != nil { return nil, err } c.sigchans = make(map[string](chan *dbus.Signal)) chsig := make(chan *dbus.Signal, 10) go func() { for { sig := <-chsig ch, ok := c.sigchans[sig.Name] if !ok { log.Print("Unhandled signal: " + sig.Name) } select { case ch <- sig: // sent singal, done default: log.Print("Unhandled signal (full channel): " + sig.Name) } } }() c.bus.Signal(chsig) c.bus.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, "type='signal',interface='com.firelizzard.teasvc',member='Pong'") return c, nil }
// GetCapabilities returns the capabilities of the notification server. func GetCapabilities() (c Capabilities, err error) { conn, err := dbus.SessionBus() if err != nil { return } obj := conn.Object(interfacePath, objectPath) call := obj.Call(getCapabilities, 0) if err = call.Err; err != nil { return } s := []string{} if err = call.Store(&s); err != nil { return } for _, v := range s { switch v { case "action-icons": c.ActionIcons = true break case "actions": c.Actions = true break case "body": c.Body = true break case "body-hyperlinks": c.BodyHyperlinks = true break case "body-images": c.BodyImages = true break case "body-markup": c.BodyMarkup = true break case "icon-multi": c.IconMulti = true break case "icon-static": c.IconStatic = true break case "persistence": c.Persistence = true break case "sound": c.Sound = true break } } return }
// GetCapabilities returns the capabilities of the notification server. func GetCapabilities() (c Capabilities, err error) { connection, err := dbus.SessionBus() if err != nil { return } obj := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications") call := obj.Call("org.freedesktop.Notifications.GetCapabilities", 0) if call.Err != nil { return Capabilities{}, call.Err } s := []string{} if err = call.Store(&s); err != nil { return } for _, v := range s { switch v { case "action-icons": c.ActionIcons = true break case "actions": c.Actions = true break case "body": c.Body = true break case "body-hyperlinks": c.BodyHyperlinks = true break case "body-images": c.BodyImages = true break case "body-markup": c.BodyMarkup = true break case "icon-multi": c.IconMulti = true break case "icon-static": c.IconStatic = true break case "persistence": c.Persistence = true break case "sound": c.Sound = true break } } return }
// EavesDrop registers to receive Dbus events for custom parsing. // func EavesDrop(match string) (chan *dbus.Message, error) { conn, e := dbus.SessionBus() if e != nil { return nil, e } e = conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, match).Err if e != nil { return nil, e } c := make(chan *dbus.Message, 10) conn.Eavesdrop(c) return c, nil }
// CloseNotification closes the notification if it exists using its id. func CloseNotification(id uint32) (err error) { connection, err := dbus.SessionBus() if err != nil { return } obj := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications") call := obj.Call("org.freedesktop.Notifications.CloseNotification", 0, id) if call.Err != nil { return call.Err } return }
func main() { conn, err := dbus.SessionBus() if err != nil { panic(err) } obj := conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications") call := obj.Call("org.freedesktop.Notifications.Notify", 0, "", uint32(0), "", "Test", "This is a test of the DBus bindings for go.", []string{}, map[string]dbus.Variant{}, int32(5000)) if call.Err != nil { panic(call.Err) } }
func main() { conn, err := dbus.SessionBus() if err != nil { panic(err) } reply, err := conn.RequestName("com.github.guelfey.Demo", dbus.NameFlagDoNotQueue) if err != nil { panic(err) } if reply != dbus.RequestNameReplyPrimaryOwner { fmt.Fprintln(os.Stderr, "name already taken") os.Exit(1) } propsSpec := map[string]map[string]*prop.Prop{ "com.github.guelfey.Demo": { "SomeInt": { int32(0), true, prop.EmitTrue, func(c *prop.Change) *dbus.Error { fmt.Println(c.Name, "changed to", c.Value) return nil }, }, }, } f := foo("Bar") conn.Export(f, "/com/github/guelfey/Demo", "com.github.guelfey.Demo") props := prop.New(conn, "/com/github/guelfey/Demo", propsSpec) n := &introspect.Node{ Name: "/com/github/guelfey/Demo", Interfaces: []introspect.Interface{ introspect.IntrospectData, prop.IntrospectData, { Name: "com.github.guelfey.Demo", Methods: introspect.Methods(f), Properties: props.Introspection("com.github.guelfey.Demo"), }, }, } conn.Export(introspect.NewIntrospectable(n), "/com/github/guelfey/Demo", "org.freedesktop.DBus.Introspectable") fmt.Println("Listening on com.github.guelfey.Demo / /com/github/guelfey/Demo ...") c := make(chan *dbus.Signal) conn.Signal(c) for _ = range c { } }
// GetServerInformation returns information about the notification server such // as its name and version. func GetServerInformation() (i ServerInformation, err error) { conn, err := dbus.SessionBus() if err != nil { return } obj := conn.Object(interfacePath, objectPath) call := obj.Call(gsInformation, 0) if err = call.Err; err != nil { return } err = call.Store(&i.Name, &i.Vendor, &i.Version, &i.SpecVersion) return }
func main() { iconName := "mail-unread" conn, err := dbus.SessionBus() if err != nil { panic(err) } notificator := notify.New(conn) n := notify.Notification{ AppName: "Test GO App", ReplacesID: uint32(0), AppIcon: iconName, Summary: "Test", Body: "This is a test of the DBus bindings for go.", Actions: []string{}, Hints: map[string]dbus.Variant{}, ExpireTimeout: int32(5000), } id, err := notificator.SendNotification(n) if err != nil { panic(err) } log.Printf("sent notification id: %v", id) caps, err := notificator.GetCapabilities() if err != nil { log.Printf("error fetching capabilities: %v", err) } for x := range caps { fmt.Printf("Registered capability: %v\n", caps[x]) } info, err := notificator.GetServerInformation() if err != nil { log.Printf("error getting server information: %v", err) } fmt.Printf("Name: %v\n", info.Name) fmt.Printf("Vendor: %v\n", info.Vendor) fmt.Printf("Version: %v\n", info.Version) fmt.Printf("Spec: %v\n", info.SpecVersion) // And there is a helper for just sending notifications directly: notify.SendNotification(conn, n) }
func NewDbus(path, iface string) (*Dbus, error) { w := new(Dbus) conn, err := dbus.SystemBus() if err != nil { conn, err = dbus.SessionBus() if err != nil { return nil, err } } w.path = path w.iface = iface w.conn = conn return w, nil }
func (s *Service) Enable() (err error) { s.System, err = dbus.SystemBus() if err != nil { return err } s.Session, err = dbus.SessionBus() if err != nil { return err } s.Subscribe("notify", "", s.handleNotify) s.Subscribe("poweroff", "", s.handlePowerOff) return s.setupSignals() }
func main() { conn, err := dbus.SessionBus() if err != nil { fmt.Fprintln(os.Stderr, "Failed to connect to session bus:", err) os.Exit(1) } conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, "type='signal',path='/org/freedesktop/DBus',interface='org.freedesktop.DBus',sender='org.freedesktop.DBus'") c := make(chan *dbus.Signal, 10) conn.Signal(c) for v := range c { fmt.Println(v) } }
func main() { say.SetLevelWithConfName("info") configFile, config, err := conf.FromArgs() switch { case err != nil: say.Fatalf("Cannot read configuration in `%s` with error: %s", configFile, err.Error()) case configFile == "": say.Infof("You should specify configuration file. Starting with test configuration: %+v", config) default: say.Infof("Starting DeviceHive gateway with configuration in '%s': %+v", configFile, config) } say.SetLevelWithConfName(config.LoggingLevel) bus, err := dbus.SystemBus() if err != nil { say.Infof("Cannot get system bus with error: %s", err.Error()) say.Infof("Trying to use session bus for testing purposes...") if bus, err = dbus.SessionBus(); err != nil { say.Fatalf("Cannot get session bus with error: %s\n", err.Error()) return } } reply, err := bus.RequestName(DBusConnName, dbus.NameFlagDoNotQueue) switch { case err != nil: say.Fatalf("Cannot request name '%s' with error: %s\n", DBusConnName, err.Error()) case reply != dbus.RequestNameReplyPrimaryOwner: say.Fatalf("The name '%s' already taken.", DBusConnName) } if config.DeviceNotificationReceive == conf.DeviceNotificationReceiveByWS { say.Infof("Starting as websocket...") wsImplementation(bus, config) return } if config.DeviceNotificationReceive == conf.DeviceNotificationReceiveByREST { say.Infof("Starting as rest...") restImplementation(bus, config) return } }
// GetServerInformation returns information about the notification server such as its name // and version. func GetServerInformation() (i ServerInformation, err error) { connection, err := dbus.SessionBus() if err != nil { return } obj := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications") call := obj.Call("org.freedesktop.Notifications.GetServerInformation", 0) if call.Err != nil { return ServerInformation{}, call.Err } if err = call.Store(&i.Name, &i.Vendor, &i.Version, &i.SpecVersion); err != nil { return } return }
func main() { var err error SystemBus, err = dbus.SystemBus() if err != nil { log.Errorln("connect to system bus:", err) } else { go monitor(SystemBus, "system") } SessionBus, err = dbus.SessionBus() if err != nil { log.Errorln("connect to session bus:", err) } else { go monitor(SessionBus, "session") } log.Fatalln(ListenAndServe(":3000")) }
func main() { conf := WMATADbus{} if err := config.Load("wmatadbusd", &conf); err != nil { panic(err) } wmata.SetAPIKey(conf.APIKey) conn, err := dbus.SessionBus() if err != nil { panic(err) } reply, err := conn.RequestName("org.anized.wmata.Rail", dbus.NameFlagDoNotQueue) if err != nil { panic(err) } if reply != dbus.RequestNameReplyPrimaryOwner { fmt.Fprintln(os.Stderr, "name already taken") os.Exit(1) } wmata := WMATADbusInterface{} introspectedMethods := introspect.Methods(wmata) node := introspect.Node{ Name: "/org/anized/wmata", Interfaces: []introspect.Interface{ introspect.Interface{ Name: "org.anized.wmata.Rail", Methods: introspectedMethods, }, }, } export := introspect.NewIntrospectable(&node) // str, err := export.Introspect() // fmt.Printf("%s %s\n", str, err) conn.Export(wmata, "/org/anized/wmata/Rail", "org.anized.wmata.Rail") conn.Export( export, "/org/anized/wmata/Rail", "org.freedesktop.DBus.Introspectable", ) select {} }
func main() { conn, err := dbus.SessionBus() if err != nil { fmt.Fprintln(os.Stderr, "Failed to connect to session bus:", err) os.Exit(1) } var s []string err = conn.BusObject().Call("org.freedesktop.DBus.ListNames", 0).Store(&s) if err != nil { fmt.Fprintln(os.Stderr, "Failed to get list of owned names:", err) os.Exit(1) } fmt.Println("Currently owned names on the session bus:") for _, v := range s { fmt.Println(v) } }