td

package
v0.0.0-...-809ad04 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 9, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package td with API interface definitions for the ExposedThing and ConsumedThing classes

Package td with Schema type definitions for the ExposedThing and ConsumedThing classes as described here: https://www.w3.org/TR/wot-thing-description/#sec-data-schema-vocabulary-definition

Package things with API interface definitions for the ExposedThing and ConsumedThing classes

Package td with API interface definitions for forms

Package things with API interface definitions for the ExposedThing and ConsumedThing classes

Package td with WoT TD vocabulary

Index

Constants

View Source
const (
	SecSchemeApiKey string = "apikey"
	SecSchemeAuto   string = "auto"
	SecSchemeBasic  string = "basic"
	SecSchemeBearer string = "bearer"
	SecSchemeDigest string = "digest"
	SecSchemePSK    string = "psk"
	SecSchemeNoSec  string = "nosec"
	SecSchemeOAuth2 string = "oauth2"
)

https://www.w3.org/TR/wot-thing-description11/#securityscheme

View Source
const (
	HTOpPing              = "ping"
	HTOpLogout            = "logout"
	HTOpObserveAction     = "observeaction"
	HTOpObserveAllActions = "observeallactions"
	HTOpReadEvent         = "readevent"
	HTOpReadAllEvents     = "readallevents"
)

HiveOT operations that are not defined with the TD and used in HiveOT.

View Source
const (
	// actions
	OpCancelAction    = "cancelaction"
	OpInvokeAction    = "invokeaction"
	OpQueryAction     = "queryaction"
	OpQueryAllActions = "queryallactions"
	// events
	OpSubscribeAllEvents   = "subscribeallevents"
	OpSubscribeEvent       = "subscribeevent"
	OpUnsubscribeAllEvents = "unsubscribeallevents"
	OpUnsubscribeEvent     = "unsubscribeevent"
	// properties
	OpObserveAllProperties        = "observeallproperties"
	OpObserveMultipleProperties   = "observemultipleproperties"
	OpObserveProperty             = "observeproperty"
	OpReadAllProperties           = "readallproperties"
	OpReadMultipleProperties      = "readmultipleproperties"
	OpReadProperty                = "readproperty"
	OpUnobserveAllProperties      = "unobserveallproperties"
	OpUnobserveMultipleProperties = "unobservemultipleproperties"
	OpUnobserveProperty           = "unobserveproperty"
	OpWriteMultipleProperties     = "writemultipleproperties"
	OpWriteProperty               = "writeproperty"
)

WoT TD1.1 operations

View Source
const (
	WoTDataType         = "type"
	DataTypeAnyURI      = "anyURI"
	DataTypeArray       = "array"
	DataTypeBool        = "boolean"
	DataTypeDateTime    = "dateTime"
	DataTypeInteger     = "integer"
	DataTypeNone        = ""
	DataTypeNumber      = "number"
	DataTypeObject      = "object"
	DataTypeString      = "string"
	DataTypeUnsignedInt = "unsignedInt"
)

WoT data types

View Source
const (
	WoTActions              = "actions"
	WoTDescription          = "description"
	WoTDescriptions         = "descriptions"
	WoTDigestSecurityScheme = "DigestSecurityScheme"
	WoTEnum                 = "enum"
	WoTEvents               = "events"
	WoTFormat               = "format"
	WoTForms                = "forms"
	WoTHref                 = "href"
	WoTID                   = "id"
	WoTInput                = "input"
	WoTLinks                = "links"
	WoTMaxItems             = "maxItems"
	WoTMaxLength            = "maxLength"
	WoTMaximum              = "maximum"
	WoTMinItems             = "minItems"
	WoTMinLength            = "minLength"
	WoTMinimum              = "minimum"
	WoTModified             = "modified"
	WoTNoSecurityScheme     = "NoSecurityScheme"
	WoTOAuth2SecurityScheme = "OAuth2SecurityScheme"
	WoTOperation            = "op"
	WoTProperties           = "properties"
	WoTReadOnly             = "readOnly"
	WoTRequired             = "required"
	WoTSecurity             = "security"
	WoTSupport              = "support"
	WoTTitle                = "title"
	WoTTitles               = "titles"
	WoTVersion              = "version"
)

