func SubscribeToSignals(bus *dbus.Conn, service *AllJoynServiceInfo) { for _, obj := range service.objects { query := "type='signal',sender='" + service.dbusService + "',path='" + obj.dbusPath + "'" bus.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, query) // log.Printf("FILTERING SIGNALS: %s", query) } }
func traverseDbusObjects(bus *dbus.Conn, dbusService, dbusPath string, fn func(path string, node *introspect.Node)) { var xmldata string var node introspect.Node var o = bus.Object(dbusService, dbus.ObjectPath(dbusPath)) err := o.Call("org.freedesktop.DBus.Introspectable.Introspect", 0).Store(&xmldata) if err != nil { log.Printf("Error getting introspect from [%s, %s]: %s", dbusService, dbusPath, err) } err = xml.NewDecoder(strings.NewReader(xmldata)).Decode(&node) if err != nil { log.Printf("Error decoding introspect from [%s, %s]: %s", dbusService, dbusPath, err) } // log.Printf("Introspect: %+v", node) if node.Name != "" && len(node.Interfaces) > 0 { fn(dbusPath, &node) } for _, child := range node.Children { traverseDbusObjects(bus, dbusService, dbusPath+"/"+child.Name, fn) } }
// ConnectEvents registers to receive Dbus applet events. // func (cda *CDDbus) ConnectEvents(conn *dbus.Conn) (e error) { cda.dbusIcon, e = dbuscommon.GetClient(dockpath.DbusObject, string(cda.busPath), dockpath.DbusInterfaceApplet) if e != nil { return e } cda.dbusSub, e = dbuscommon.GetClient(dockpath.DbusObject, string(cda.busPath)+"/sub_icons", dockpath.DbusInterfaceSubapplet) if e != nil { return e } if cda.dbusIcon == nil || cda.dbusSub == nil { return errors.New("missing Dbus interface") } // Log all errors returned from DBus calls. Applets won't have to bother about that. cda.dbusIcon.SetTestErr(cda.testErr) cda.dbusSub.SetTestErr(cda.testErr) // Listen to all events emitted for the icon. matchIcon := "type='signal',path='" + string(cda.busPath) + "',interface='" + dockpath.DbusInterfaceApplet + "',sender='" + dockpath.DbusObject + "'" matchSubs := "type='signal',path='" + string(cda.busPath) + "/sub_icons',interface='" + dockpath.DbusInterfaceSubapplet + "',sender='" + dockpath.DbusObject + "'" e = conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, matchIcon).Err if cda.log.Err(e, "connect to icon DBus events") { return e } e = conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, matchSubs).Err cda.log.Err(e, "connect to subicons DBus events") return e }
func recurseObjects(bus *dbus.Conn, service, prefix string) ([]string, error) { var s string err := bus.Object(service, dbus.ObjectPath(prefix)).Call("org.freedesktop.DBus.Introspectable.Introspect", 0).Store(&s) if err != nil { return nil, err } var n introspect.Node err = xml.Unmarshal([]byte(s), &n) if err != nil { return nil, err } names := make([]string, 0, 100) if len(n.Interfaces) > 1 { names = append(names, prefix) } for _, child := range n.Children { childPath := path.Join(prefix, child.Name) items, err := recurseObjects(bus, service, childPath) if err != nil { return nil, err } names = append(names, items...) } return names, nil }
func New(conn *dbus.Conn, name string) *Player { obj := conn.Object(name, dbusObjectPath).(*dbus.Object) return &Player{ &base{obj}, &player{obj}, } }
func newPrompter(conn *dbus.Conn) *prompter { p := new(prompter) p.cond = sync.NewCond(&p.lock) p.dbusObj = conn.Object("com.subgraph.FirewallPrompt", "/com/subgraph/FirewallPrompt") p.policyMap = make(map[string]*Policy) go p.promptLoop() return p }
func ListServices(bus *dbus.Conn) ([]string, error) { if bus == nil { return nil, fmt.Errorf("bus not available") } var services []string err := bus.BusObject().Call("org.freedesktop.DBus.ListNames", 0).Store(&services) if err != nil { return nil, err } return services, nil }
func NewAllJoynBridge(bus *dbus.Conn) *AllJoynBridge { bridge := new(AllJoynBridge) bridge.bus = bus bridge.signals = make(chan *dbus.Signal, 100) bridge.services = make(map[string]*AllJoynServiceInfo) bridge.sessions = []uint32{} sbuffer := make(chan *dbus.Signal, 100) go bridge.signalsPump(sbuffer) bus.Signal(sbuffer) return bridge }
// main loop func mainLoop(bus *dbus.Conn, service devicehive.Service, config conf.Conf) { // getting server info info, err := service.GetServerInfo(waitTimeout) if err != nil { log.Warnf("Cannot get service info (error: %s)", err) return } // registering device device := devicehive.NewDevice(config.DeviceID, config.DeviceName, devicehive.NewDeviceClass("go-gateway-class", "0.1")) device.Key = config.DeviceKey if len(config.NetworkName) != 0 || len(config.NetworkKey) != 0 { device.Network = devicehive.NewNetwork(config.NetworkName, config.NetworkKey) device.Network.Description = config.NetworkDesc } err = service.RegisterDevice(device, waitTimeout) if err != nil { log.Warnf("Cannot register device (error: %s)", err) return } // start polling commands listener, err := service.SubscribeCommands(device, info.Timestamp, waitTimeout) if err != nil { log.Warnf("Cannot subscribe commands (error: %s)") return } wrapper := DBusWrapper{service: service, device: device} exportDBusObject(bus, &wrapper) for { select { case cmd := <-listener.C: params := "" if cmd.Parameters != nil { buf, err := json.Marshal(cmd.Parameters) if err != nil { log.Warnf("Cannot generate JSON from parameters of command %+v (error: %s)", cmd, err) continue } params = string(buf) } log.Infof("COMMAND %s -> %s(%v)", config.URL, cmd.Name, params) bus.Emit(ComDevicehiveCloudPath, ComDevicehiveCloudIface+".CommandReceived", cmd.Id, cmd.Name, params) } //time.Sleep(5 * time.Second) } }
func List(conn *dbus.Conn) ([]string, error) { var names []string err := conn.BusObject().Call("org.freedesktop.DBus.ListNames", 0).Store(&names) if err != nil { return nil, err } var mprisNames []string for _, name := range names { if strings.HasPrefix(name, baseInterface) { mprisNames = append(mprisNames, name) } } return mprisNames, nil }
// SendNotification is same as Notifier.SendNotification // Provided for convenience. func SendNotification(conn *dbus.Conn, note Notification) (uint32, error) { obj := conn.Object(dbusNotificationsInterface, objectPath) call := obj.Call(notify, 0, note.AppName, note.ReplacesID, note.AppIcon, note.Summary, note.Body, note.Actions, note.Hints, note.ExpireTimeout) if call.Err != nil { return 0, call.Err } var ret uint32 err := call.Store(&ret) if err != nil { log.Printf("error getting uint32 ret value: %v", err) return ret, err } return ret, nil }
// dbusPath returns the dbus path of the job object. func (j *job) dbusPath(conn *dbus.Conn) (dbus.ObjectPath, error) { var jobpath dbus.ObjectPath // get the job path err := conn. Object(upstartServiceDBusPath, upstartManagerObject). Call("com.ubuntu.Upstart0_6.GetJobByName", 0, j.Name). Store(&jobpath) if err != nil { return jobpath, err } return jobpath, nil }
func monitor(conn *dbus.Conn, name string) { call := conn.BusObject().Call("org.freedesktop.DBus.Monitoring.BecomeMonitor", 0, []string{}, uint32(0)) if call.Err != nil { log.Warnln("BecomeMonitor not supported, falling back to AddMatch:", call.Err) for _, v := range []string{"method_call", "method_return", "error", "signal"} { call = conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, "eavesdrop='true',type='"+v+"'") if call.Err != nil { log.Fatalln("add match:", call.Err) } } } ch := make(chan *dbus.Message, 1000) conn.Eavesdrop(ch) log.Infoln("Monitoring", name, "bus") for m := range ch { log.WithField("bus", name).Infoln(m) } }
// export main + introspectable DBus objects func exportDBusObject(bus *dbus.Conn, w *DBusWrapper) { bus.Export(w, ComDevicehiveCloudPath, ComDevicehiveCloudIface) // main service interface serviceInterface := introspect.Interface{ Name: ComDevicehiveCloudIface, Methods: introspect.Methods(w), Signals: []introspect.Signal{ { Name: "CommandReceived", Args: []introspect.Arg{ {"id", "t", "in"}, {"name", "s", "in"}, {"parameters", "s", "in"}, // JSON string }, }, }, } // main service node n := &introspect.Node{ Name: ComDevicehiveCloudPath, Interfaces: []introspect.Interface{ introspect.IntrospectData, prop.IntrospectData, serviceInterface}, } n_obj := introspect.NewIntrospectable(n) log.Tracef("%q introspectable: %s", ComDevicehiveCloudPath, n_obj) bus.Export(n_obj, ComDevicehiveCloudPath, "org.freedesktop.DBus.Introspectable") // root node root := &introspect.Node{ Children: []introspect.Node{ {Name: ComDevicehiveCloudPath}, }, } root_obj := introspect.NewIntrospectable(root) log.Tracef("%q introspectable: %s", "/", root_obj) bus.Export(root_obj, "/", "org.freedesktop.DBus.Introspectable") }
func NewLogindObject(conn *dbus.Conn) *LogindObject { return &LogindObject{ conn.Object("org.freedesktop.login1", "/org/freedesktop/login1"), } }
func NewSession(conn *dbus.Conn, path dbus.ObjectPath) *Session { return &Session{ conn: conn, dbus: conn.Object(DBusServiceName, path), } }
func NewItem(conn *dbus.Conn, path dbus.ObjectPath) *Item { return &Item{ conn: conn, dbus: conn.Object(DBusServiceName, path), } }
func main() { // go func() { // log.Println(http.ListenAndServe("localhost:6060", nil)) // }() var err error var bus *dbus.Conn bus, err = dbus.SystemBus() if err != nil { log.Panic(err) } reply, err := bus.RequestName("com.devicehive.bluetooth", dbus.NameFlagDoNotQueue) if err != nil { log.Panic(err) } if reply != dbus.RequestNameReplyPrimaryOwner { log.Fatal("name already taken") } w := NewBleDbusWrapper(bus) bus.Export(w, dbus.ObjectPath("/com/devicehive/bluetooth"), "com.devicehive.bluetooth") // Introspectable n := &introspect.Node{ Interfaces: []introspect.Interface{ { Name: "com.devicehive.bluetooth", Methods: introspect.Methods(w), Signals: []introspect.Signal{ introspect.Signal{ Name: "PeripheralDiscovered", Args: []introspect.Arg{{"id", "s", "out"}, {"name", "s", "out"}, {"rssi", "i", "out"}}, }, introspect.Signal{ Name: "PeripheralConnected", Args: []introspect.Arg{{"id", "s", "out"}}, }, introspect.Signal{ Name: "PeripheralDisconnected", Args: []introspect.Arg{{"id", "s", "out"}}, }, introspect.Signal{ Name: "NotificationReceived", Args: []introspect.Arg{{"mac", "s", "out"}, {"uuid", "s", "out"}, {"value", "s", "out"}}, }, introspect.Signal{ Name: "IndicationReceived", Args: []introspect.Arg{{"mac", "s", "out"}, {"uuid", "s", "out"}, {"value", "s", "out"}}, }, }, }, }, } root := &introspect.Node{ Children: []introspect.Node{ { Name: "com/devicehive/bluetooth", }, }, } bus.Export(introspect.NewIntrospectable(n), dbus.ObjectPath("/com/devicehive/bluetooth"), "org.freedesktop.DBus.Introspectable") bus.Export(introspect.NewIntrospectable(root), "/", "org.freedesktop.DBus.Introspectable") // workaroud for dbus issue #14 select {} }
func restImplementation(bus *dbus.Conn, config conf.Conf) { err := rest.DeviceRegisterEasy(config.URL, config.DeviceID, config.AccessKey, config.DeviceName, config.DeviceKey, config.NetworkName, config.NetworkKey, config.NetworkDesc) if err != nil { say.Infof("DeviceRegisterEasy error: %s", err.Error()) return } go func() { nControl := rest.NewPollAsync() cControl := rest.NewPollAsync() nOut := make(chan rest.DeviceNotificationResource, 16) cOut := make(chan rest.DeviceCmdResource, 16) go rest.DeviceNotificationPollAsync(config.URL, config.DeviceID, config.AccessKey, nOut, nControl) go rest.DeviceCmdPollAsync(config.URL, config.DeviceID, config.AccessKey, cOut, cControl) for { select { case n := <-nOut: parameters := "" if n.Parameters != nil { b, err := json.Marshal(n.Parameters) if err != nil { say.Infof("Could not generate JSON from parameters of notification %+v\nWith error %s", n, err.Error()) continue } parameters = string(b) } say.Verbosef("NOTIFICATION %s -> %s(%v)", config.URL, n.Notification, parameters) bus.Emit(restObjectPath, restCommandName, uint32(n.Id), n.Notification, parameters) case c := <-cOut: parameters := "" if c.Parameters != nil { b, err := json.Marshal(c.Parameters) if err != nil { say.Infof("Could not generate JSON from parameters of command %+v\nWith error %s", c, err.Error()) continue } parameters = string(b) } say.Verbosef("COMMAND %s -> %s(%v)", config.URL, c.Command, parameters) bus.Emit(restObjectPath, restCommandName, uint32(c.Id), c.Command, parameters) } } }() w := NewDbusRestWrapper(config) bus.Export(w, "/com/devicehive/cloud", DBusConnName) // Introspectable n := &introspect.Node{ Name: "/com/devicehive/cloud", Interfaces: []introspect.Interface{ introspect.IntrospectData, prop.IntrospectData, { Name: "com.devicehive.cloud", Methods: introspect.Methods(w), }, }, } bus.Export(introspect.NewIntrospectable(n), "/com/devicehive/cloud", "org.freedesktop.DBus.Introspectable") root := &introspect.Node{ Children: []introspect.Node{ { Name: "com/devicehive/cloud", }, }, } bus.Export(introspect.NewIntrospectable(root), "/", "org.freedesktop.DBus.Introspectable") select {} }
// New returns a new Properties structure that manages the given properties. // The key for the first-level map of props is the name of the interface; the // second-level key is the name of the property. The returned structure will be // exported as org.freedesktop.DBus.Properties on path. func New(conn *dbus.Conn, path dbus.ObjectPath, props map[string]map[string]*Prop) *Properties { p := &Properties{m: props, conn: conn, path: path} conn.Export(p, path, "org.freedesktop.DBus.Properties") return p }
func systemdObject(conn *dbus.Conn) dbus.BusObject { return conn.Object("org.freedesktop.systemd1", dbus.ObjectPath("/org/freedesktop/systemd1")) }
func NewCollection(conn *dbus.Conn, path dbus.ObjectPath) *Collection { return &Collection{ conn: conn, dbus: conn.Object(DBusServiceName, path), } }
func wsImplementation(bus *dbus.Conn, config conf.Conf) { var conn *ws.Conn for { info, err := rest.GetApiInfo(config.URL) if err == nil { say.Verbosef("API info: %+v", info) c := ws.New(info.WebSocketServerUrl, config.DeviceID, config.SendNotificationQueueCapacity, func(m map[string]interface{}) { p := m["parameters"] params := "" if p != nil { b, err := json.Marshal(p) if err != nil { say.Fatalf("Could not generete JSON from command %+v\nWith error %s", m, err.Error()) } params = string(b) } say.Verbosef("COMMAND %s -> %s(%v)", info.WebSocketServerUrl, m["command"].(string), params) bus.Emit("/com/devicehive/cloud", "com.devicehive.cloud.CommandReceived", uint32(m["id"].(float64)), m["command"].(string), params) }) conn = &c if err == nil { break } } say.Infof("API info error: %s", err.Error()) time.Sleep(5 * time.Second) } w := NewDbusObjectWrapper(conn) go conn.Run(config.AccessKey, func() { conn.RegisterDevice(config.DeviceID, config.DeviceName, config.DeviceKey, config.NetworkName, config.NetworkKey, config.NetworkDesc) conn.Authenticate(config.DeviceID, config.DeviceKey) conn.SubscribeCommands() }) bus.Export(w, "/com/devicehive/cloud", DBusConnName) // Introspectable n := &introspect.Node{ Name: "/com/devicehive/cloud", Interfaces: []introspect.Interface{ introspect.IntrospectData, prop.IntrospectData, { Name: "com.devicehive.cloud", Methods: introspect.Methods(w), }, }, } bus.Export(introspect.NewIntrospectable(n), "/com/devicehive/cloud", "org.freedesktop.DBus.Introspectable") root := &introspect.Node{ Children: []introspect.Node{ { Name: "com/devicehive/cloud", }, }, } bus.Export(introspect.NewIntrospectable(root), "/", "org.freedesktop.DBus.Introspectable") select {} }
func NewNotificationObject(conn *dbus.Conn) *NotificationObject { return &NotificationObject{ conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications"), } }
func (fw *Interface) dbusSignalHandler(bus *dbus.Conn) { rule := fmt.Sprintf("type='signal',sender='%s',path='%s',interface='%s',member='Reloaded'", firewalldName, firewalldPath, firewalldInterface) bus.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule) rule = fmt.Sprintf("type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus',sender='org.freedesktop.DBus',arg0='%s'", firewalldName) bus.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule) signal := make(chan *dbus.Signal, 10) bus.Signal(signal) for s := range signal { if s.Name == "org.freedesktop.DBus.NameOwnerChanged" { name := s.Body[0].(string) new_owner := s.Body[2].(string) if name != firewalldName || len(new_owner) == 0 { continue } // FirewallD startup (specifically the part where it deletes // all existing iptables rules) may not yet be complete when // we get this signal, so make a dummy request to it to // synchronize. fw.obj.Call(firewalldInterface+".getDefaultZone", 0) fw.reload() } else if s.Name == firewalldInterface+".Reloaded" { fw.reload() } } }