Ejemplo n.º 1
0
func (c *client) bridgeToMaster(host net.IP, port int) {

	log.Debugf("Bridging to the master: %s:%d", host, port)

	mqttURL := fmt.Sprintf("%s:%d", host, port)

	clientID := "slave-" + config.Serial()

	log.Infof("Connecting to master %s using cid:%s", mqttURL, clientID)

	c.masterBus = bus.MustConnect(mqttURL, clientID)
	c.localBus = bus.MustConnect(fmt.Sprintf("%s:%d", config.MustString("mqtt.host"), config.MustInt("mqtt.port")), "meshing")

	log.Infof("Connected to master? %t", c.masterBus.Connected())

	if c.masterBus.Connected() {
		c.setUnorphaned()
	} else {
		c.setOrphaned()
	}

	c.masterBus.OnDisconnect(func() {
		log.Infof("Disconnected from master")
		go func() {
			time.Sleep(time.Second * 5)
			if !c.masterBus.Connected() {
				log.Infof("Still disconnected from master, setting orphaned.")
				c.setOrphaned()
			}
		}()
	})

	c.masterBus.OnConnect(func() {
		log.Infof("Connected to master")
		go func() {
			time.Sleep(time.Second * 2)
			if !c.masterBus.Connected() {
				log.Infof("Still connected to master, setting unorphaned")
				c.setUnorphaned()
			}
		}()
	})

	bridgeTopics := []string{"$discover", "$site/#", "$home/#" /*deprecated*/, "$node/#", "$thing/#", "$device/#"}

	c.bridgeMqtt(c.masterBus, c.localBus, true, bridgeTopics)
	c.bridgeMqtt(c.localBus, c.masterBus, false, bridgeTopics)
}
Ejemplo n.º 2
0
// Connect Builds a new ninja connection to the MQTT broker, using the given client ID
func Connect(clientID string) (*Connection, error) {

	log := logger.GetLogger(fmt.Sprintf("%s.connection", clientID))

	conn := Connection{
		log:      log,
		services: []model.ServiceAnnouncement{},
	}

	mqttURL := fmt.Sprintf("%s:%d", config.MustString("mqtt", "host"), config.MustInt("mqtt", "port"))

	log.Infof("Connecting to %s using cid:%s", mqttURL, clientID)

	conn.mqtt = bus.MustConnect(mqttURL, clientID)

	log.Infof("Connected")

	conn.rpc = rpc.NewClient(conn.mqtt, json2.NewClientCodec())
	conn.rpcServer = rpc.NewServer(conn.mqtt, json2.NewCodec())

	// Add service discovery service. Responds to queries about services exposed in this process.
	discoveryService := &discoverService{&conn}
	_, err := conn.exportService(discoveryService, "$discover", &simpleService{*discoveryService.GetServiceAnnouncement()})
	if err != nil {
		log.Fatalf("Could not expose discovery service: %s", err)
	}

	return &conn, nil
}
Ejemplo n.º 3
0
func createBus(conf *Config, agent *Agent) *Bus {
	var addr string
	if strings.HasPrefix(conf.LocalUrl, "tcp://") {
		addr = conf.LocalUrl[len("tcp://"):]
	} else {
		addr = conf.LocalUrl
	}
	logger.Infof("connecting to the bus %s...", addr)
	theBus := bus.MustConnect(addr, "sphere-leds")
	logger.Infof("connected to the bus.")
	return &Bus{conf: conf, bus: theBus, agent: agent}
}