TD-1.1 affordance and data schema vocabulary

View Source
const HiveOTContext = "https://www.hiveot.net/vocab/v0.1"
View Source
const WoTTDContext = "https://www.w3.org/2022/wot/td/v1.1"

Variables

This section is empty.

Functions

func ConvertToNative

func ConvertToNative(strVal string, dataSchema *DataSchema) (val any, err error)

ConvertToNative converts the string value to native type based on the given data schema this converts int, float, and boolean if the dataschema is an object or an array then strVal is assumed to be json encoded

func ForEachTD

func ForEachTD(tdDir string, handler func(sourceFile string, tdi *TD))

ForEachTD iterate the given TD folder and invokes the handler with the TD instance

func GetSourceFilesInDir

func GetSourceFilesInDir(sourceDir string) ([]string, error)

GetSourceFilesInDir return the list of .json source files in the given directory

func MarshalTD

func MarshalTD(tdi *TD) (tdJson string, err error)

UnmarshalTD unmarshals a JSON encoded TD

func SortThingsByID

func SortThingsByID(tds []*TD)

SortThingsByID as the name suggests sorts the things in the given slice

func SortThingsByTitle

func SortThingsByTitle(tds []*TD)

SortThingsByTitle as the name suggests sorts the things in the given slice

Types

type ActionAffordance

type ActionAffordance struct {

	// AtType is the JSON-LD @type keyword to classify the action using standard vocabulary, or nil if not known
	// Intended for grouping and querying similar actions, and standardized presentation such as icons
	AtType any `json:"@type,omitempty"`

	// Multiline description
	Comments []string `json:"comments,omitempty"`
	// Provides additional (human-readable) information based on a default language
	Description string `json:"description,omitempty"`
	// Provides additional nulti-language information
	Descriptions []string `json:"descriptions,omitempty"`

	// Form hypermedia controls to describe how an operation can be performed
	// Forms are serializations of Protocol Bindings.
	Forms []Form `json:"forms,omitempty"`

	// Provides a human-readable title in the default language
	Title string `json:"title,omitempty"`
	// Provides a multi-language human-readable titles
	Titles []string `json:"titles,omitempty"`
	// Define URI template variables according to [RFC6570] as collection based on DataSchema declarations.
	// HiveOT supports linking uri variable to input
	UriVariables map[string]DataSchema `json:"uriVariables,omitempty"`
	// If this is a dataschema of a URIvariable, then:
	//  Hiveot:input links this as a URI variable schema to the affordance input
	//  If empty or '.', the matching URI variable will be pass as the default input
	//  Otherwise the content is a field name in the input dataschema.
	HiveotInput string `json:"hiveot:input,omitempty"`

	// Indicate whether the action is idempotent, eg repeated calls have the
	// same result.
	Idempotent bool `json:"idempotent,omitempty" default:"false"`

	// Define the input data Schema of the action or nil if the action doesn't take input data
	Input *DataSchema `json:"input,omitempty"`

	// Defines the output data Schema of the action or nil if the action doesn't have outputs
	Output *DataSchema `json:"output,omitempty"`

	// Signals if the Action is state safe or not.
	// Safe actions do not change the internal state of a resource.
	// Unsafe action are likely to affect one or more properties or emit events.
	Safe bool `json:"safe,omitempty" default:"false"`

	// A synchronous action means that the response of action contains all the information
	// about the result of the action and no further querying about the status of the action
	// is needed.
	// Lack of this keyword means that no claim on the synchronicity of the action
	// can be made.
	Synchronous bool `json:"synchronous,omitempty"`
}

ActionAffordance metadata that defines how to invoke a function of a Thing to manipulate its state, eg toggle lamp on/off or trigger a process

func (*ActionAffordance) AddForm

func (aff *ActionAffordance) AddForm(form Form)

AddForm adds an interaction form to the action affordance this is not thread-safe.

func (*ActionAffordance) GetAtTypeString

func (aff *ActionAffordance) GetAtTypeString() string

GetAtTypeString returns the @type field from the affordance as a single string. If @type is an array then the first item is returned.

func (*ActionAffordance) GetStateful

func (aff *ActionAffordance) GetStateful() string

