Skip to content

Create Thing

DravenK edited this page Aug 16, 2020 · 1 revision

Create Thing:

// Create a Lamp.
thing := webthing.NewThing("urn:dev:ops:my-thing-1234",
	"Lamp",
	[]string{"OnOffSwitch", "Light"},
	"A web connected thing")

Before creating OnOffProperty you need to create the Forwarder method of OnOff Value. The method that updates the actual value on the thing Example:

func onValueForwarder(i interface{}) {
    fmt.Println("Now on statue: ", i)
}

Create an onValue with default value:

onValue := webthing.NewValue(true, onValueForwarder)
// Adding an OnOffProperty to thing.
onDescription := []byte(`{
    "@type": "OnOffProperty",
    "type": "boolean",
    "title": "On/Off",
    "description": "Whether the lamp is turned on"
    }`)
onValue := webthing.NewValue(true, onValueForwarder)
on := webthing.NewProperty(thing,
	"on",
	onValue,
	onDescription)
thing.AddProperty(on)

Create an action. The methods you have to implement are:

// Customize Action needs to create a Generator to generate an action.
// The application will invoke the Action created by the Generator method.
// This is very similar to simply constructor.
// See thing.PerformAction()*Action
Generator(thing *Thing) *Action

// Override this with the code necessary to perform the action.
PerformAction() *Action

// Override this with the code necessary to cancel the action.
Cancel()

The Action Request can be used to retrieve input data in the following way like the fade.Thing().Input(). Here is an example:

type FadeAction struct {
	*webthing.Action
}

func (fade *FadeAction) Generator(thing *webthing.Thing) *webthing.Action {
	fade.Action = webthing.NewAction(uuid.New().String(), thing, "fade", nil, fade.PerformAction, fade.Cancel)
	return fade.Action
}

func (fade *FadeAction) PerformAction() *webthing.Action {
	thing := fade.Thing()
	params, _ := fade.Input().MarshalJSON()

	input := make(map[string]interface{})
	if err := json.Unmarshal(params, &input); err != nil {
		fmt.Println(err)
	}
	if brightness, ok := input["brightness"]; ok {
		thing.Property("brightness").Set(brightness)
	}
	if duration, ok := input["duration"]; ok {
		time.Sleep(time.Duration(int64(duration.(float64))) * time.Millisecond)
	}
	return fade.Action
}

func (fade *FadeAction) Cancel() {}

You can find an example of creating Thing above in single-thing. You can find more Examples in the Examples directory

Clone this wiki locally