func mainEasyTest() {
	c := conf.TestConf()

	dcr, err := rest.DeviceCmdPoll(c.URL, c.DeviceID, c.AccessKey, nil, nil, nil)

	if err != nil {
		say.Infof("Error: %s", err.Error())
	} else {
		say.Infof("Ok: %+v", dcr)
	}
}
func main() {
	say.Level = say.DEBUG
	say.Infof("POLLING COMMANDS TEST. Send command from another terminal")

	mainInfinityLoop()
	//Choose another main function
}
Beispiel #3
0
func (c *Conn) SendCommand(command map[string]interface{}) {
	c.lastCommandId++
	requestId := c.lastCommandId
	command["requestId"] = requestId

	r := make(chan bool, 1)
	c.queueLock.Lock()
	c.queue[requestId] = func(res map[string]interface{}) {
		r <- true
	}
	c.queueLock.Unlock()

	c.postCommand(command)

	select {
	case <-time.After(CommandResponseTimeout * time.Second):

		c.queueLock.Lock()
		delete(c.queue, requestId)
		c.queueLock.Unlock()

		say.Infof("Timed out waiting for response to command: %+v", command)

	case <-r:
	}
}
func main() {
	say.Level = say.DEBUG
	say.Infof("POLLING NOTIFICATIONS TEST. Send notification from another terminal")

	mainInfinityLoop()
	//Choose another main function
}
func DeviceNotificationPollAsync(
	deviceHiveURL, deviceGuid, accessKey string,
	out chan DeviceNotificationResource, control PollAsync, // cannot be nil
) {
	tr := &http.Transport{}
	client := &http.Client{Transport: tr}

	requestOut := make(chan *http.Request, 1)
	local := make(chan []DeviceNotificationResource, 1)
	isStopped := make(chan struct{})
	for {
		go func() {
			for {

				dnrs, err := DeviceNotificationPoll(deviceHiveURL, deviceGuid, accessKey, nil, client, requestOut)
				select {
				case <-requestOut:
				default:
				}

				select {
				case <-isStopped:
					return
				default:
				}

				if err != nil {
					say.Infof("Polling notifications error: %s", err.Error())
					time.Sleep(time.Second)
					continue
				}

				if len(dnrs) == 0 {
					continue
				}

				local <- dnrs
				break
			}
		}()

		select {
		case dnrs := <-local:
			for _, dnr := range dnrs {
				out <- dnr
			}
			continue
		case <-control:
			select {
			case req := <-requestOut:
				isStopped <- struct{}{}
				tr.CancelRequest(req)
				return
			default:
			}
		}
	}
}
func main() {
	say.Level = say.DEBUG

	f, c, err := conf.FromArgs()
	if err != nil {
		say.Infof("Load conf err: %s", err.Error())
		return
	}

	say.Infof("Conf(%s): %+v", f, c)

	err = rest.DeviceRegisterEasy(c.URL, c.DeviceID, c.AccessKey, c.DeviceName)

	if err != nil {
		say.Infof("Error: %s", err.Error())
	} else {
		say.Infof("Ok")
	}
}
func mainInfinityLoopWithInterruption() {
	c := conf.TestConf()

	control := rest.NewPollAsync()
	out := make(chan rest.DeviceCmdResource, 16)

	go rest.DeviceCmdPollAsync(c.URL, c.DeviceID, c.AccessKey, out, control)

	for {
		select {
		case item := <-out:
			say.Infof("item: %+v", item)
		case <-time.After(15 * time.Second):
			say.Infof("start Stop()")
			control.Stop()
			say.Infof("finish Stop()")
			return
		}
	}
}
func main() {
	name := "TestRestNotification"
	parameters := map[string]interface{}{"key1": "value1"}

	f, c, err := conf.FromArgs()
	if err != nil {
		say.Infof("Load conf err: %s", err.Error())
		return
	}

	say.Infof("Conf(%s): %+v", f, c)

	dnir, err := rest.DeviceNotificationInsert(c.URL, c.DeviceID, c.AccessKey, name, parameters)

	if err != nil {
		say.Infof("Error: %s", err.Error())
	} else {
		say.Infof("Ok: %+v", dnir)
	}
}
func main() {
	var id uint32 = 782346
	status := "UpdateCommandTestStatus"
	result := "UpdateCommandTestResult"

	f, c, err := conf.FromArgs()
	if err != nil {
		say.Infof("Load conf err: %s", err.Error())
		return
	}

	say.Infof("Conf(%s): %+v", f, c)

	err = rest.DeviceCmdUpdate(c.URL, c.DeviceID, c.AccessKey, id, status, result)

	if err != nil {
		say.Infof("Error: %s", err.Error())
	} else {
		say.Infof("ok")
	}
}
func mainInfinityLoop() {
	c := conf.TestConf()

	control := rest.NewPollAsync()
	out := make(chan rest.DeviceCmdResource, 16)

	go rest.DeviceCmdPollAsync(c.URL, c.DeviceID, c.AccessKey, out, control)

	for {
		select {
		case item := <-out:
			say.Infof("item: %+v", item)
		}
	}
}
func DeviceRegisterEasy(deviceHiveURL, deviceGuid, accessKey, deviceName, deviceKey, networkName, networkKey, networkDesc string) (err error) {
	api := gopencils.Api(deviceHiveURL)

	resource := api.Res("device").Id(deviceGuid)
	resource.SetHeader("Authorization", "Bearer "+accessKey)

	// device class
	dc := map[string]interface{}{
		"name":           "go-gateway-class",
		"version":        "0.1",
		"offlineTimeout": 10}

	// network (optional)
	n := map[string]interface{}{
		"name":        networkName,
		"key":         networkKey,
		"description": networkDesc}

	// device
	d := map[string]interface{}{
		// [optional] "key":    deviceKey,
		"name":        deviceName,
		"status":      "Online",
		"deviceClass": dc}

	// omit "network" if all fields are empty
	if len(networkName) != 0 || len(networkKey) != 0 || len(networkDesc) != 0 {
		d["network"] = n
	}

	// omit device key if empty
	if len(deviceKey) != 0 {
		d["key"] = deviceKey
	}

	resp, err2 := resource.Put(d)
	say.Infof("DeviceRegisterEasy Response: %+v \r\n %+v", resp, resp.Raw)

	if err2 == nil {
		err = resource.ProcessedError()
	}
	return
}
func main() {
	say.SetLevelWithConfName("info")

	configFile, config, err := conf.FromArgs()
	switch {
	case err != nil:
		say.Fatalf("Cannot read configuration in `%s` with error: %s", configFile, err.Error())
	case configFile == "":
		say.Infof("You should specify configuration file. Starting with test configuration: %+v", config)
	default:
		say.Infof("Starting DeviceHive gateway with configuration in '%s': %+v", configFile, config)
	}

	say.SetLevelWithConfName(config.LoggingLevel)

	bus, err := dbus.SystemBus()
	if err != nil {
		say.Infof("Cannot get system bus with error: %s", err.Error())
		say.Infof("Trying to use session bus for testing purposes...")
		if bus, err = dbus.SessionBus(); err != nil {
			say.Fatalf("Cannot get session bus with error: %s\n", err.Error())
			return
		}
	}

	reply, err := bus.RequestName(DBusConnName, dbus.NameFlagDoNotQueue)
	switch {
	case err != nil:
		say.Fatalf("Cannot request name '%s' with error: %s\n", DBusConnName, err.Error())
	case reply != dbus.RequestNameReplyPrimaryOwner:
		say.Fatalf("The name '%s' already taken.", DBusConnName)
	}

	if config.DeviceNotificationReceive == conf.DeviceNotificationReceiveByWS {
		say.Infof("Starting as websocket...")
		wsImplementation(bus, config)
		return
	}

	if config.DeviceNotificationReceive == conf.DeviceNotificationReceiveByREST {
		say.Infof("Starting as rest...")
		restImplementation(bus, config)
		return
	}

}
Beispiel #13
0
func (c *Conn) runInternal(accessKey string, init func()) error {
	origin := "http://localhost/"
	url := c.WebSocketURL() + "/device"

	say.Verbosef("Connecting using WS to %s", url)

	ws, _, err := websocket.DefaultDialer.Dial(url,
		http.Header{"Origin": []string{origin},
			"Authorization": []string{"Bearer " + accessKey}})
	if err != nil {
		say.Infof("Dial error: %s", err.Error())
		return err
	}

	c.ws = ws

	go func() {
		for m := range c.senderQ.Out() {
			say.Verbosef("THROTTLING: Message has been received from priotiorized chan: %+v", m)
			c.SendCommand(m)
		}
	}()

	go c.writePump()
	go func() {
		for {
			m := <-c.receive
			go c.handleMessage(m)
		}
	}()

	go init()

	c.readPump()
	return nil
}
Beispiel #14
0
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 {}

}
Beispiel #15
0
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 {}
}