Return 'yes'/no if the action is stateful (unsafe)

func (*ActionAffordance) SetAtType

func (aff *ActionAffordance) SetAtType(vocabType string) *ActionAffordance

SetAtType sets the event @type field from the HT vocabulary

type CredLoc

type CredLoc string

Location of credentials in securityScheme

const (
	CredLocHeader CredLoc = "header"
	CredLocQuery  CredLoc = "query"
	CredLocBody   CredLoc = "body"
	CredLocCookie CredLoc = "cookie"
	CredLocAuto   CredLoc = "auto"
)

type DataSchema

type DataSchema struct {
	// JSON-LD keyword to classify the object with semantic tags, if any
	// Intended for grouping and querying similar data, and standardized presentation such as icons
	// For properties this would be the property type, eg temperature, humidity, etc.
	// For action input this is the action parameter type
	// For event data this is the event payload type
	AtType any `json:"@type,omitempty"`
	// Provides a human-readable title in the default language
	Title string `json:"title,omitempty"`
	// Provides a multi-language human-readable titles
	Titles []string `json:"titles,omitempty"`
	// Provides additional (human-readable) information based on a default language
	// this can be a string or array for multi-line description.
	Description string `json:"description,omitempty"`
	// Provides additional nulti-language information
	Descriptions []string `json:"descriptions,omitempty"`

	// Optional comments for additional multi-line descriptions
	// Not part of the WoT spec as it doesn't support multi-line descriptions
	Comments []string `json:"comments,omitempty"`

	// Provides a constant value of any type as per data Schema
	Const any `json:"const,omitempty"`

	// Provides a default value of any type as per data Schema
	Default any `json:"default,omitempty"`

	// Restricted set of values provided as an array.
	//  for example: ["option1", "option2"]
	Enum []any `json:"enum,omitempty"`

	// Allows validation based on a format pattern such as "date-time", "email", "uri", etc.
	// See vocab DataFormXyz "date-time", "email", "uri" (todo)
	Format string `json:"format,omitempty"`

	// OneOf provides constraint of data as one of the given data schemas
	OneOf []DataSchema `json:"oneOf,omitempty"`

	// Boolean value to indicate whether a property interaction / value is read-only (=true) or not (=false)
	// the value true implies read-only.
	ReadOnly bool `json:"readOnly"`

	// Boolean value to indicate whether a property interaction / value is write-only (=true) or not (=false)
	// the value true implies writable but not readable. Intended for secrets such as passwords.
	WriteOnly bool `json:"writeOnly,omitempty"`

	// Type provides JSON based data type,  one of DataTypeNumber, ...object, array, string, integer, boolean or null
	Type string `json:"type,omitempty"`

	// Reference to an external data schema when type is object
	Schema string `json:"schema,omitempty"`

	// Unit as used in international science, engineering, and business.
	// See vocab UnitNameXyz for units in the vocabulary
	Unit string `json:"unit,omitempty"`

	// ArraySchema with metadata describing data of type Array.
	// https://www.w3.org/TR/wot-thing-description/#arrayschema
	// Used to define the characteristics of an array.
	// Note that in golang a field cannot both be a single or an array of items
	// Right now 'items' has to be a dataschema
	ArrayItems *DataSchema `json:"items,omitempty"`
	// Defines the minimum number of items that have to be in the array
	ArrayMinItems uint `json:"minItems,omitempty"`
	// Defines the maximum number of items that have to be in the array.
	ArrayMaxItems uint `json:"maxItems,omitempty"`

	// NumberSchema with metadata describing data of type number.
	// This Subclass is indicated by the value number assigned to type in DataSchema instances.
	// Maximum specifies a maximum numeric value representing an upper limit
	// FIXME: both number and integer schemas have a minimum and maximum field.
	// Different types of course. How to flatten ?
	Maximum float64 `json:"maximum,omitempty"`
	// Minimum specifies a minimum numeric value representing a lower limit
	Minimum float64 `json:"minimum,omitempty"`

	// ObjectSchema with metadata describing data of type Object.
	// This Subclass is indicated by the value object assigned to type in DataSchema instances.
	// Properties of Object.
	Properties map[string]*DataSchema `json:"properties,omitempty"`
	// Defines which members of the object type are mandatory
	Required []string `json:"required,omitempty"`
	// object schema is a map with the data type defined in AdditionalProperties
	// this datatype can be a dataschema or a $ref string
	AdditionalProperties map[string]any `json:"additionalProperties,omitempty"`

	// StringSchema with metadata describing data of type string.
	// This Subclass is indicated by the value string assigned to type in DataSchema instances.
	// MaxLength specifies the maximum length of a string
	StringMaxLength uint `json:"maxLength,omitempty"`
	// MinLength specifies the minimum length of a string
	StringMinLength uint `json:"minLength,omitempty"`
	// Pattern provides a regular expression to express constraints.
	// The regular expression must follow the [ECMA-262] dialect.	optional
	StringPattern string `json:"pattern,omitempty"`
	// ContentEncoding specifies the encoding used to store the contents, as specified in RFC 2054.
	// e.g., 7bit, 8bit, binary, quoted-printable, or base64
	StringContentEncoding string `json:"contentEncoding,omitempty"`
	// ContentMediaType specifies the MIME type of the contents of a string value, as described in RFC 2046.
	// e.g., image/png, or audio/mpeg)
	StringContentMediaType string `json:"contentMediaType,omitempty"`
}

