Beispiel #1
0
func NewServer() *Server {
	s := &Server{
		Broker: sarif.NewBroker(),
	}
	s.ModuleManager = services.NewModuleManager(s.instantiate)
	return s
}
Beispiel #2
0
func ExampleClient() {
	recv := make(chan bool)

	// Hosting a broker
	broker := sarif.NewBroker()
	go broker.Listen(&sarif.NetConfig{
		Address: "tcp://localhost:5698",
		Auth:    sarif.AuthNone,
	})
	time.Sleep(10 * time.Millisecond)

	// Setup client and listen for "testaction"
	client := sarif.NewClient("mytestdevice")
	err := client.Dial(&sarif.NetConfig{
		Address: "tcp://localhost:5698",
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	client.Subscribe("testaction", "", func(msg sarif.Message) {
		fmt.Printf("received %q from %q\n", msg.Action, msg.Source)

		var payload MyPayload
		msg.DecodePayload(&payload)
		fmt.Println("payload:", payload.Value)
		recv <- true
	})

	// Publish a "testaction" message
	client.Publish(sarif.CreateMessage("testaction", MyPayload{"weee, a test message!"}))

	// Block until message received or timeout
	select {
	case <-recv:
	case <-time.After(time.Second):
	}

	// Output:
	// received "testaction" from "mytestdevice"
	// payload: weee, a test message!
}
Beispiel #3
0
func (s *Server) InitBroker() error {
	if s.Broker != nil {
		return nil
	}

	sarif.SetDefaultLogger(s.Log)
	s.Broker = sarif.NewBroker()
	if s.Log.GetLevel() <= core.LogLevelTrace {
		s.Broker.TraceMessages(true)
	}

	s.Client = sarif.NewClient(s.ServerConfig.Name + "/sarifd")
	s.Client.Connect(s.Broker.NewLocalConn())
	s.Client.SetLogger(s.Log)

	cfg := &s.ServerConfig
	if _, ok := s.Config.Get("server", cfg); !ok {
		if len(cfg.Listen) == 0 {
			cfg.Listen = append(cfg.Listen, &sarif.NetConfig{
				Address: "tcp://localhost:23100",
				Auth:    sarif.AuthNone,
			})
			s.Config.Set("server", cfg)
		}
	}

	// Listen on connections
	for _, cfg := range cfg.Listen {
		go func(cfg *sarif.NetConfig) {
			s.Log.Infoln("[server] listening on", cfg.Address)
			s.Must(s.Broker.Listen(cfg))
		}(cfg)
	}

	// Setup bridges
	for _, cfg := range cfg.Bridges {
		go func(cfg *sarif.NetConfig) {
			for {
				s.Log.Infoln("[server] bridging to ", cfg.Address)
				conn, err := sarif.Dial(cfg)
				if err == nil {
					err = s.Broker.ListenOnBridge(conn)
				}
				s.Log.Errorln("[server] bridge error:", err)
				time.Sleep(5 * time.Second)
			}
		}(cfg)
	}

	// Setup gateways
	for _, cfg := range cfg.Gateways {
		go func(cfg *sarif.NetConfig) {
			for {
				s.Log.Infoln("[server] gateway to ", cfg.Address)
				conn, err := sarif.Dial(cfg)
				if err == nil {
					err = s.Broker.ListenOnGateway(conn)
				}
				s.Log.Errorln("[server] gateway error:", err)
				time.Sleep(5 * time.Second)
			}
		}(cfg)
	}

	return nil
}