示例#1
0
func SetupEndpoints() {
	// create Publisher
	ep := Config.Endpoints
	var broker *mqtt.Broker
	if ep.Mqtt.Broker != "" {
		broker = mqtt.NewBroker(ep.Mqtt.Broker)
		Publisher = broker.Publisher()
	} else if ep.Nanomsg.Pub != "" {
		Publisher = nanomsg.NewPublisher(ep.Nanomsg.Pub, true)
	}
	if Publisher == nil {
		log.Fatalln("Failed to initialise pub endpoint")
	}

	// create Subscriber
	if ep.Mqtt.Broker != "" {
		Subscriber = broker.Subscriber()
	} else if ep.Nanomsg.Sub != "" {
		Subscriber = nanomsg.NewSubscriber(ep.Nanomsg.Sub, "", true)
	}
	if Subscriber == nil {
		log.Fatalln("Failed to initialise sub endpoint")
	}

	// listen for config changes
	go ConfigWatcher()
	// listen for commands
	go QuerySubscriber()
}
示例#2
0
文件: main.go 项目: kienhung/gohome
func (self *Service) Run() error {
	ep := services.Config.Endpoints

	routing := map[pubsub.Subscriber][]pubsub.Publisher{}

	// setup subscribers
	var subscribers []pubsub.Subscriber
	var publishers []pubsub.Publisher
	if ep.Nanomsg.Pub != "" {
		sub := nanomsg.NewSubscriber(ep.Nanomsg.Pub, "", false)
		subscribers = append(subscribers, sub)
	}
	if ep.Mqtt.Broker != "" {
		broker := mqtt.NewBroker(ep.Mqtt.Broker)
		pub := broker.Publisher()
		publishers = append(publishers, pub)
		for _, sub := range subscribers {
			routing[sub] = append(routing[sub], pub)
		}
		// do not add the mqtt publisher to the mqtt subscriber, otherwise
		// this creates a loop. The mqtt broker itself relays messages.
		sub := broker.Subscriber()
		subscribers = append(subscribers, sub)
	}

	// setup publishers
	if ep.Nanomsg.Sub != "" {
		pub := nanomsg.NewPublisher(ep.Nanomsg.Sub, false)
		publishers = append(publishers, pub)
		for _, sub := range subscribers {
			routing[sub] = append(routing[sub], pub)
		}
	}

	log.Println("Subscriber endpoints:")
	for _, sub := range subscribers {
		log.Println("-", sub.ID())
	}
	log.Println("Publisher endpoints:")
	for _, pub := range publishers {
		log.Println("-", pub.ID())
	}

	// Copy from subscribers to publishers
	var wg sync.WaitGroup
	wg.Add(len(subscribers))
	for _, sub := range subscribers {
		// for each subscriber
		go func(sub pubsub.Subscriber) {
			pubs := routing[sub]
			// wait for an event
			for ev := range sub.Channel() {
				// send the event onto publishers
				for _, pub := range pubs {
					pub.Emit(ev)
				}
				atomic.AddUint64(&self.Processed, 1)
			}
			wg.Done()
		}(sub)
	}

	wg.Wait()

	return nil
}