DataSchema with metadata that describes the data format used. It can be used for validation.

Golang doesn't support dynamic types or subclasses, so DataSchema merges all possible schemas including string, number, integer, object, array,...

based on https://www.w3.org/TR/wot-thing-description/#dataschema

func NoSchema

func NoSchema() *DataSchema

func (*DataSchema) GetAtTypeString

func (ds *DataSchema) GetAtTypeString() string

GetAtTypeString returns the @type field as a string. If @type contains an array, the first element is returned.

func (*DataSchema) IsNative

func (ds *DataSchema) IsNative() bool

IsNative returns true if the type is string, number, boolean If type is an object or array this returns false Intended for use in input forms

func (*DataSchema) SetEnumAsStrings

func (ds *DataSchema) SetEnumAsStrings(e []string)

SetEnumAsStrings sets the enum values as type string. This is one of the most common use of enums so warrants its own type method.

type ErrInvalidTD

type ErrInvalidTD struct {
	// contains filtered or unexported fields
}

type EventAffordance

type EventAffordance struct {

	// AtType is the JSON-LD @type keyword to classify the action using standard vocabulary, or nil if not known
	// Intended for grouping and querying similar actions, and standardized presentation such as icons
	AtType any `json:"@type,omitempty"`

	// Multiline description
	Comments []string `json:"comments,omitempty"`
	// Provides additional (human-readable) information based on a default language
	Description string `json:"description,omitempty"`
	// Provides additional nulti-language information
	Descriptions []string `json:"descriptions,omitempty"`

	// Form hypermedia controls to describe how an operation can be performed
	// Forms are serializations of Protocol Bindings.
	Forms []Form `json:"forms,omitempty"`

	// Provides a human-readable title in the default language
	Title string `json:"title,omitempty"`
	// Provides a multi-language human-readable titles
	Titles []string `json:"titles,omitempty"`
	// Define URI template variables according to [RFC6570] as collection based on DataSchema declarations.
	// ... right
	UriVariables map[string]DataSchema `json:"uriVariables,omitempty"`

	// Data Schema of the event payload, if any. nil if the event comes without data
	Data *DataSchema `json:"data,omitempty"`
}

EventAffordance with metadata that describes an event source

func (*EventAffordance) AddForm

func (aff *EventAffordance) AddForm(form Form)

AddForm adds an interaction form to the event affordance this is not thread-safe.

func (*EventAffordance) GetAtTypeString

func (aff *EventAffordance) GetAtTypeString() string

GetAtTypeString returns the @type field from the affordance as a single string. If @type is an array then the first item is returned.

func (*EventAffordance) SetAtType

func (aff *EventAffordance) SetAtType(atType string) *EventAffordance

SetAtType sets the event @type field from the HT vocabulary

type Form

type Form map[string]any

Form can be viewed as a statement of "To perform an operation type operation on form context, make a request method request to submission target" where the optional form fields may further describe the required request. In Thing Descriptions, the form context is the surrounding Object, such as Properties, Actions, and Events or the Thing itself for meta-interactions.

