當前位置: 首頁>>代碼示例>>Golang>>正文


Golang backend.Backend類代碼示例

本文整理匯總了Golang中home/core/backend.Backend的典型用法代碼示例。如果您正苦於以下問題:Golang Backend類的具體用法?Golang Backend怎麽用?Golang Backend使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Backend類的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: initOpenWeatherMapBackend

func initOpenWeatherMapBackend(config map[string]interface{}, back *backend.Backend) error {

	apiKey, ok := utils.GetString("api_key", config, "")
	if !ok {
		logrus.Warnf("Backend: %s configuration option missing: 'apiKey'", back.Name())
		return nil // CHANGE
	}

	weather := weatherTracker{}

	weather.unit, _ = utils.GetString("unit", config, "C")
	language, _ := utils.GetString("language", config, "DE")
	weather.delay, _ = utils.GetInt("delay", config, 60)

	w, err := owm.NewCurrent(weather.unit, language, apiKey)
	if err != nil {
		logrus.Warnf("Backend: %s failed to update state", back.Name())
	}
	weather.current = w

	back.RegisterComponent <- &backend.Component{
		Internal:  &weather,
		Name:      "weather",
		Polling:   updateWeather,
		Type:      backend.WeatherTracker,
		StateSink: make(chan interface{}),
	}

	return nil
}
開發者ID:nethack42,項目名稱:go-home,代碼行數:30,代碼來源:openweathermap.go

示例2: initExampleBackend

func initExampleBackend(config map[string]interface{}, back *backend.Backend) error {
	// config represents the backend configuration passed to GoHome. Thus,
	// the `name` (if set) and `typ` fields are still present within the map.
	logrus.Infof("Started backend %s with name %s", config["type"].(string), back.Name())

	// Manipulate the backend structure as you like
	back.OnShutdown = shutdownExampleBackend

	// use the component registration channel to register new components
	// here a simple boolen "sensor" is created which value will toggle every
	// few seconds
	comp := &backend.Component{
		StateSink: make(chan interface{}),
		Name:      "example",
		Polling:   updateExampleComponent,
		Internal:  true,
	}
	back.RegisterComponent <- comp

	return nil
}
開發者ID:nethack42,項目名稱:go-home,代碼行數:21,代碼來源:example.go

示例3: LocalScriptBackend

/*
LocalScriptBackend provides the possibility to execute local scripts while
publishing their results on the internal eventbus. Scripts can either be
registered as components/sensors or as services. In the first case scripts are
polled in a regular interval. The latter one enables the script to be called
vie Service Call requests.

In order to use this backend add something like the following to your
configuration:

 backends:
  - type: script
	  scripts:
		 - exec: /path/to/script
		   name: MyPrettyName
		   #type: sensor (default)
		 - exec: /path/to/other/script
		 	 name: my_pretty_name_2
			 type: service

Service scripts can latter be called by sending a Service Call request to
`script.MyPrettyName`. Note that `script` may differ if a `name` field is
specified within the backend configuration.

The result of script executions is published as a string within state_changed
events.

*/
func LocalScriptBackend(config map[string]interface{}, back *backend.Backend) error {
	var scripts []interface{}
	services := make(map[string]command)

	switch a := config["scripts"].(type) {
	case []interface{}:
		scripts = a
	default:
		logrus.Warnf("Backend: %s invalid configuration: %#v", back.Name(), config)
		return nil // CHANGE ME
	}

	for _, s := range scripts {
		script, ok := s.(map[string]interface{})
		if !ok {
			logrus.Warnf("Backend: %s script with invalid configuration: %#v", back.Name(), script)
			continue
		}
		exec, ok := script["exec"].(string)
		if !ok {
			logrus.Warnf("Backend: %s script configuration without `exec`: %s", back.Name(), script)
			continue
		}
		name, ok := script["name"].(string)
		if !ok {
			name = exec
		}
		execType, ok := script["type"].(string)
		if !ok {
			execType = "sensor"
		}
		cmd := command{
			command: exec,
		}

		comp := &backend.Component{
			StateSink: make(chan interface{}),
			Name:      name,
			Polling:   updateScriptResult,
			Internal:  cmd,
		}
		switch execType {
		case "sensor":
			back.RegisterComponent <- comp
		case "service":
			service.ServiceRegistry.Register(back, comp.Name, "Call local script",
				cmd.execute, map[string]string{}, map[string]string{})
		}
	}

	back.Internal = services

	return nil
}
開發者ID:nethack42,項目名稱:go-home,代碼行數:82,代碼來源:script.go

示例4: NotifyMyAndroidBackend

func NotifyMyAndroidBackend(config map[string]interface{}, back *backend.Backend) error {
	apiKey, ok := utils.GetString("api_key", config, "")
	if !ok {
		return fmt.Errorf("Backend: %s missing configuration option 'api_key'", back.Name())
	}

	comp := &notifyMyAndroid{
		nma:     nma.New(apiKey),
		backend: back,
	}
	back.Internal = comp

	service.ServiceRegistry.Register(back, "notify", "Send a notification via Notify-My-Android",
		comp.Notify, map[string]string{
			"subject": "Subject of the notification",
			"message": "Message part of the notification",
		},
		map[string]string{
			"priority": "Priority of the notification. Defaults to 0",
		})

	return nil
}
開發者ID:nethack42,項目名稱:go-home,代碼行數:23,代碼來源:nma.go

