Documentation
¶
Overview ¶
Package td with Schema type definitions as described here: https://www.w3.org/TR/wot-thing-description/#sec-data-schema-vocabulary-definition
Package msg with the response error value ¶
Package things with API interface definitions ¶
Package td with API interface definitions for forms ¶
Package things with API interface definitions ¶
Package wot with WoT TD vocabulary
Index ¶
- Constants
- func ConvertToNative(strVal string, dataSchema *DataSchema) (val any, err error)
- func ForEachTD(tdDir string, handler func(sourceFile string, tdi *TD))
- func GetSourceFilesInDir(sourceDir string) ([]string, error)
- func MarshalTD(tdi *TD) (tdJson string)
- func SortThingsByID(tds []*TD)
- func SortThingsByTitle(tds []*TD)
- type ActionAffordance
- type CredLoc
- type DataSchema
- type ErrInvalidTD
- type ErrorValue
- type EventAffordance
- type Form
- func (f Form) GetHRef() (href string, found bool)
- func (f Form) GetMethodName() (method string, found bool)
- func (f Form) GetOperation() string
- func (f Form) GetOperations() []string
- func (f Form) GetSubprotocol() (subp string, found bool)
- func (f Form) ResolveHRef(base string, uriVars map[string]string) (hrefURL *url.URL, err error)
- func (f Form) SetMethodName(method string) Form
- func (f Form) SetSubprotocol(subp string) Form
- type InteractionAffordance
- type PropertyAffordance
- type SecurityScheme
- type TD
- func (tdoc *TD) AddAction(name string, title string, description string, input *DataSchema) *ActionAffordance
- func (tdoc *TD) AddEvent(eventName string, title string, description string, schema *DataSchema) *EventAffordance
- func (tdoc *TD) AddForms(forms []Form)
- func (tdoc *TD) AddProperty(propName string, title string, description string, dataType string) *PropertyAffordance
- func (tdoc *TD) AddPropertyAsBool(propName string, title string, description string) *PropertyAffordance
- func (tdoc *TD) AddPropertyAsInt(propName string, title string, description string) *PropertyAffordance
- func (tdoc *TD) AddPropertyAsString(propName string, title string, description string) *PropertyAffordance
- func (tdoc *TD) AddSecurityScheme(name string, scheme SecurityScheme)
- func (tdoc *TD) AsMap() map[string]interface{}
- func (tdoc *TD) EscapeKeys()
- func (tdoc *TD) GetAction(actionName string) *ActionAffordance
- func (tdoc *TD) GetAtTypes() []string
- func (tdoc *TD) GetEvent(eventName string) *EventAffordance
- func (tdoc *TD) GetForm(op string, name string, prefScheme, prefSubprotocol string) (form *Form, match bool)
- func (tdoc *TD) GetForms(operation string, name string) []Form
- func (tdoc *TD) GetID() string
- func (tdoc *TD) GetProperty(propName string) *PropertyAffordance
- func (tdoc *TD) GetPropertyOfVocabType(vocabType string) (string, *PropertyAffordance)
- func (tdoc *TD) GetRCID() string
- func (tdoc *TD) GetSecurityScheme() (scheme SecurityScheme, hasMultiple bool, err error)
- func (tdoc *TD) IsDirectory() bool
- func (tdoc *TD) ResolveHRef(form *Form, uriVars map[string]string) (href string, scheme string, err error)
- func (tdoc *TD) SetForms(formList []Form)
- func (tdoc *TD) SetRCID(id string)
- func (tdoc *TD) SetType(atType string)
- func (tdoc *TD) ToJSON() string
- func (tdoc *TD) UpdateAction(name string, affordance *ActionAffordance) *ActionAffordance
- func (tdoc *TD) UpdateEvent(name string, affordance *EventAffordance) *EventAffordance
- func (tdoc *TD) UpdateProperty(name string, affordance *PropertyAffordance) *PropertyAffordance
- func (tdoc *TD) UpdateTitleDescription(title string, description string)
Constants ¶
const ( SecSchemeApiKey string = "apikey" SecSchemeAuto string = "auto" SecSchemeBasic string = "basic" SecSchemeBearer string = "bearer" // no longer in TD-1.1; we still support it as its useful SecSchemeCert string = "cert" SecSchemeDigest string = "digest" SecSchemePSK string = "psk" SecSchemeNoSec string = "nosec" SecSchemeOAuth2 string = "oauth2" )
https://www.w3.org/TR/wot-thing-description11/#securityscheme
const ( UriVarName = "name" UriVarThingID = "id" UriVarOperation = "op" )
URI variables for use in TD
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.
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
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
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
const AtTypeDirectory = "ThingDirectory"
const AtTypeGateway = "ThingGateway"
const HiveOTContext = "https://www.hiveot.net/vocab/v0.1"
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 GetSourceFilesInDir ¶
GetSourceFilesInDir return the list of .json source files in the given directory
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"`
// 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( op string, href string, method string, vars map[string]string) Form
AddForm adds an interaction form to the action affordance Use SetSubprotocol in case the form is a sub-protocol. This modifies vars to include the operation. 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 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"`
// 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 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"`
// 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 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/IntegerSchema 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
// Note that both the 'number' and 'integer' schemas use different types, so
// please use the 'conv' package to decode to the desired type.
Maximum any `json:"maximum,omitempty"`
// Minimum specifies a minimum numeric value representing a lower limit
Minimum any `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.
func (*DataSchema) UnitSymbol ¶
func (ds *DataSchema) UnitSymbol() string
UnitSymbol returns the symbol of the unit of this schema using the vocabulary unit map.
This returns: * an empty string of the schema has no unit * an international symbol for the unit if one is known * the unit name if no symbol is defined in the vocab
type ErrInvalidTD ¶
type ErrInvalidTD struct {
// contains filtered or unexported fields
}
type ErrorValue ¶
type ErrorValue struct {
// Status code: https://w3c.github.io/wot-profile/#error-responses
Status int `json:"status"`
// Type is a URI reference [RFC3986] that identifies the problem type.
Type string `json:"type"`
// Title contains a short, human-readable summary of the problem type
Title string `json:"title"`
// Detail a human-readable explanation
Detail string `json:"detail,omitempty"`
}
Error response payload
func ErrorValueFromError ¶
func ErrorValueFromError(err error) *ErrorValue
Create an ErrorValue object from the given error. This returns nil if err is nil.
func (*ErrorValue) AsError ¶
func (e *ErrorValue) AsError() error
AsError returns an error instance or nil if no error is contained
func (*ErrorValue) String ¶
func (e *ErrorValue) String() string
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"`
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( op string, href string, method string, vars map[string]string) Form
AddForm adds an interaction form to the event affordance Use SetSubprotocol if the affordance is a websocket, sse or other http subprotocol 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 ¶
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 ¶
NewForm creates a new form instance
operation is required href can be a relative path is base is set.
func (Form) GetHRef ¶
GetHRef returns the form's href field. This returns an empty string if not found. See also ResolveHRef
func (Form) GetMethodName ¶
GetMethodName returns the form's HTTP "htv:methodName" field
func (Form) GetOperation ¶
GetOperation returns the first of a form's operation
func (Form) GetOperations ¶
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 ¶
GetSubprotocol returns the form's subprotoco field
func (Form) ResolveHRef ¶
ResolveHRef resolves the form's URL merging it with the provided base according to RFC3986 and optionally merged with URI variables and query parameters. This returns an error if the url cannot be parsed
func (Form) SetMethodName ¶
SetMethodName sets the form's HTTP "htv:methodName" field
func (Form) SetSubprotocol ¶
SetSubprotocol sets the form's subprotocol field
type InteractionAffordance ¶
type InteractionAffordance 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"`
}
Interaction Affordance common to Property, Event and Action affordances
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( op string, href string, method string, vars map[string]string) Form
AddForm adds an interaction form to the property affordance Use SetSubprotocol if the form is for an http sub-protocol. 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"`
// 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
// Directory TD's have the "Directory" type, but they can also have a more specific type such as "LightDirectory"
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"`
// RFC3339 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"`
// RFC3339 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"`
// RCID is a hiveot extension containing the ID of the client that wrote the TD.
// Intended for supporting reverse connections on a gateway.
RCID string `json:"hiveot:rcid,omitempty"`
// Data schema definitions used in this TD.
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 ¶
NewTD creates a new Thing Description document with properties, events and actions
Conventions:
- Things should add a writable property WoTTitle to allow consumers to update the TD title.
- Things should add a writable property WoTDescription to allow consumers to update the TD description.
- 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, ...}
}
thingID is the unique ID of the device
title to include in the TD
deviceType is the optional @type identifying the device
func ReadTD ¶
ReadTD reads and unmarshals a JSON encoded TD from the given reader This returns a nil TD if unmarshalling fails
func ReadTDFromFile ¶
ReadTDFromFile returns the TD instance of a TM/TD loaded from file
sourceFile is the file containing the TM/TD in JSON
This returns nil and an error if the TD file cannot be loaded
func UnmarshalTD ¶
UnmarshalTD unmarshals a JSON encoded TD
This returns a nil TD if unmarshalling fails
func UnmarshalTDList ¶
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) 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) 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) GetAtTypes ¶
GetAtTypes returns the Thing @type fields of this TD.
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) GetForm ¶
func (tdoc *TD) GetForm(op string, name string, prefScheme, prefSubprotocol string) (form *Form, match bool)
GetForm returns the form that matches the transport protocol.
The protocol is determined by the href scheme and the optional subprotocol field.
Steps to determine a match:
- Narrow down the available forms by matching operation If a name is provided then collect the forms of the affordance. Add the thing level forms with the matching operation.
- If no preferred scheme/subprotocol is provided then return the first one.
- If a subprotocol is provided then for each form check the 'subprotocol' field. If the subprotocol matches, return the form. The scheme is less specific so it can be ignored. If no form matches the preferred subprotocol then match the scheme.
- If a preferred scheme is provided try to find a match on scheme.
- If no scheme matches then return the first available form.
To determine the href of each form both the 'base' field and the form 'href' field must be considered:
If base is empty, use the form href
If the form href is relative, combined base and href
If href is absolute use href and ignore 'base'
If form href is empty then use TD 'base'.
op is the operation as defined in TD forms. Use "" for only considering thing level forms. name is the optional name of property, event or action affordance, or "" for thing level operations. prefScheme is the preferred scheme to match prefSubprotocol is the preferred subprotocol name. This overrides the scheme check.
This returns the form and a flag if preferred scheme/protocol matched
func (*TD) GetForms ¶
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. If no operation is given then this returns the Thing level forms.
If no operation is provided then this returns the thing level forms.
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) 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) GetRCID ¶
GetRCID returns the clientID of the device that manages the Thing.
The reverse-connection ID is a HiveOT extension to the WoT TD and only used on a gateway.
It is intended for use by a gateway to identify the reverse-connected client that will handle requests for this thing.
func (*TD) GetSecurityScheme ¶
func (tdoc *TD) GetSecurityScheme() (scheme SecurityScheme, hasMultiple bool, err error)
Get the security scheme for connecting to this device.
NOTE: this is a convenience function that returns a single security scheme. If multiple schemes then 'hasMultiple' returns true and the application can decide to do more work to select an alternative.
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) IsDirectory ¶
IsDirectory returns true if the TD represents a directory Directories are identified by the @type "ThingDirectory" keyword.
func (*TD) ResolveHRef ¶
func (tdoc *TD) ResolveHRef(form *Form, uriVars map[string]string) ( href string, scheme string, err error)
ResolveHRef is a helper that determines the href from base and optional form and substitutes optional URI variables.
func (*TD) SetRCID ¶
Set the clientID of the RC device that published this TD to the directory. Intended for use in gateways to facilitate routing of requests to reverse-connected devices.
func (*TD) SetType ¶
SetType adds the given type to the @type field. If the @type field is empty then set the value as a string If the @type field already has a value then add the value as a list If the same value already exists then do nothing.
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 ¶
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.