func NewForm

func NewForm(operation string, href string, args ...string) Form

NewForm creates a new form instance

operation is required
href can be a relative path is base is set.

args is an optional sub-protocol as the third parameter

func (Form) GetHRef

func (f Form) GetHRef() (href string)

GetHRef returns the form's href field Since hrefs are mandatory, this returns an empty string if not present

func (Form) GetMethodName

func (f Form) GetMethodName() (method string, found bool)

GetMethodName returns the form's HTTP "htv:methodName" field

func (Form) GetOperation

func (f Form) GetOperation() string

GetOperation returns the first of a form's operation

func (Form) GetOperations

func (f Form) GetOperations() []string

GetOperations returns the list of form's operations or nil if the form has no operations The form operation can be stored as a single string, or an array of strings

func (Form) GetSubprotocol

func (f Form) GetSubprotocol() (subp string, found bool)

GetSubprotocol returns the form's subprotoco field

func (Form) SetMethodName

func (f Form) SetMethodName(method string) Form

SetMethodName sets the form's HTTP "htv:methodName" field

func (Form) SetSubprotocol

func (f Form) SetSubprotocol(subp string) Form

SetSubprotocol sets the form's subprotocol field

type PropertyAffordance

type PropertyAffordance struct {
	DataSchema

	// This property contains a sensor value. This is not a WoT attribute.
	IsSensor bool `json:"isSensor,omitempty"`

	// This property contains an actuator state. This is not a WoT attribute.
	IsActuator bool `json:"isActuator,omitempty"`

	// Form hypermedia controls to describe how an operation can be performed
	// Forms are serializations of Protocol Bindings. Don't omit if empty as forms are mandatory.
	Forms []Form `json:"forms"`

	// Define URI template variables according to [RFC6570] as collection based on DataSchema declarations.
	// ... right
	UriVariables map[string]DataSchema `json:"uriVariables,omitempty"`

	// Optional nested properties. Map with PropertyAffordance
	Properties map[string]PropertyAffordance `json:"properties,omitempty"`
}

PropertyAffordance metadata that defines Thing properties This is a Subclass of the InteractionAffordance Class and the DataSchema Class. Note: https://github.com/w3c/wot-thing-description/issues/1390 The spec simply cannot be implemented in golang without dynamic types. PropertyAffordance must be able to have a Schema based on the type, not just DataSchema, as a property can be any of the types integer, boolean, object, array, number...

func (*PropertyAffordance) AddForm

func (aff *PropertyAffordance) AddForm(form Form)

AddForm adds an interaction form to the property affordance this is not thread-safe.

func (*PropertyAffordance) SetAtType

func (aff *PropertyAffordance) SetAtType(atType string) *PropertyAffordance

SetAtType sets the property @type field from the HT vocabulary

type SecurityScheme

type SecurityScheme struct {
	// JSON-LD keyword to label the object with semantic tags (or types).
	AtType []string `json:"@type,omitempty"`

	// Provides additional (human-readable) information based on a default language
	Description string `json:"description,omitempty"`

	// Can be used to support (human-readable) information in different languages. Also see MultiLanguage.
	Descriptions []string `json:"descriptions,omitempty"`

	// URI of the proxy server this security configuration provides access to.
	// If not given, the corresponding security configuration is for the endpoint.
	Proxy string `json:"proxy,omitempty"`

	// Identification of the security mechanism being configured.
	// See also SecSchemeXyz above.
	Scheme string `json:"scheme"`

	//--- fields for bearer schema
	// URI of the authorization server
	// Used in Bearer Schema
	Authorization string `json:"authorization,omitempty"`

	// Name for query, header, cookie or uri parameters
	// Used in Bearer Schema
	Name string `json:"name,omitempty"`

	// Encoding, encryption, or digest algorithm
	// eg: ES256, ES512-256
	// Used in Bearer Schema
	Alg string `json:"alg,omitempty"`

	// Specifies format of security authentication information
	// e.g.: jwt, cwt, jwe, jws
	// Used in Bearer Schema
	Format string `json:"format,omitempty"`

	// Specifies the location of security authentication information.
	// one of: header, query, body, cookie or auto
	In CredLoc `json:"in,omitempty"`
}

