Встраиваем своё устройство «умного дома» в экосистему smartthings
Содержание:
- Как удалить?
- Manage/Control Devices
- Using personal access tokens
- Step 2: Update device information
- Чем мы уникальны?
- Что можно делать с помощью Smart Things
- Build your Project
- Manage a device profile
- Views
- April 20, 2018
- Step 5. Test your Automation
- Device subscriptions
- Example with Postman
- Using SmartApp tokens
- Page creation
- PAGE Phase
- Authorizing calls from SmartThings
- Light
- Authentication
Как удалить?
Если вы не пользуетесь системой умного дома и само приложение вам ни к чему, тогда его можно удалить. Чем новее телефон, тем сложнее это сделать. Если в наиболее часто встречающихся смартфонах (Lenovo, Alcatel, Xiaomi, BQ и др.) можно удалить приложение простым удержанием и перетаскиванием иконки к верхней функции «удалить», то в смартфонах по типу ASUS, LG, Samsung нужно нажать на три точки вверху, откуда выбрать «Удаление / отключение приложения».
Однако в самых свежих телефонах от Samsung, например, в Galaxy S8 удаление происходит через удержание значка и с переходом в распахнувшееся контекстное меню справа к пункту «удалить».
Обратите внимание:
Код ошибки 910 (Плей Маркет): что делать?
Поскольку Smart Things – предустановленное приложение, в некоторых смартфонах оно может так просто не удалиться
Конкретно это приложение для смартфона не жизненно важно, поэтому его отключение не повредит системе, но и удалить его просто нельзя:
- Заходим в настройки системы.
- Находим нужно приложение.
- Выбираем «Отключить».
Итак, подведем небольшие итоги. Что это – SmartThings Samsung? Это приложение или программа на андроид в телефоне Самсунг, например, в Galaxy, которое отвечает за активность и работоспособность техники и умных систем внутри умного дома.
Как пользоваться? Просто запустить приложение при включенных активных устройствах, чтобы Smart Things обнаружил их. Что это такое и для чего приложение нужно, мы разобрались. Если же вы хотите узнать, как отключить или даже удалить его, то тут все зависит от вашей модели и версии смартфона. В некоторых телефонах вы сможете удалить простым нажатием, в более свежих нужно заходить в настройки системы.
На этом все. Если у вас был опыт удаления или использования такой программы, приглашаем в комментарии поделиться опытом.
Manage/Control Devices
You can also use the CLI to display and control the status of a device. The following commands display all the devices registered on SmartThings Cloud.
- : Print devices that contain an OCF resource model.
- : Print client devices.
Check detailed information of a device.
You can also use the CLI to display detailed information of a device. Information listed about a device includes deviceID, label, name, locationID, deviceTypeId, deviceTypeName, DeviceNetworkType, deviceManufacturerCode and components.
- : Specify a target device ID.
- : Print a resource mode of target device.
- : Print a resource model in detail.
Check the status of a device.
- : Specify a target device ID
- : Specify a component ID of target device.
- : Print an OCF resource status of target device.
- : Specify HREF information of target resource when option is enabled.
Update the status of a device.
- : Specify a target device ID.
- : Specify a Capability ID to which you want to send a command.
- : Specify a command that a Capability supports, Refer to the Capabilities reference page for more information.
- : Specify a component ID of device. It is by default if you don’t specify a name.
- : Specify arguments of a command. Refer to the Capabilities reference page for more information.
Update the status of a resource directly
This command only applies if a device contains an OCF resource model.
- : Update the OCF resource status of device
- : Specify the HREF information of target resource when is enabled
- : Specify a target resource’s status (JSON format) that will be updated when is enabled
- : Specify an OCF resource type when option is enabled
- : Specify an OCF interface when is enabled
Using personal access tokens
When creating a personal access token on the personal access token page, you select the specific permissions granted for that token.
The permissions map to the specific OAuth scopes as documented in the table below:
Permission | OAuth scope | Description |
---|---|---|
Read all devices | Read details about a device, including device attribute state. The scope is limited to the account associated with the token. This scope is required to create subscriptions. | |
Write all devices | Update details such as the device name, or delete a device. The scope is limited to the account associated with the token. | |
Execute all devices | Execute commands on a device. The scope is limited to the account associated with the token. | |
Read all installed apps | Read details about installed SmartApps, such as which devices have been configured for the installation. The scope is limited to the account associated with the token. | |
Write all installed apps | Create, update, or delete installed SmartApps. The scope is limited to the account associated with the token. | |
Read all locations | Read details of a location, such as geocoordinates and temperature scale. The scope is limited to the account associated with the token. | |
Execute all locations | Execute commands at a Location. The scope is limited to the account associated with the token. | |
Create device types | Create devices of the type associated with the device profile. Only applicable for SmartApp tokens, and requires that the device profile and the SmartApp have the same account owner. | |
Read all scenes | Get all the scenes. Only for personal access tokens, and the scope is limited to the account associated with the token. | |
Execute all scenes | Execute scenes. Only for personal access tokens, and the scope is limited to the account associated with the token. |
Step 2: Update device information
Your device needs two files to connect to the SmartThings cloud:
- Device Identity (device_info.json)
- Device Onboarding (onboarding_config.json)
Device identity file
All devices must be provisioned in advance with the SmartThings cloud. The device’s identity and authentication data are needed before the device can connect.
For individual contributors
When testing your device, provide the following information in the device_info.json file in the main directory of your device application:
For manufacturers
It is expected that commercially-ready devices will store the device identity information of each device in a secure location during the manufacturing process for the production level device app. For example, device identity data will be flashed into the SmartThings non-volatile memory location.
For ED25519
Flashed item | Type | Description | Examples |
---|---|---|---|
PKType | data | Public key algorithm type | ED25519 |
CACert | file | Server CA Certificate | root_crt.pem |
SubCert | file | Client (=Device) Certificate, only for X.509 | device.pubkey.b64 |
PrivateKey | file | Client (=Device) Private key | device.seckey.b64 |
SerialNum | data | Device Serial Number | cc50e309dcd0 |
Device onboarding file
The onboarding_config.json was created in the Developer Workspace during the device registration process. Download the file and copy it to the root directory of the device app.
The location for ESP8266 is displayed below:
You can see an example onboarding_config.json file below:
Here’s a breakdown of the data contained in onboarding_config.json:
- — the prefix used in the SSID of Soft-AP during the Easy-setup process. The value is defined in the final stages of device registration. This value is tightly coupled with the device identity provisioned in the Developer Workspace. If is changed, all previously provisioned device identities will not be able to authenticate; the device identities will need to be submitted again.
- — manufacturer ID. A unique four-letter ID assigned by SmartThings to developers to uniquely identify accounts. Organizations have their own , which is shared with its members. You can find your in the Developer Workspace under My Page -> MNID.
- — a unique three-digit number. This value comes from the Device onboarding ID when you performed the Create a device onboarding profile step in the Developer Workspace.
- — an alphanumeric vendor identifier that you give to your device. This vendor identifier is created when you Create a device profile in the Developer Workspace.
- — determines the device icon and default UI layout in the SmartThings app. This value is selected when creating your device profile.
-
— This is the method your device will apply to validate ownership when onboarding to SmartThings. There are four supported types:
- — no owner intervention needed
- — owner will press a button
- — owner enters a 4 digit code
- — owner scans the device’s QR code
- — a unique certificate or public key pair used for authentication when connecting to the SmartThings Cloud. At this time only is supported.
Чем мы уникальны?
Инновационные технологии в обучении
Активное применение интерактивной доски и компьютерной техники практически на каждом занятии. Курс робототехники: наши дети, начиная с 1-го класса, сами пишут программы и изобретают приборы для создания «умного» дома.
Индивидуальный подход к каждому
Каждый ребенок уникален от природы! В каждом ребенке мы гармонично развиваем все 8 интеллектов: вербальный, логико-математический, пространственный, музыкальный, телесно-кинестетический, внутриличностный и межличностный, натуралистический.
Профессиональная помощь в процессе обучения
Самостоятельное выполнение ребенком домашнего задания сопровождают педагоги-профессионалы. Также каждый ребенок может дополнительно получить индивидуальную консультацию по любому предмету.
Обучение и поддержка родителей
Smart J – это территория для детей и родителей. У нас работает специальная программа обучения и поддержки родителей: ежемесячные встречи, вебинары, семинары, индивидуальные консультации лучших специалистов по вопросам возрастной психологии, развития детей и подростков.
Что можно делать с помощью Smart Things
Пользователь, установивший Smart Things в свое мобильное устройство, сможет задавать достаточно много задач с помощью данного программного обеспечения:
- Задавать время активации и прекращения работы различных световых систем. Например, фонарей, расположенных рядом с домом, которые некоторые просто забывают выключать. Или можно настроить аналогичное оборудование, расположенное непосредственно внутри помещений;
- Полностью автоматизировать систему подачи воды. Например, набрать ванну к определенному времени и с заданной температурой;
- Контролировать время функционирования различного бытового оборудования. Удаленно управлять их функциями;
- Осуществлять контроль за корректностью работы датчиков. Например, используемых в сигнализации, холодильной технике, сушилках и так далее.
- Выполнять анализ состояния дверей и окон – на наличие их недостаточного закрытия, к примеру;
- Подготавливать расписание, по которому будет действовать техника в определенное время.
То есть, вариантов очень много.
Build your Project
You need to build a project before you can test it. Building a project provides the .ppk file you install into the SmartThings app.
To build your project, navigate to the project folder and use the the following command.
Building a project generates your app with your manufacturer ID (MNID) and your device-profile Vendor ID (VID).
Reference
Your app is built using the following files:
- catalog.json: contains easy setup information for how to add devices into the SmartThings app.
- project.json: contains information for building your .ppk file.
- {MNID}_{VID}_ui.json: contains information for displaying device cards.
- {MNID}_{VID}_voice.json: contains information for handling devices using voice.
Once you build your project, a new folder is created in the project directory named . Here you find your .ppk file.
{Device-Plugin ID}_{Version}.ppk: displays device information in detail.
Manage a device profile
The SmartThings SDK defines a device type using a device profile. This is based on a JSON Capability model, similar to below:
- Name: Name of device profile
- Component ID: Component ID of device
- Capability ID: Capability ID supported by component
- MNID: Manufacturer ID of developer
- VID: Device Vendor ID
You can check the supported Capability IDs on the capabilities reference page
The CLI also provides a default device profile.
You can also check a detailed device model by with the device profile ID.
-
: Specify the target device profile ID
-
: Print the device model based on Capability as OCF resource model
Custom device profile
To create a custom device profile, you need to generate the device profile file in the JSON model and then execute the following command.
—in: Specify the device profile file path that is written in JSON format
Views
There are three main views of a device in the SmartThings app.
Detail View
This describes what the device will look like once the device card is tapped, and the device is being displayed full screen.
Automation View
The automation section describes how the process for setting up an automation for a device will look. This includes which UI elements will be used for the «if» () part of the automation, as well is the «then» () part.
States
Within the context of device configurations, states are used for overriding the formatted state strings as defined in the capability presentation < TODO: Insert link to capability presentation #states>. This allows devices to have state strings that are relevant to their particular device integration.
Actions
Simialar to Device Configuration states, actions here are meant as overrides to the underlying capability presentation values that the device is referencing. See: <TODO: link here to capabilities presentation actions >
Conditions
Conditions define states that will trigger automations to fire. These can be defined within capability presentations, but overriden here if a device wishes to deviate from that definition in some way.
< TODO: link to capability presentaton conditions section >
April 20, 2018
Release Contents
-
Developer Workspace
- Enhanced UI for the cloud-connected device integration.
- Now you can set the App setting for the Automation.
- “My page” is now available.
- Now you can download UI Manifest files.
-
Local SDK
-
IDE: Device Profile manager is now available to manage device profiles better.
- When you create a new device profile, you can now use five predefined device profiles.
- Create, delete, update, and save as options are now available for device profiles.
- CLI: Added option to show CLI/CommonLib versions.
- Enhanced the performance, and the user interface, of the device plugin simulator and the virtual device.
-
IDE: Device Profile manager is now available to manage device profiles better.
Known Issues
- In the local SDK, exporting your project will not work if the project has capabilities with POST command.
- In the local SDK, please use the Device plugin simulator to test your custom device plugins if the version of your SmartThings app is 1.7.05-25. We recommend you to test custom device plugins inside the SmartThings app with above 1.7.05-25.
- On Developer Workspace, for the Smoke Detector capability for the cloud-connected device: you cannot see the state on the Dashboard, but you can check the status on the Detail page.
Step 5. Test your Automation
Start with the SmartThings app.
- After adding your Automation in the app, you will see the Example Weather Color Light app. Tap on it to install it.
- Enter all the required inputs on the configuration screens.
- Once installed, the configured bulb will turn on and its color will be either:
- Purple (if precipitation is in the forecast),
- Orange (if the forecast calls for temperatures above 80 degrees Fahrenheit),
- Blue (if the forecast calls for temperatures below 50 degrees Fahrenheit), or
- White (if no precipitation and temperature between 50 and 80 degrees Fahrenheit). The app will check the current weather at the interval set during installation.
Device subscriptions
SmartApps may create subscriptions for specific devices selected and authorized by the user during Configuration.
Device subscriptions are created by specifying and including a object in the JSON request body:
Components, Capabilities, and Attributes
Device subscriptions may be created at the Component, Capability, and Attribute (and attribute value) granularity, or some combination thereof.
IMPORTANT : When subscribing to a specific attribute value, the value can be any valid JSON object type, and it should correspond to the attribute type defined by the Capability. For example, if an attribute is of type NUMBER, then a JSON number would be used.
Moreover, when receiving device events, the type of the value will also correspond to the attribute type defined in the Capability, as noted above.
At its most granular, subscriptions can be created for a specific value of an attribute of a specified capability, on a specific component.
The following shows a subscription request body for when a «switch» capability device, of the «main» component, has its «switch» attribute change to «on»:
Use the wildcard operator, , to specify any value.
The following example subscription create request body shows how to create a subscription to a device for any capability and attribute event:
Omitting the is equivalent to specifying all values.
Required permissions
Creating a device subscription requires that the SmartApp has requested the permission to read specific authorized devices.
This is set during app creation or update, and the permission format is .
The SmartApp does not need to request any additional permissions during the INITIALIZE phase of the CONFIGURE lifecycle.
Upon selection of devices and authorization by the user to read these devices, all incoming requests to your SmartApp will contain permission in the form of .
This permission allows your app to get information (including device attribute values) about the authorized device.
Example with Postman
You can use Postman app for accessing and updating your devices using SmartThings API.
In the example below we will use Postman to get a list of all the devices for a user account, and actuate and update a device. Make sure that you have at least one device in your SmartThings user account and follow the steps below:
Obtain SmartThings personal access token
-
If you don’t have it already, open your Samsung account.
-
Next, get a personal access token for calling the SmartThings API. You will use this as a bearer token in the Postman app.
Go to the personal access tokens page and click on the Generate new token on top-right.
Give a name for your token. Select Devices to authorize the scope of the token for the devices. Click on Generate Token in the bottom right.
This will generate a token, as shown below (token display hidden in the pictures below). Copy the token and save it somewhere safe and private.
Get a list of devices
-
In the Postman window, select GET and type in the SmartThings API .
-
In the Authorization section, for the TYPE field, select Bearer Token from the drop-down menu list. This will display the Token form field on the right. Copy and paste here the personal access token that you obtained from above.
Click Send in the top right.
The response from SmartThings Cloud will be seen in the bottom half of the Postman window. SmartThings Cloud will respond with a JSON body containing a list of devices, as shown in the picture below.
Get the description of a specific device
For any device in the above list of devices, using the of that device, we can get a full description of that device.
-
For any device of your choice from the above list in the JSON response body, copy the value of the .
-
In the Postman window, select GET and type in the SmartThings API as shown below.
Click Send in the top right. You will get a detailed description of the device in the same response window of the Postman app.
Execute commands on the device
To actuate a device you need to send a POST request to the API with the device command in the body of the request.
-
In the Postman window, select POST and type in the SmartThings API .
-
In the Body section of the Postman request window, select raw option, and JSON (application/json) from the pull down menu, as shown below.
Type in the JSON command body. In this example, the below device command to turn ON a Sylvania Smart bulb is issued:
Click Send in the top right. This will turn ON the Sylvania bulb.
Update a device
You can change the properties of a device with the PUT request to the SmartThings API .
-
In the Postman window, select PUT and type in the SmartThings API .
-
In the Body section of the Postman request window, select raw option, and JSON (application/json) from the pull down menu, as shown below.
Type in the JSON command body. In this example, the label property of the Sylvania bulb is changed to New Bulb.
Using SmartApp tokens
When SmartThings sends a request to your SmartApp for the INSTALL, UPDATE, and EVENT lifecycles, it includes an authorization token on the request body.
The authorization token has its OAuth scopes defined as below.
OAuth scopes for SmartApp token
The scopes for a SmartApp token are derived from the following steps:
-
When you create a SmartApp, you must also ensure that a set of OAuth scopes are whitelisted for your SmartApp. These whitelisted scopes are what your SmartApp may request during the installation process.
NOTE : The SmartThings Developer Workspace will require you to select a set of OAuth scopes to be whitelisted for your SmartApp.
-
In your SmartApp, during the INITIALIZE phase of the CONFIGURATION lifecycle, you specify any non-entity-specific permissions your SmartApp requires. Entity-specific permissions, such as device-specific permissions, are handled by the DEVICE setting. The permissions requested must be present in the whitelist defined in step 1).
-
The specific OAuth scopes for an installation are then created from the requested permissions in 1) and 2) above.
Whitelisting OAuth scopes
NOTE : Whether you are using Developer Workspace or working on the command line, you are required to explicitly select a set of OAuth scopes to be whitelisted for your SmartApp.
Setting and updating the whitelisted OAuth scopes
To explicitly whitelist the OAuth scopes or to update the OAuth scopes, which may be requested by your SmartApp, make a request to the API (), using a personal access token (the token must have the permission).
The example below shows a request to update a SmartApp’s OAuth settings. In this example the SmartApp will be able to request permissions to read and execute commands on devices, as well as read and write schedules.
You should replace the values with those required for your SmartApp.
Page creation
When a user chooses to install your SmartApp, the user will be guided through the installation process via configuration screens (Pages). These screens provide the user with basic information about the SmartApp, and request information and/or access to devices needed by the SmartApp.
The installation process triggers the lifecycle event in your SmartApp. Your SmartApp must handle the event in two phases:
- Provide basic information about the SmartApp itself. ( phase)
- Provide configuration data that represents the information the user must provide on Pages to install your SmartApp. ( phase)
PAGE Phase
In the phase, the SmartApp receives a JSON request:
Your SmartApp must respond with a JSON payload that describes the sections and settings for . The components of a Page are explained in .
NOTE : Your SmartApp must define at least one Page in JSON format during the phase. Testing the implementation without defining at least one Page will return a server error.
Define a Single Page
Below is an example of a JSON response that describes a single Page.
This payload consists of Page data, Page sections, and settings that correspond to each Page section. Read more details in .
The field ‘complete’ is a Boolean that indicates whether this Page is the last Page. If your SmartApp has only one Page, this field should be set to «true».
Below is the page that is displayed.
Multiple Pages
If your app requires multiple Pages for configuration, you must specify , , and in a series of responses to the lifecycle. Based on the values of and , a request will be made to your SmartApp for each Page.
An example response to a lifecycle request for the first Page of a multi-page configuration would look like the following:
Upon advancing to the second Page, another lifecycle event occurs, and your SmartApp would respond to this request as shown below.
For a two-page configuration, you must specify = «true» to indicate that the SmartApp configuration will be completed on this Page.
The property in the object has the value «DEVICE». This means that tapping this type of setting will take the user to a list of Connected Devices that have the same Capabilities. Since is set to «true», the user must choose one of the Connected Devices.
In the , we will discuss other possible values of ‘type’.
Below are the Pages corresponding to the above responses that are displayed in the SmartThings app:
Authorizing calls from SmartThings
HTTP Signatures
All requests sent by SmartThings are digitally signed in accordance with the IETF HTTP Signatures Draft 3 specification.
A full discussion of HTTP signature verification is beyond the scope of this document; consult the specification referenced above, or see Joyent’s page on http signing for more information.
Authorization Flow
Currently, SmartThings provides 2 mechanisms for which signatures are generated.
- Using a publicly available SmartThings generated x.509 certifcate.
- Using the public / private key generated during SmartApp registration.
The following diagram outlines the general flow for both signing mechanisms.
- Request made by SmartThings to your SmartApp.
- Depending on the elected signing mechanism (SmartThings x.509 Certificate or SmartApp Public Key), the field in the Authorization header will vary.
- If SmartThings x.509 ⟶ SmartApp should call to fetch the correct public key for signature verification.
- If SmartThings Public Key ⟶ Fetch public key via the mechanism you implemented to store. This is same public key provided during registration.
- SmartApp computes the validity of the signature using the resolved key combined with the HTTP Headers provided on callback request.
Using SmartThings x.509 Certificate
A Webhook SmartApp will receive requests digitally signed by one of the publicly available SmartThings x.509 certificates.
This approach has the following benefits:
- Increased security as the certificates are rotated periodically.
- Ease of use. You are no longer required to deploy copies of your SmartApp’s public key alongside your integration.
On each request, the Webhook SmartApp will lookup / cache the certificate referenced by the HTTP Signature attribute. It will then use that certificate to verify the signature was generated by SmartThings.
Using SmartApp Public Key
NOTE : This method is currently deprecated.
Using the SmartApp’s public key was the original approach for SmartThings callback authorization.
This mechanism requires you to copy the public key you received during SmartApp registration into your SmartApp container, and use it to verify that the signature provided on the Authorization header originated from SmartThings.
Newly created SmartApps will be opted into the above SmartThings x.509 Certificate method. Existing SmartApps will continue to use the public key method documented in this section.However, they may opt-in at anytime to leveraging SmartThings x.509 Certificate by following the next section.
Opt in your SmartApp
To opt into using the SmartThings x.509 certificate for digital signing, make a simple API call.
You will need a and your SmartApp’s App ID, which can be found in Developer Workspace.
Request
Response
Additionally, a SmartApp can revert back to using the associated public key:
Request
Response
The request to change the signature type of your SmartApp is processed asynchronously. It may take up to a few minutes for the change to fully take effect.
Example
The recommended and easiest way to implement the callback authorization logic in your SmartApp is to use one of the official SDKs.
The following uses the SmartThings Node SDK.
Node
Light
Set light value
Bixby Commands | Examples | Capabilities |
---|---|---|
Change the / dimming level to | «Change the light bulb dimming level to 25» | |
Maximize/Minimize the brightness of the / | «Maximize the brightness of the light» «Minimize the brightness of the light» |
Dim / Brighten by a certain percentage
Bixby Commands | Examples | Capabilities |
---|---|---|
Dim the / by 50% | «Dim the light name by 50%» | |
Brighten the / by 50% | «Brighten the light by 50%» |
Change the color
Bixby Commands | Examples | Capabilities |
---|---|---|
Change the / color to | «Change the light color to Blue» |
Check status
Bixby Commands | Examples | Capabilities |
---|---|---|
Check the dimming level of the / | «Check the dimming level of the light bulb» |
Authentication
Get an access token
You need an Access Token to interact with SmartThings Cloud. To get an Access token, you login with your Samsung Account.
By logging in to Samsung Account, the SDK associates your project info with your identity. Projects can be accessed through Developer Workspace and in the SmartThings app (on a mobile device).
There are two ways to get an Access Token.
- Use the Samsung Account login page.
- Use a Samsung Account Authcode.
Samsung Account login page
The easiest way to get the Access Token is to use the command. This opens a login prompt for your Samsung Account. Once you do this, your token is automatically generated.
Samsung Account Authcode
You can also get an access token with a Samsung Account authcode. An authcode is a unique string of letters and numbers – generated by Samsung – that is assigned to your account. This is useful when you don’t have a dedicated UI set up on your environment.
To generate an authcode from Samsung.
- Open the Samsung Account authorization token page.
- Log in with your Samsung account.
- You receive a message similar to this :
- Copy the second string in the message. In the example above, it is .
- Use the following command.
Reference
—value {authCode}: Replace {authCode} with your generated authcode from Samsung.