示例5: WebsocketConnectorBackend

/*
Backend providing a JSON based component connector via Websockets.

Configuration

In order to use this websocket based connector add something like the following
to your configuration file:

 backends:
  - type: websocket
    listen: httpapi


Description

The `listen` parameter may specifiy an endpoint the websocket server should
be bound to (e.g. localhost:8080, 0.0.0.0:6600, :9000). As a special case,
"httpapi" can be specified. If so, the websocket connector backend attaches it
self the the HTTP API plugin and will therefore share it's HTTP server. In the
latter case the access URI will be "/devices" instead of "/".


API Description

First a Websocket connection must be established. During this HTTP request,
the device name and type must be provided. Consider the following Websocket URL:

  ws://example.com/device?name=<YourDeviceName>&type=<YourDeviceType>

If this module is not used in conjunction with the HTTP API plugin the request
URL should look like:

	ws://example.com/?name=<YourDeviceName>&type=<YourDeviceType>

If both parameters are provided a websocket connection can be initialized.

Now the client can start providing data by sending JSON messages following this
format:

  {
	   "topic": "state_changed",
		 "state": <YourStateOfWhatsOEver>
  }

Everything provided in `state` will be published on the internal eventbus and
thus be available for all subscribers.

Note that a WebSocket component can only send state updates and register service
calles. It is prohibited to execute other services or send other topics then
"state_changed" and "register_service".

Invalid messages will be logged and the respective connection will be closed.

In order to register new service calles within GoHome a Websocket component could
send a service registration request with the following format:

 {
   "topic": "register_service",
   "name": "<NameOfYourService>",
   "required": {
   "param1": "This is the first and only parameter required"
  },
  "optional" {
   "param2": "This is an optional parameter which defaults to: some-value"
  }
 }

The `name`, `required` and `optional` fields are required to be set during
service registration. However, `required` and `optional` may be an empty
map/object.

Whenever a service should be executed GoHome send the following request via the
Websocket connection:

{
	"topic": "service_call",
	"method": "<NameOfYourService>",
	"params": [<ListOfParameters]
}

BUG: Currently it is NOT possible for Websocket components to return a response
to the caller! All service call will immediately return nil.

*/
func WebsocketConnectorBackend(config map[string]interface{}, back *backend.Backend) error {
	logrus.Infof("Started backend %s with name %s", config["type"].(string), back.Name())

	listen, _ := utils.GetString("listen", config, "httpapi")

	back.OnShutdown = shutdownWebsockets
	back.Internal = &websocketServer{
		clients: make(map[string]peer),
		name:    back.Name(),
		back:    back,
	}

	if listen == "httpapi" {
		logrus.Infof("Backend: %s: attaching to default HTTP server (httpapi) on URI /device", back.Name())
		http.Handle("/device", back.Internal.(*websocketServer))
	} else {
//.........這裏部分代碼省略.........
開發者ID:nethack42,項目名稱:go-home,代碼行數:101,代碼來源:websocket.go

示例6: shutdownWebsockets

func shutdownWebsockets(back *backend.Backend) error {
	logrus.Infof("Shutting down backend %s", back.Name())
	// Currently we cannot gracefully shutdown the HTTP server ...
	return nil
}
開發者ID:nethack42,項目名稱:go-home,代碼行數:5,代碼來源:websocket.go

示例7: shutdownExampleBackend

func shutdownExampleBackend(back *backend.Backend) error {
	logrus.Infof("Shutting down backend %s", back.Name())
	return nil
}
開發者ID:nethack42,項目名稱:go-home,代碼行數:4,代碼來源:example.go

示例8: MediaPlayerDaemonBackend

/*
This backend let GoHome connect to an MPD server and retrieve information about
it's current status as well as perform some basic operations like play/pause.

In order to use this backend add something like the following to your configuration:

 backends:
  - type: mpd
	  endpoint: 192.168.0.10:6600

Data within state changes published on the eventbus will have the following
format:
 {
  "TOBEDONE": "TOBEDONE"
 }

In addition, the following service calls are exported

  <mpd-name>.play()
	<mpd-nam>.pause()


*/
func MediaPlayerDaemonBackend(config map[string]interface{}, back *backend.Backend) error {
	url, ok := utils.GetString("endpoint", config, "localhost:6600")
	if !ok {
		logrus.Warn("Backend: %s missing configuration option 'endpoint'. assuming 'localhost:6600'", back.Name())
	}

	intern := mpdClientComponent{
		url:       url,
		connected: false,
	}

	comp := &backend.Component{
		Name:      "mpd",
		Internal:  &intern,
		StateSink: make(chan interface{}),
		Polling:   updateMPD,
	}
	back.RegisterComponent <- comp

	service.ServiceRegistry.Register(comp, "pause", "Pause MPD playback", intern.pause,
		map[string]string{}, map[string]string{})
	service.ServiceRegistry.Register(comp, "play", "Resume MPD playback", intern.play,
		map[string]string{}, map[string]string{})

	go (&intern).connect()
	return nil
}
開發者ID:nethack42,項目名稱:go-home,代碼行數:50,代碼來源:mpd.go


注:本文中的home/core/backend.Backend類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。