SecurityScheme

type TD

type TD struct {
	// All action-based interaction affordances of the things
	Actions map[string]*ActionAffordance `json:"actions"`

	// AgentID is a hiveot extension containing the clientID of the agent that provided this TD
	// Intended for supporting reverse connections instead of forms.
	// FIXME: this field is tentative for use in the digitwin. If possible try to remove this dependency.
	AgentID string `json:"hiveot:agentID,omitempty"`

	// JSON-LD keyword to define shorthand names called terms that are used throughout a TD document. Required.
	// in order to add the "hiveot" namespace, the context value can be a string or map
	// Type: anyURO or Array
	AtContext []any `json:"@context"`

	// JSON-LD keyword to label the object with semantic tags (or types).
	// in HiveOT this contains the device type defined in the vocabulary.
	// Intended for grouping and querying similar devices, and standardized presentation such as icons
	AtType any `json:"@type,omitempty"`

	// Base: The base URI that is used for all relative URI references throughout a TD document.
	Base string `json:"base,omitempty"`

	// ISO8601 timestamp this document was first created. See also 'Modified'.
	Created string `json:"created,omitempty"`

	// Describe the device in the default human-readable language.
	// It is recommended to use the product description.
	Description string `json:"description,omitempty"`
	// Provides additional nulti-language information
	Descriptions []string `json:"descriptions,omitempty"`

	// All event-based interaction affordances of the things
	Events map[string]*EventAffordance `json:"events"`

	// Form hypermedia controls to describe how an operation can be performed. Forms are serializations of
	// Protocol Bindings. Thing-level forms are used to describe endpoints for a group of interaction affordances.
	Forms []Form `json:"forms,omitempty"`

	// ID is the Thing instance identifier.
	ID string `json:"id,omitempty"`

	// ISO8601 timestamp this document was last modified. See also 'Created'.
	Modified string `json:"modified,omitempty"`

	// Indicates the WoT Profile mechanisms followed by this Thing Description and
	// the corresponding Thing implementation.
	// Type: anyURI or Array of anyURI
	Profile any `json:"profile,omitempty"`

	// All properties-based interaction affordances of the things
	Properties map[string]*PropertyAffordance `json:"properties"`

	SchemaDefinitions map[string]DataSchema `json:"schemaDefinitions,omitempty"`

	// Security is a string or array of strings, chosen from those defined in securityDefinitions.
	// See also constants defined 'SecSchemeXyz'
	Security any `json:"security"`

	// Set of named security configurations (definitions only).
	// Not actually applied unless names are used in a security name-value pair. (why is this mandatory then?)
	SecurityDefinitions map[string]SecurityScheme `json:"securityDefinitions"`

	// Title is the name of the thing in human-readable in the default language. Required.
	// The same name is provided through the properties configuration, where it can be changed.
	// This allows to present the TD by its name without having to load its property values.
	Title string `json:"title"`
	// Human-readable titles in the different languages
	Titles map[string]string `json:"titles,omitempty"`

	// Provides information about the TD maintainer as URI scheme (e.g., mailto [RFC6068], tel [RFC3966], https [RFC9112]).
	Support string `json:"support,omitempty"`
}

TD contains the Thing Description document Its structure is:

{
	@context: <WoTTDContext>, {"hiveot":<HiveOTContext>},
	@type: <deviceType>,
	id: <thingID>,
	title: <human description>,  (why is this not a property?)
	modified: <iso8601>,
	schemaDefinitions: {...},
	actions: {actionID: ActionAffordance, ...},
	events:  {eventID: EventAffordance, ...},
	properties: {propID: PropertyAffordance, ...}
	forms: [...]
 }

func NewTD

func NewTD(deviceID string, title string, deviceType string) *TD

NewTD creates a new Thing Description document with properties, events and actions

Conventions: 1. Agents should add a property WoTTitle and update the TD title if it is set. 2. Agents should add a property WoTDescription and update the TD description if it is set. 3. the deviceType comes from the vocabulary and has ID vocab.DeviceType<Xyz>

Devices or bindings are not expected to use forms. The form content describes the connection protocol which should reference the hub, not the device.

	 Its structure:
		{
		     @context: "http://www.w3.org/ns/td",{"hiveot":"http://hiveot.net/vocab/v..."}
		     @type: <deviceType>,        // required in HiveOT. See DeviceType vocabulary
		     id: <thingID>,              // required
		     title: string,              // required. Name of the thing
		     created: <rfc3339>,         // will be the current timestamp. See vocabulary TimeFormat
		     actions: {name:TDAction, ...},
		     events:  {name: TDEvent, ...},
		     properties: {name: TDProperty, ...}
		}

 deviceID is the unique ID of the device
	title to include in the TD
 deviceType is the optional @type identifying the device

func ReadTD

func ReadTD(r io.Reader) (tdi *TD, err error)

ReadTD reads and unmarshals a JSON encoded TD from the given reader

func ReadTDFromFile

func ReadTDFromFile(sourceFile string) (*TD, error)

ReadTDFromFile returns the TD instance of a TM/TD loaded from file

sourceFile is the file containing the TM/TD in JSON

func UnmarshalTD

func UnmarshalTD(tdJSON string) (tdi *TD, err error)

UnmarshalTD unmarshals a JSON encoded TD

func UnmarshalTDList

func UnmarshalTDList(tdListJSON []string) (tdList []*TD, err error)

func (*TD) AddAction

func (tdoc *TD) AddAction(name string, title string, description string,
	input *DataSchema) *ActionAffordance

AddAction provides a simple way to add an action affordance Schema to the TD. This returns the action affordance that can be augmented/modified directly. By default this is considered 'unsafe', it affects device state.

If the action accepts input parameters then set the .Data field to a DataSchema instance that describes the parameter(s).

name is the action name under which it is stored in the action affordance map.
actionType from the vocabulary or "" if this is a non-standardized action
title is the short display title of the action
description optional explanation of the action
input with dataschema of the action input data, if any

func (*TD) AddEvent

func (tdoc *TD) AddEvent(
	eventName string, title string, description string, schema *DataSchema) *EventAffordance

AddEvent provides a simple way to add an event to the TD. This returns the event affordance that can be augmented/modified directly. To set a known vocabulary @type, use setVocabType on the result

If the event returns data then set the .Data field to a DataSchema instance that describes it.

eventName is the name under which it is stored in the affordance map.
title is the short display title of the event
schema optional event data schema or nil if the event doesn't carry any data

func (*TD) AddForms

func (tdoc *TD) AddForms(forms []Form)

AddForms adds top level forms to the TD Existing forms are retained.

func (*TD) AddProperty

func (tdoc *TD) AddProperty(propName string, title string, description string, dataType string) *PropertyAffordance

AddProperty provides a simple way to add a read-only property to the TD.

This returns the property affordance that can be augmented/modified directly By default the property is a read-only attribute.

propName is the name under which it is stored in the affordance map.
	If omitted, the eventType is used.
propType describes the type of property in HiveOT vocabulary if available, or "" if this is a non-standard property.
title is the short display title of the property.
dataType is the type of data the property holds, DataTypeNumber, ..Object, ..Array, ..String, ..Integer, ..Boolean or null

func (*TD) AddPropertyAsBool

func (tdoc *TD) AddPropertyAsBool(
	propName string, title string, description string) *PropertyAffordance

AddPropertyAsBool is short for adding a read-only boolean property

propType describes the type of property in HiveOT vocabulary if available, or "" if this is a non-standard property.

func (*TD) AddPropertyAsInt

func (tdoc *TD) AddPropertyAsInt(
	propName string, title string, description string) *PropertyAffordance

AddPropertyAsInt is short for adding a read-only integer property

propType describes the type of property in HiveOT vocabulary if available, or "" if this is a non-standard property.

func (*TD) AddPropertyAsString

func (tdoc *TD) AddPropertyAsString(
	propName string, title string, description string) *PropertyAffordance

AddPropertyAsString is short for adding a read-only string property

propType describes the type of property in HiveOT vocabulary if available, or "" if this is a non-standard property.

func (*TD) AddSecurityScheme

func (tdoc *TD) AddSecurityScheme(name string, scheme SecurityScheme)

AddSecurityScheme adds a security scheme to the TD

func (*TD) AsMap

func (tdoc *TD) AsMap() map[string]interface{}

AsMap returns the TD document as a key-value map

func (*TD) EscapeKeys

func (tdoc *TD) EscapeKeys()

EscapeKeys replace spaces in property, event and action keys with dashes

func (*TD) GetAction

func (tdoc *TD) GetAction(actionName string) *ActionAffordance

GetAction returns the action affordance with Schema for the action. Returns nil if name is not an action or no affordance is defined.

func (*TD) GetAgentID

func (tdoc *TD) GetAgentID() string

GetAgentID returns the agentID of the thing TD, if set. This returns the agentID field.

func (*TD) GetEvent

func (tdoc *TD) GetEvent(eventName string) *EventAffordance

GetEvent returns the Schema for the event or nil if the event doesn't exist

func (*TD) GetFormHRef

func (tdoc *TD) GetFormHRef(form Form, uriVars map[string]string) (href string, err error)

GetFormHRef returns the URL of the form and injects the URI variables if provided. If the form uses a relative href then prepend it with the base defined in the TD.

func (*TD) GetForms

func (tdoc *TD) GetForms(operation string, name string) []Form

GetForms returns the forms for the requested operation. The caller still has to find the matching protocol based on url and subprotocol field.

This first checks for forms in the requested operation by affordance name, and appends the global forms.

FIXME: make this wot compatible. The top level forms seem to play a different role than the one in the affordances. The other problem is that the sheer amount of forms would bloat the TD so I have trouble accepting this approach.

operation is the operation as defined in TD forms
name is the name of property, event or action whose form to get or "" for the TD level operations

func (*TD) GetID

func (tdoc *TD) GetID() string

GetID returns the ID of the things TD

func (*TD) GetProperty

func (tdoc *TD) GetProperty(propName string) *PropertyAffordance

GetProperty returns the Schema and value for the property or nil if its key is not found.

func (*TD) GetPropertyOfVocabType

func (tdoc *TD) GetPropertyOfVocabType(vocabType string) (string, *PropertyAffordance)

GetPropertyOfVocabType returns the first property affordance with the given @type This returns the property ID and the property affordances, or nil if not found

func (*TD) GetSecurityScheme

func (tdoc *TD) GetSecurityScheme() (scheme SecurityScheme, err error)

Get the security scheme for connecting to this device.

This only supports a single scheme as hivekit transports only handle a single scheme. If multiple schemes apply then the application must handle it.

If the Security field is empty, then return a nosec scheme.

This returns an error if multiple schemes must be used or not scheme is defined for the TD security field.

func (*TD) SetForms

func (tdoc *TD) SetForms(formList []Form)

SetForms replaces the top level forms section of the TD

func (*TD) Substitute

func (tdoc *TD) Substitute(s string, vars map[string]string) string

Substitute substitutes the variables in a string Variables are define with curly brackets, eg: "this is a {variableName}"

func (*TD) ToString

func (tdoc *TD) ToString() string

ToString returns the JSON representation of the TD

func (*TD) UpdateAction

func (tdoc *TD) UpdateAction(name string, affordance *ActionAffordance) *ActionAffordance

UpdateAction adds a new or replaces an existing action affordance of actionID. Intended for creating TDs.

name is the name under which to store the action affordance.

This returns the added action affordance

func (*TD) UpdateEvent

func (tdoc *TD) UpdateEvent(name string, affordance *EventAffordance) *EventAffordance

UpdateEvent adds a new or replaces an existing event affordance of eventID. Intended for creating TDs

name is the ID under which to store the event affordance.

This returns the added event affordance.

func (*TD) UpdateProperty

func (tdoc *TD) UpdateProperty(name string, affordance *PropertyAffordance) *PropertyAffordance

UpdateProperty adds or replaces a property affordance in the TD. Intended for creating TDs

name is the name under which to store the property affordance.

This returns the added affordance to support chaining

func (*TD) UpdateTitleDescription

func (tdoc *TD) UpdateTitleDescription(title string, description string)

UpdateTitleDescription sets the title and description of the Thing in the default language

title is the name of the device, equivalent to the vocab.PropDeviceName property.
description is the device product description.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL