Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Recommendations
Filter
Develop Mobile Samsung Automation
docsmartthings automation integrating smartthing's automation requires an understanding of the smartapp lifecycles and implementing its protocol the smartthings nodes provided in the automation studio allows you to wire installed devices to implement autorun rules without any code or simply deploying an automation node that implements the smartapp lifecycle without coding event nodes for device subscriptions, status nodes for device status checks, and command nodes for device commands are provided in general, the smartthings automation is designed in the following order place the device profile node and determine the required capability enter the web-hook url through the automation node after that, implement the logic that corresponds to the autorun rule you can read the state of the device through the status node you can command the device by placing an command node you can extend the experience using external apis device profile node this node represents an installed device in this flow, you need to choose a device for automation event, condition and action nodes need to know which devices will subscribe to the smartthings cloud or commands this node has a capability that represents a device feature find more information about the capabilities of smartthings properties - name required a label of the name assigned by the user it is a unique name in the flow - capability required the list of capabilities provided by this device determines if this device supports the specified capability name automation node this node represents the webhook endpoint of smartapp the automation node handles lifecycles of smartapp a webhook endpoint in this context is a web services application which can receive incoming http post requests properties - name required a name for the webhook endpoint - endpoint required an endpoint that should be invoked during execution - output lifecyle event next node is the event node only event node this node is registered as a subscriber through the automation node must be used with automation node this node represents a change of device whenever a user installs a smartapp, they typically will select the devices to be used on the smartapp the installed device interacts with this event node when the device changes and an event occurs, the event node can receive the event as a subscriber properties - name required the label of the device assigned by the user - device the unique system identifier for this device - capability required the list of capabilities provided by this device determines if this device supports the specified capability name - attribute the list of attributes for this device determines if this device has the specified attribute status node this node checks the status of the device when a user installs a smartapp, they typically will select the devices to be used by the smartapp this condition node interacts with the installed device this node allows you to branch the flows based on the state of the device properties - name required the label of the device assigned by the user - device the unique system identifier for this device - capability required the list of capabilities provided by this device determines if this device supports the specified capability name - attribute the list of attribute s for this device determine if this device has the specified attribute command node this node can commands to the device when a user installs a smartapp, they typically will select the devices to be used by the smartapp this action node interact with the installed device the commands in this action node can change the state of the installed device properties - name required the label of the device assigned by the user - device the unique system identifier for this device - capability required the list of capabilities provided by this device determine if this device supports the specified capability name - attribute the list of attribute s for this device determines if this device has the specified attribute properties - name required the label of the device assigned by the user - device the unique system identifier for this device - capability required the list of capabilities provided by this device determines if this device supports the specified capability name - attribute the list of attributes for this device determines if this device has the specified attribute example it's a smartthings automation using contactsensor and lifx bulb create a webhook with device profile and automation nodes add a device profile node for the contactsensor with contactsensor capability add a device profile node for the bulb with a switch capability add a node for the smartthings automation webhook add an event node to subscribe to the contactsensor change add status nodes to check the switch is "off" add command nodes to change the bulb to "on" add command nodes to change the bulb "off" save and deploy register in smartthings developer workspace in order for smartthings automation to work, app-registration is required visit the smartthings developer workspace create a new automation project register the smartapp webhook endpoint copy the webhook endpoint on the automation node complete the registration process next is to "deploy to test" install smartapp in smartthings app deploying your smartapp to test does not mean your service is published when you deploy your service to test, only the samsung developer account used to deploy to test will be able to install the service from the smartthings app, and only after enabling developer mode in the smartthings app test-your-device after this, you can install the smartapp that "deploy to test" above visit now - samsung automation studio beta
Develop Mobile Samsung Automation
docsmartthings my device directly control smartthings devices without even registering the automation by using the automation studio to do this, you are advised to get your 'pat personal access token ' and the 'device id' of smartthings before you can make a flow my device node this node represents an your smartthings device you can control your smartthings devices directly without even registering the automation to do this, you should set your pat on this node and select one on your device list then, you can get a condition or put a command to your installed devices by using 'status', 'command' nodes after setting your pat, get your device list and select device that you want to control properties - name the label of the name assigned by the user it's unique name in flow - personal access token getting a smartthings pat on the personal access token page never share your tokens with anyone! - device list the list of your device that select device that you want to control, subscribe example set your pat on the 'my device' node select the device that you want to use on the your device list 3 select the device you want on the 'status'/'command' node make a flow using 'status'/'command' node that was set sample use case a bulb switch control using the bixby voice visit now - samsung automation studio beta
Learn Code Lab
codelabdevelop a smartthings find-compatible device objective learn how to create your own smartthings find-compatible device using the smartthings find partnership program device sdk learn how to measure the radio frequency rf performance of a bluetooth low energy ble device using tag toolbox partnership request the smartthings find partnership program is available only to registered partners who wish to commercialize you can only do this code lab and get the resources after a successful partnership to form a partnership, contact partners@smartthings com overview the smartthings find partnership program comprises smartthings find device specification, smartthings find device sdk, test tool, and technical support it facilitates the development of devices operating with smartthings find services and mobile applications the smartthings find device sdk is small enough to work on resource-limited microcontroller unit mcu devices in this code lab, you can learn how to develop your own smartthings find device first, you can know how to set up your project in smartthings using the developer workspace next, you can learn how to build your firmware with smartthings find device sdk lastly, you can know how to check the functionalities of your device's rf performance using the tag toolbox app set up your environment you will need the following host pc running on windows 11 visual studio code as the ide smartthings find device sdk code smartthings find tag toolbox smartthings app toolchain for nrf52833 dk use the ncs nrf connect sdk version 2 6 1 nrf52833 dk with buzzer module and nfc antenna galaxy smarttag2 register and deploy to test your device using the smartthings developer workspace, you can create a device profile, customize the instructions for onboarding the device on the smartthings app, and test the devices by deploying them you can edit the configurations until you submit the device for publication in the smartthings ecosystem sign in to smartthings developers go to smartthings developer workspace and sign in using your samsung account select a project and add a device profile select stfind codelab example and check its device profile under the device profile, specify whether the device operates on ble ble and uwb afterward, you can customize your device's onboarding experience in smartthings by uploading your product images, user instructions, and brand name under device onboarding lastly, you can fill in basic product information in the product info deploy your device to test after you complete all of these, you can go back to the overview tab and press deploy to test you can download the tagonboardingconfig h file which includes your project configuration the sdk code needs this configuration file register your devices you can add the identity of your device in the smartthings cloud for authentication this requires device information like serial number and device public key ed25519 when you reach the maximum number of test devices per user, remove the existing ones this example shows how to create an ed25519 key pair with sdk tools in visual studio code, press the tagkeygen button at the bottom afterward, you can generate the serial number, private key, and public key register it to the smartthings cloud using the smartthings developer workspace and include it in your firmware after checking the created information on visual studio code go to the developer workspace go to test > test devices menu, and click register new device input the generated serial number and public key build the firmware with the sdk open visual studio code and build the firmware for your device open the sdk project in the file explorer of visual studio code, you can find four code lab files here when you click the nrf connect icon, it shows important functions such as build, flash, and serial log check the configuration files ensure that two essential configuration files are applied tagonboardingconfig h tagdeviceinfo h write your code in main c, complete the code to call the taginit and tagstart apis of device sdk you can find code_mission in the source code and follow the instructions in the code by simply removing the comments #include <zephyr/zephyr h> #include <zephyr/sys/printk h> #include "tagsdk h" #include "mbedtls/aes h" static void init_aes_table void { mbedtls_aes_context dump_ctx; unsigned char dump_key[16]; mbedtls_aes_setkey_enc &dump_ctx, dump_key, 128 ; } void main void { int err = 0xff; tagresult_t result = tag_result_not_supported; /** * code_mission * you will check this serial log later in this codelab */ printk "tag demo! %s-%s-%s\n", config_board, __date__,__time__ ; init_aes_table ; /** * code_mission * call taginit api by removing comment // * * by calling this api, tag sdk will load nv, set rtc and * initialize crypto, and so on * you shall initialize bsp before call this api * services and starts ble advertising */ // result = taginit ; if result != tag_result_success { printk "failed to init %d\n", result ; return; } err = bt_enable 0 ; if err { printk "failed to init bt %d\n", err ; return; } /** * code_mission * call tagstart api by removing comment // * * by calling this api, tag sdk will initialize ble gatt * db and services and starts ble advertising * you shall initialize ble stack before call this api */ // result = tagstart ; if result != tag_result_success { printk "failed to start maintask %d\n", result ; return; } } in portnfc c, call the seturl function you can find code_mission in the source code and follow the instructions in the code by simply removing the comments tagerror_t portnfcseturl char *url, size_t urllen { tagerror_t ret = tag_error_none; ret = disablenfc ; if ret != tag_error_none { tag_log_e "failed to disable nfc" ; return ret; } /** * code_mission * remove comment // below to call seturl function */ // ret = seturl url, urllen ; if ret != tag_error_none { tag_log_e "failed to set url message" ; return ret; } ret = enablenfc ; if ret != tag_error_none { tag_log_e "failed to enable nfc" ; return ret; } return tag_error_none; } build go to nrf connect > actions click on build noteit may take some time for the build to finish you can see the progress by checking the popup at the bottom-right corner of the ide you can also select nrf connect build in the terminal to check the detailed status flash connect the nrf52833 dk to your computer go to nrf connect > actions click on flash once completed, you can hear a notification sound from your device check the serial log of your device go to nrf connect > connected devices click the plug icon on the right side of vcom0 comxx at the top of the ide, select the first item in the list under connected devices press the reset button briefly on your device by checking the timestamp from the serial log, you can verify whether your device successfully downloaded the firmware onboard and control your device via smartthings app onboard your device launch the smartthings app tap the + icon at the top right of the screen click on add device select add in the partner devices section select my testing devices then, select stfind codelab example to start onboarding allow the use of location information and press agree verify your device by pressing the button on the board in the success! page, tap on done to finish onboarding your device locate and ring your device tap on view map to show the location of your device select ring and your device produces a sound through its buzzer module you may switch to either high-volume or low-volume ringing press stop to stop the ringing configure the lost mode of your device when lost mode is activated, it allows you to view a lost message showing the owner's contact information and any personalized messages in the smartthings app, tap on view map > more > lost mode in the lost mode page, select next add email, contact, and message information then, tap on turn on test it by placing an nfc device or a mobile device at the nfc antenna of your device a lost message should show on your mobile device test the device's rf performance via tag toolbox smartthings find tag toolbox allows you to measure the rf performance of a ble device and log the results create a new test item launch the tag toolbox app on a mobile device tap on ble performance > add new test to create a new test item select a target device and a reference device to compare rf performance a target device this is your device created through this code lab b reference device this is the smarttag2 as a comparison target conduct rf performance tests press start session and check your device's rf performance once completed, tap on take a picture and capture how far away the mobile device is from both your device and the smarttag2 tap on test result to find out your device's rf performance export test result test reports can be exported as a file either during the test or after completing the test check your device's rf performance in the list of session menu a min rssi minimum value of your device's rf signal b max rssi maximum value of your device's rf signal c packet detection rate if the advertising transmission interval is two seconds, it indicates how many packets were detected during the test duration press export test result and it shows the location of the file on your mobile device you're done! congratulations! you have successfully achieved the goal of this code lab topic now, you can develop your own smartthings find-compatible devices to form a partnership, contact partners@smartthings com
Learn Code Lab
codelabintegrate iot devices into the smartthings ecosystem objective learn how to create your own iot device using smartthings sdk for direct connected devices overview the smartthings sdk for direct connected devices is provided to ease the development of devices which operate with smartthings cloud and mobile application it is small enough to work on resource limited embedded devices in this code lab, you will learn how to create your own iot device profile at smartthings cloud and how to implement on your test device it is explained into three parts the first explains how you can register and deploy to test your own iot device profile in smartthings using the developer workspace then, it demonstrates how to create your own iot device application with smartthings sdk the last part shows how to onboard and control instances of your device with smartthings mobile application noteyou will name the device as code lab example for this tutorial set up your environment you will need the following host pc this code lab is based on ubuntu linux x64 toolchain and board support package bsp for micro-controller unit mcu board you will use the esp32-c3-devkitc board you may set up the environment by referring to this github repository github repositories for the library and references or samples of smartthings sdk for direct connected devices for c $ git clone https //github com/smartthingscommunity/st-device-sdk-c-ref git $ cd st-cevice-sdk-c-ref $ python3 setup py esp32 smartthings mobile application sample code here is a sample code for you to start coding in this code lab download it and start your learning experience! smartthings sdk sample code 2 60 kb register and deploy to test your device using the developer workspace, create a device profile and customize the instructions for onboarding the device on the smartthings mobile app, and deploy devices to be tested these configurations can be edited up until the point you submit the device for publication in the production of the smartthings ecosystem sign in to smartthings developers sign in to smartthings developer workspace using your samsung account create new project you need to create an integration project for a direct connected device create a new device project for device integration select device integration, then direct-connected afterwards, name your project respectively add a device profile define your device’s functionalities with smartthings capability first, navigate and select define device profile and then click create device profile fill the required fields with respective values afterwards, select a capability for your device you can get more information about the capabilities available here notethe health check capability is automatically added for all direct connected devices it should not be removed the required capabilities are switch and health check add device onboarding the device onboarding guides device owners when their device is first registering and connecting to smartthings you can customize the screens presented by adding a device onboarding profile the ownership validation type is also defined at this stage you may customize the screens displayed when the device onboards via the smartthings mobile app, or just use the default values noteuse just works or button confirm for this example add a product info the product info defines how this device is shown at smartthings mobile app catalog you can define device’s category and its regional availability deploy your device to test you can start testing by deploying your device to test there are two ways to do this via overview menu via test > test devices you will be able to see your device in the smartthings mobile app when in developer mode only after it has been deployed for testing register test devices you can add the identity of device for authenticating it to the smartthings cloud this requires device information like serial number and device public key ed25519 since the maximum number of test device is limited per user, once you’ve reached it, you should remove the existing one this example shows how to create ed25519 key pair with sdk tools you can get device_info json file as a result from tools/keygen/linux/output_{ serialnumber} linux version of key generator keygen utility is located at st-iot-device-sdk-c-reference/iot-core/tools/keygen/ or st-device-sdk-c/tools/keygen/ serial number for testing device would be randomly generated by this tool which has stdk + 12-digit alphanumeric format $ cd ~/workspace/st-device-sdk-c-ref/iot-core/tools/keygen/ $ python3 stdk-keygen py –firmware switch_example_001 use following serial number and public key for the identity of your device in developer workspace serial number stdk**e90w***ucx public key nfn5x***uqusq****zhobsfaaop9***kndlnjdjrew= copy stdk**e90w***ucx from keygen output and paste it into serial number field of register a test device page copy public key string from keygen output nfn5x***uqusq****zhobsfaaop9***kndlnjdjrew= in this example and paste it into public key field generate device qr code using the device qr code could be helpful while device onboarding qr code should have format like below refer here for more details urlhttps //qr samsungiots com/?m={your mnid}&s={device onboardingid}&r={device serialnumber} {your mnid} 4-digit alphanumeric mnid of your account {device onboardingid} 3-digit number onboarding id, you can find it from your developer workspace project device onboarding > other info page {device serialnumber} device serial number which is registered at your developer workspace project you can simply generate qr code with using below python script import qrcode mnid = 'ffff' # "ffff" is an example you should replace it with yours onboardingid = '111' # "111" is an example you should replace it with yours serialnumber = 'stdktest0001' # "stdktest0001" is an exmaple you should replace it with yours qrurl = 'https //qr samsungiots com/?m=' + mnid + '&s=' + onboardingid + '&r=' + serialnumber img = qrcode make qrurl img save serialnumber + ' png' qrcode qrcode box_size=10, border=4 write device application open and edit sample device app currently, you are doing the code lab example, which is located at apps/esp32/code_lab_example directory in the github repository download onboarding_profile json from the overview of your device in developer workspace copy onboarding_profile json file into your application directory, apps/esp32/code_lab_example/main $ cd ~/workspace/st-device-sdk-c-ref/apps/esp32/code_lab_example/main/ $ cp ~/downloads/onboarding_config json copy device_info json from tools/keygen/linux/output_{serialnumber} which contains your device specific information to application directory, apps/esp32/code_lab_example/main $ cd ~/workspace/st-device-sdk-c-ref/iot-core/tools/keygen/ $ cp output_{serialnumber}/device_info json ~/workspace/st-device-sdk-c-ref/apps/esp32/code_lab_example/main/ firmwareversion version string privatekey base64 encoded ed25519 private key this value should be paired with what you registered to developer workspace publickey base64 encoded ed25519 public key this value should be same with what you registered to developer workspace serialnumber this value should be same with what you registered to developer workspace { "deviceinfo" { "firmwareversion" "switch_example_001", "privatekey" "dh**jkmrd5x****bav+fgoxa3qzfnw3v****jhxomd0=", "publickey" "nfn5x***uqusq****zhobsfaaop9***kndlnjdjrew=", "serialnumber" "stdk**e90w***ucx" } } open sample application source code browse in apps/esp32/code_lab_example/main/ directory open main c file write your device application code this example already has cloud connection functionality using smartthings sdk apis void app_main void { /** easily integrate your direct connected device using the direct connected devices sdk the sdk manages all mqtt topics and onboarding requirements, freeing you to focus on the capabilities of your device that is, you can simply develop a basic application by just calling the apis provided by st_iot_core layer like below // create a iot context 1 st_conn_init ; // create a handle to process capability 2 st_cap_handle_init ; called in function 'capability_init' // register a callback function to process capability command when it comes from the smartthings server 3 st_cap_cmd_set_cb ; called in function 'capability_init' // process on-boarding procedure there is nothing more to do on the app side than call the api 4 st_conn_start ; */ unsigned char *onboarding_config = unsigned char * onboarding_config_start; unsigned int onboarding_config_len = onboarding_config_end - onboarding_config_start; unsigned char *device_info = unsigned char * device_info_start; unsigned int device_info_len = device_info_end - device_info_start; int err; iot_gpio_init ; xtaskcreate app_main_task, "app_main_task", 4096, null, 10, null ; //create a iot context iot_ctx = st_conn_init onboarding_config, onboarding_config_len, device_info, device_info_len ; if iot_ctx != null { err = st_conn_set_noti_cb iot_ctx, iot_noti_cb, null ; if err printf "fail to set notification callback function\n" ; } else { printf "fail to create the iot_context\n" ; } //create a handle to process capability and initialize capability info capability_init ; //connect to server err = st_conn_start iot_ctx, st_status_cb &iot_status_cb, iot_status_all, null, null ; if err { printf "fail to start connection err %d\n", err ; } } complete your command callback function for each capability the command callback function should contain your device control upon each command such as led on or off control capability example for each capability would be helpful to handle attribute command for each capability you can find it at apps/capability_example/main static void update_switch_state int switch_state { const char* switch_value; if switch_state == switch_on { switch_value = caps_helper_switch attr_switch value_on; } else { switch_value = caps_helper_switch attr_switch value_off; } //todo set switch attribute value and send // // example //=============================================================================== // cap_switch_data->set_switch_value cap_switch_data, switch_value ; // cap_switch_data->attr_switch_send cap_switch_data ; //=============================================================================== } static int get_switch_state void { const char* switch_value; int switch_state = switch_off; //todo get switch attribute value // // example //=============================================================================== // switch_value = cap_switch_data->get_switch_value cap_switch_data ; // // if !strcmp switch_value, caps_helper_switch attr_switch value_on { // switch_state = switch_on; // } else if !strcmp switch_value, caps_helper_switch attr_switch value_off { // switch_state = switch_off; // } //=============================================================================== return switch_state; } static void cap_switch_cmd_cb struct caps_switch_data *caps_data { int switch_state = get_switch_state ; set_led_mode switch_state ; } static void capability_init { //todo initialize switch capability with using capability sample's initializae function // // example // //=============================================================================== // cap_switch_data = caps_switch_initialize iot_ctx, "main", null, null ; // if cap_switch_data { // const char *switch_init_value = caps_helper_switch attr_switch value_on; // // cap_switch_data->cmd_on_usr_cb = cap_switch_cmd_cb; // cap_switch_data->cmd_off_usr_cb = cap_switch_cmd_cb; // // cap_switch_data->set_switch_value cap_switch_data, switch_init_value ; // } //=============================================================================== } build, flash, and monitor you can build, flash, and monitor in the console with the following $ cd ~/workspace/st-device-sdk-c-ref $ python3 build py apps/esp32/code_lab_example $ python3 build py apps/esp32/code_lab_example flash $ python3 build py apps/esp32/code_lab_example monitor or $ cd ~/workspace/st-device-sdk-c-ref $ python3 build py apps/esp32/code_lab_example flash monitor onboard and control the device via smartthings app onboarding a enable developer mode developer mode should be enabled on smartthings mobile application launch the smartthings app, go to dashboard > settings long-press about smartthings for 20 seconds enable the developer mode, then restart the smartthings app you can find out more information here b add a new device go to add device and click my testing devices or scan qr code you can now see and add your self-published devices control by smartthings application a device control from dashboard you can turn your device’s led on or off by clicking the button in the smartthings app b device control from plugin you can control various attributes and get more detailed information from the device plugin user interface you're done! congratulations! you have successfully achieved the goal of this code lab now, you can control your iot devices using the smartthings app all by yourself! if you're having trouble, you may download this file smartthings device sdk complete code 2 49 kb
Learn Code Lab
codelabtest edge drivers using smartthings test suite objective learn how to identify and resolve issues when deploying edge drivers using smartthings test suite overview smartthings test suite is a tool for testing iot device integrations within the smartthings platform this solution provides a seamless certification process, allowing developers of smartthings hub connected devices to submit their products for certification without the need for manual testing this accelerates the certification timeline and offers a more cost-effective path to certifying these devices the key feature of this self-testing tool is it contains an automated testing suite that covers critical certification criteria, ranging from functionality to performance tests the tool also provides real-time feedback that gives detailed information on the device's compliance status, allowing for quick identification and resolution of any issues lastly, it has an intuitive and user-friendly interface that ensures a seamless experience for developers of all levels set up your environment you will need the following host pc running on windows 10 or higher or ubuntu 20 04 x64 visual studio code latest version recommended devices connected on the same network android mobile device with smartthings app installed with android 10 or higher smartthings station or smartthings hub onboarded with samsung account smartthings v4 multipurpose sensor or lightify tunable white 60 light bulb notemake sure that your devices are connected to your smartthings app sample code here is a sample code for this code lab download it and start your learning experience! test suite sample code 185 4 kb install smartthings cli you need to install smartthings cli as this is the main tool for developing apps and drivers for smartthings edge drivers to install smartthings cli, open a web browser and download the smartthings msi installer from the latest release notefor other operating systems, download the appropriate zipped binary and install it on your system path open the smartthings cli setup in the downloaded file, then click next accept the license agreement terms, then click next select the destination path for installation and click next to begin the installation process, click install notethe windows installer may display a warning titled windows protected your pc to continue the installation, click more info > run anyway complete the setup by clicking finish to verify if smartthings cli is installed correctly, open the command prompt and run this command smartthings --version view and run available commands for smartthings cli with this command smartthings --help for a full list of commands, visit the smartthings cli commands notethe smartthings cli supports an automatic login flow that launches a browser window, prompting the user to log in with samsung account and grant the cli permissions to access the user's account start your project after downloading and extracting the sample code containing the project files, click file > open folder in visual studio code to open it locate the sample code file directory and click select folder once finished, the project files are seen on the explorer menu configure custom edge drivers open your command prompt or terminal and follow the corresponding instructions depending on your device availability make sure that the path directory in your cli contains the project file smartthings multipurpose sensor in the terminal, type the following command to build and upload your edge driver package to the smartthings cloud smartthings edge drivers package drivers/codelab-zigbee-contact create a new channel for your edge driver and enter the following channel details smartthings edge channels create channel name smartthings test suite demo channel description channel for sdc2024 channel terms of service url www smartthings com enroll your hub in your newly created channel and select the corresponding channel and hub smartthings edge channels enroll assign your driver to the created channel smartthings edge channels assign install the created edge driver from your channel to your own hub smartthings edge drivers install confirm that the correct version of the driver is present in your hub smartthings edge drivers installed select the edge driver for this device smartthings edge drivers switch lightify tunable white 60 bulb in the terminal, type the following command to build and upload your edge driver package to the smartthings cloud smartthings edge drivers package drivers/codelab-zigbee-switch create a new channel for your edge driver and enter the following channel details smartthings edge channels create channel name smartthings test suite demo channel description channel for sdc2024 channel terms of service url www smartthings com enroll your hub in your newly created channel and select the corresponding channel and hub smartthings edge channels enroll assign your driver to the created channel smartthings edge channels assign install the created edge driver from your channel to your own hub smartthings edge drivers install confirm that the correct version of the driver is present in your hub smartthings edge drivers installed select the edge driver for this device smartthings edge drivers switch test your device on your web browser, go to smartthings test suite, login to your samsung account and follow the corresponding instructions depending on your device availability smartthings multipurpose sensor on the test suite, look for your device, click menu icon > prepare new test under the compatible capabilities, select all capabilities except for battery, and click start during the test execution, perform the indicated user actions for every test case if there are any it might cause incorrect test results if user actions are not performed tipyou may view the real-time sensor states of the device in the smartthings mobile app view the test summary after the test it returns a failed test that you are going to resolve in the next step lightify tunable 60 white bulb on the test suite, look for your device, click menu icon > prepare new test under the compatible capabilities, select all capabilities after you've selected the capabilities, click start warningduring the test execution, observe the behavior of the bulb it might cause incorrect test results if automated tests are interrupted view the test summary after the test it returns a failed test that you are going to resolve in the next step resolve test failures smartthings multipurpose sensor the test logs contain basic information about the test results and specific test cases, providing technical context to users for efficient troubleshooting download the test logs by navigating to the bottom page of the test summary > show full test details > download log to understand the test logs, its structure follows this schema {execution timestamp} device node path node type [node state] {execution message} in the downloaded test log, two test cases failed with the following error [failed] initialize states following states were not set correctly [contact any other state than "open" on main contactsensor] [failed] send command and validate some events didn't happen [contact "closed" on main contactsensor] some states aren't final [contact "closed" on main contactsensor] in the first error log, it appears that the test suite cannot change the device's state to anything other than an open state in the second error log, the test suite tries to change its state to closed, but to no avail it is confirmed in the capability definition that the contact sensor has only two states open and closed therefore, the device is constantly in an open state and unable to change to a closed state with these information, you can start troubleshooting by going to drivers > codelab-zigbee-contact > multi-sensor > init lua and look for incorrect code implementation with these keywords open, closed, contactsensor it can be seen in the zone_status_change_handler and zone_status_handler functions that there are code blocks on comment this might be a result of someone developing this code have changed this part of code for debugging and forgot to uncomment this part uncomment this code block from zone_status_change_handler function if not device preferences["certifiedpreferences garagesensor"] then contactsensor_defaults ias_zone_status_change_handler driver, device, zb_rx end uncomment this code block from zone_status_handler function if not device preferences["certifiedpreferences garagesensor"] then contactsensor_defaults ias_zone_status_attr_handler driver, device, zone_status, zb_rx end remove this line of code from zone_status_change_handler and zone_status_handler functions device emit_event_for_endpoint zb_rx address_header src_endpoint_value, capabilities contactsensor contact open save the file and update the driver by invoking the same cli commands that were also used during the configuration of custom edge drivers smartthings edge drivers package drivers/codelab-zigbee-contact smartthings edge channels assign smartthings edge drivers install again, go to smartthings test suite, select your device, click menu > prepare new test ensure that all compatible capabilities are selected, with the exception for battery again, start the test and perform indicated user actions for every test case if there are any now, all tests are passed! lightify tunable white 60 bulb the test logs contain basic information about the test results and specific test cases, providing technical context to users for efficient troubleshooting download the test logs by navigating to the bottom page of the test summary > show full test details > download log to understand the test logs, its structure follows this schema {execution timestamp} device node path node type [node state] {execution message} in the downloaded test log, one test case failed with the following error [failed] send command and validate some events didn't happen [colortemperature maximum 7500k on main colortemperature] some states aren't final [colortemperature maximum 7500k on main colortemperature] in the error log, it directs to an issue for setting an incorrect maximum colortemperature value the configuration on your edge driver is set to 7500k you can start to troubleshoot by looking for the bulb's color temperature rating either from the device packaging or the device manufacturer website with these information, you can start troubleshooting by going to drivers > codelab-zigbee-switch > profiles > rgbw-bulb yml and look for lines that declares the colortemperature value change the colortemperature range declaration range [ 2700, 6500 ] save the file and update the driver by invoking the same cli commands that were also used during the configuration of custom edge drivers smartthings edge drivers package drivers/codelab-zigbee-switch smartthings edge channels assign smartthings edge drivers install again, go to smartthings test suite, select your device, click menu > prepare new test under the compatible capabilities, select all capabilities again, start the test and perform indicated user actions for every test case if there are any now, all tests are passed! you're done! congratulations! you have successfully achieved the goal of this code lab now, you can test your edge driver for smartthings devices using smartthings test suite! if you're having trouble, you may download this file test suite complete code 184 6 kb to learn more about smartthings test suite, visit smartthings edge architecture smartthings developer console
Learn Code Lab
codelabcreate a smartthings edge driver for an iot bulb objective learn how to create and customize an edge driver for an iot bulb to seamlessly interoperate on the smartthings platform overview smartthings is a platform for iot devices to communicate within its ecosystem, enabling smarter living solutions that simplify everybody else's way of life there are multiple methods to connect an iot device to the smartthings platform, one of which is through a smartthings hub hub connected devices connect to a smartthings-compatible hub using matter, zigbee, z-wave, or lan protocols the smartthings-compatible hub allows devices that utilize these protocols to integrate within the smartthings platform, permitting users to view and control devices from the smartthings app to automate actions and more the connection from a smartthings device to a smartthings hub is made possible with edge drivers smartthings edge drivers serve as translators between the protocols used by the device and the smartthings platform these drivers enable the devices to run locally on the hub, offering many benefits including speed, reliability, and enhanced functionality learn more about edge drivers in the smartthings edge architecture section set up your environment you will need the following host pc running on windows 10 or higher or ubuntu 20 04 x64 visual studio code latest version recommended devices connected on the same network android mobile device with smartthings app installed with android 10 or higher smartthings station or smartthings hub onboarded with samsung account philips hue bulb smartthings connected device sample code here is a sample code for this code lab download it and start your learning experience! edge driver sample code 6 1 kb install smartthings cli you need to install smartthings cli as this is the main tool for developing apps and drivers for smartthings edge drivers to install smartthings cli, open a web browser and download the smartthings msi installer from the latest release open the smartthings cli setup in the downloaded file, then click next accept the license agreement terms, then click next select the destination path for installation and click next to begin the installation process, click install notethe windows installer may display a warning titled windows protected your pc to continue the installation, click more info > run anyway complete the setup by clicking finish to verify if smartthings cli is installed correctly, open the command prompt and run this command smartthings --version view and run available commands for smartthings cli with this command smartthings --help for a full list of commands, visit the smartthings cli commands notethe smartthings cli supports an automatic login flow that launches a browser window, prompting the user to log in with a samsung account and grant the cli permissions to access the user's account start your project after downloading and extracting the sample code containing the project files, click file > open folder in visual studio code to open it locate the sample code directory and click select folder once finished, the project files are seen on the explorer menu set the bulb's color configuration in init lua, under the device_init function, write the code below to set the bulb's colors and its transition time local colorcontrol = clusters colorcontrol local philips_hue_colors = { {0xed, 0xc4}, -- red {0xae, 0xe3}, -- blue {0x2c, 0xc3}, -- yellow {0x53, 0xd3}, -- green {0xca, 0x08}, -- white } local index = 1 local transition_time = 0 --1/10ths of a second -- when sent with a command, these options mask and override bitmaps cause the command -- to take effect when the switch/light is off local options_mask = 0x01 local options_override = 0x01 device send colorcontrol server commands movetohueandsaturation device, philips_hue_colors[5][1], philips_hue_colors[5][2], transition_time, options_mask, options_override local timer = device thread call_on_schedule 1, function local hue = philips_hue_colors[index][1] local sat = philips_hue_colors[index][2] device send colorcontrol server commands movetohueandsaturation device, hue, sat, transition_time, options_mask, options_override index = index + 1 % 6 if index == 0 then index = 1 end end, "color_schedule_timer" save the file and open either the command prompt or terminal notemake sure that the path directory in your cli contains the project file build and upload your edge driver in the terminal, type the following command to build and upload your edge driver package to the smartthings cloud smartthings edge drivers package create a private channel create a new channel for your edge driver and enter the following channel details smartthings edge channels create channel name smartthings edge driver channel channel description channel for sdc2024 channel terms of service url www smartthings com enroll the smartthings hub in your channel enroll your hub in your newly created channel and select the corresponding channel and hub smartthings edge channels enroll assign the edge driver to your channel assign your driver to the created channel smartthings edge channels assign install the edge driver to your hub install the created edge driver from your channel to your own hub smartthings edge drivers install control the bulb via smartthings app on your mobile phone, launch the smartthings app and tap the + icon once you're on the add device page, tap scan nearby make sure that the philips light bulb is turned on wait for the light bulb to be visible once visible, tap done now, observe the blinking and changing colors of your bulb you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create an edge driver for smartthings devices that can be integrated into the smartthings ecosystem! if you're having trouble, you may download this file edge driver complete code 8 6 kb to learn more about smartthings hub connected devices and edge drivers, visit smartthings hub connected devices smartthings edge driver documentation
Learn Code Lab
codelabmatter build a matter iot app with smartthings home api objective learn how to create an iot app to onboard, control, remove, and share matter devices using smartthings home apis notesmartthings home apis are distributed only to authorized users if you want permission to use the apis, contact st matter@samsung com overview matter is an open-source connectivity standard for smart home and internet of things iot devices it is a secure, reliable, and seamless cross-platform protocol for connecting compatible devices and systems with one another smartthings provides the matter virtual device app and smartthings home apis to help you quickly develop matter devices and use the smartthings ecosystem without needing to build your own iot ecosystem you can use smartthings home apis to onboard, control, remove, and share all matter devices when building your application other iot ecosystems can use the matter devices onboarded on your iot app through the multi-admin function for detailed information, go to partners smartthings com/matter set up your environment you will need the following host pc running on windows 10 or higher or ubuntu 20 04 x64 android studio latest version recommended java se development kit jdk 11 or later devices connected on the same network mobile device with matter virtual device app installed mobile device with developer mode and usb debugging enabled matter-enabled smartthings station onboarded with samsung account used for smartthings app tipyou can create a virtual device as a third-party iot device sample code noteyou can request permission to access the sample project file for this code lab by sending an email to st matter@samsung com start your project after downloading the sample code containing the project files, open your android studio and click open to open an existing project locate the downloaded android project from the directory and click ok commission the device you can onboard a matter-compatible device to the iot app by calling the commissiondevice api, which can lay the groundwork to control, remove, and share the device go to app > java > com samsung android matter home sample > feature > main in the mainviewmodel kt file, call the commissiondevice api to launch the onboarding activity and join the device to the smarththings fabric // ================================================================================= // codelab // step 1 create an instance of matter commissioning client // step 2 call the commissiondevice api to launch the onboarding activity in home service // step 3 set _intentsender value from return value of commissiondevice api // todo 1 device commission and join a device to smartthings fabric // todo 1 uncomment the following code blocks // --------------------------------------------------------------------------------- //val commissioningclient = matter getcommissioningclient //val intentsender = commissioningclient commissiondevice context //_intentsender value = intentsender // ================================================================================= control the device capabilities are core to the smartthings architecture they abstract specific devices into their underlying functions, which allows the retrieval of the state of a device component or control of the device function each device has its own appropriate capabilities therefore, each device has a different control api, and the more functions it supports, the more apis it has to use in this step, select a device type that you want to onboard and control using necessary home apis the level of modification complexity is assigned per each device contact sensorlevel 1 3 mins file path app > java > com samsung android matter home sample > feature > device file name contactsensorviewmodel kt // ================================================================================= // codelab level 1 // step 1 get contactsensor capability from device instance // step 2 get stream openclose value from contactsensor capability // step 3 set _openclose value for ui updating // todo 1 uncomment the following code blocks // --------------------------------------------------------------------------------- //device readcapability contactsensor ? openclose? collect { openclose -> // _openclose value = openclose //} // ================================================================================= // ================================================================================= // codelab level 1 // step 1 get battery capability from device instance // step 2 get stream battery value from battery capability // step 3 set _batterystatus value for ui updating // todo 2 uncomment the following code blocks // --------------------------------------------------------------------------------- //device readcapability battery ? battery? collect { battery -> // _batterystatus value = battery //} // ================================================================================= motion sensorlevel 1 3 mins file path app > java > com samsung android matter home sample > feature > device file name motionsensorviewmodel kt // ================================================================================= // codelab level 1 // step 1 get motionsensor capability from device instance // step 2 get stream occupied value from motionsensor capability // step 3 set _motionoccupied value for ui updating // todo 1 uncomment the following code blocks // --------------------------------------------------------------------------------- //device readcapability motionsensor ? occupied? collect { motionoccupied -> // _motionoccupied value = motionoccupied // timber d "occupied= $motionoccupied" //} // ================================================================================= // ================================================================================= // codelab level 1 // step 1 get battery capability from device instance // step 2 get stream battery value from battery capability // step 3 set _batterystatus value for ui updating // todo 2 uncomment the following code blocks // --------------------------------------------------------------------------------- //device readcapability battery ? battery? collect { battery -> // _batterystatus value = battery // timber d "battery= $battery" //} // ================================================================================= on-off switchlevel 2 4 mins file path app > java > com samsung android matter home sample > feature > device file name switchviewmodel kt // ================================================================================= // codelab level 2 // step 1 get switch capability from device instance // step 2 get stream onoff value from switch capability // step 3 set _onoff value for ui updating // todo 1 uncomment the following code blocks // --------------------------------------------------------------------------------- //device readcapability switch ? onoff? collect { onoff -> // _onoff value = onoff //} // ================================================================================= // ================================================================================= // codelab level 2 // step 1 get switch capability from device instance // step 2 control the device using the apis that supported by switch capability // toggle switch state based on onoff value // onoff == true call switch off // onoff == false call switch on // todo 2 uncomment the following code blocks // --------------------------------------------------------------------------------- //device readcapability switch ? let { switch -> // if onoff == true { // switch off // } else { // switch on // } //} // ================================================================================= smart locklevel 3 8 mins file path app > java > com samsung android matter home sample > feature > device file name smartlockviewmodel kt // ================================================================================= // codelab level 3 // step 1 get lock capability from device instance // step 2 get stream lockunlock value from lock capability // step 3 set _lockstatus value for ui updating // --------------------------------------------------------------------------------- // todo 1 copy code below device readcapability lock ? lockunlock? collect { lockunlock -> _lockstatus value = lockunlock } // ================================================================================= // ================================================================================= // codelab level 3 // step 1 get tamperalert capability from device instance // step 2 get stream tamperalert value from tamperalert capability // step 3 set _tamperstatus value for ui updating // --------------------------------------------------------------------------------- // todo 2 copy code below device readcapability tamperalert ? tamperalert? collect { tamperalert -> _tamperstatus value = tamperalert } // ================================================================================= // ================================================================================= // codelab level 3 // step 1 get battery capability from device instance // step 2 get stream battery value from battery capability // step 3 set _batterystatus value for ui updating // --------------------------------------------------------------------------------- // todo 3 copy code below device readcapability battery ? battery? collect { battery -> _batterystatus value = battery } // ================================================================================= // ================================================================================= // codelab level 3 // step 1 get lock capability from device instance // step 2 control the device using the apis that supported by lock capability // toggle lock state based on lockunlock value // lockunlock == true call lock // lockunlock == false call unlock // --------------------------------------------------------------------------------- // todo 4 copy code below device readcapability lock ? let { lock -> if lockunlock == true { lock lock } else { lock unlock } } // ================================================================================= blindslevel 3 8 mins file path app > java > com samsung android matter home sample > feature > device file name blindviewmodel kt // ================================================================================= // codelab level 3 // step 1 get windowshade capability from device instance // step 2 get stream windowshademode value from windowshade capability // step 3 set _windowshademode value for ui updating // --------------------------------------------------------------------------------- // todo 1 copy code below device readcapability windowshade ? windowshademode? collect { windowshademode -> timber d "windowshademode $windowshademode" _windowshademode value = windowshademode } // ================================================================================= // ================================================================================= // codelab level 3 // step 1 get windowshadelevel capability from device instance // step 2 get stream shadelevel value from windowshadelevel capability // step 3 set _shadelevel value for ui updating // --------------------------------------------------------------------------------- // todo 2 copy code below device readcapability windowshadelevel ? shadelevel? collect { shadelevel -> timber d "shadelevel $shadelevel" _shadelevel value = shadelevel } // ================================================================================= // ================================================================================= // codelab level 3 // step 1 get battery capability from device instance // step 2 get stream battery value from battery capability // step 3 set _batterystatus value for ui updating // --------------------------------------------------------------------------------- // todo 3 copy code below device readcapability battery ? battery? collect { battery -> _batterystatus value = battery } // ================================================================================= // ================================================================================= // codelab level 3 // step 1 get windowshade capability from device instance // step 2 control the device using the apis that supported by windowshade capability // send windowshade open/close/pause command based on controlcommand value // "open" call windowshade open // "close" call windowshade close // "pause" call windowshade pause // --------------------------------------------------------------------------------- // todo 4 copy code below device readcapability windowshade ? let { windowshade -> when controlcommand { "open" -> windowshade open "close" -> windowshade close "pause" -> windowshade pause } } // ================================================================================= extended color lightlevel 4 10 mins file path app > java > com samsung android matter home sample > feature > device file name lightviewmodel kt // ================================================================================= // codelab level 4 // step 1 get switch capability from device instance // step 2 get stream onoff value from switch capability // step 3 set _onoff value for ui updating // --------------------------------------------------------------------------------- // todo 1 copy code below device readcapability switch ? onoff? collect { onoff -> _onoff value = onoff } // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get switchlevel capability from device instance // step 2 get stream level value from switchlevel capability // step 3 set _level value for ui updating // --------------------------------------------------------------------------------- // todo 2 copy code below device readcapability switchlevel ? level? collect { level -> _level value = level } // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get switch capability from device instance // step 2 control the device using the apis that supported by switch capability // toggle switch state based on onoff value // onoff == true call switch off // onoff == false call switch on // --------------------------------------------------------------------------------- // todo 3 copy code below device readcapability switch ? let { switch -> if onoff == true { switch off } else { switch on } } // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get switchlevel capability from device instance // step 2 control the device using the apis that supported by switchlevel capability // call switchlevel setlevel with percentage value // --------------------------------------------------------------------------------- // todo 4 copy code below timber d "target position = $percentage" device readcapability switchlevel ? setlevel percentage // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get colorcontrol capability from device instance // step 2 control the device using the apis that supported by colorcontrol capability // call colorcontrol setcolor with hue,saturation value // --------------------------------------------------------------------------------- // todo 5 copy code below timber d "hue $hue,saturation $saturation" device readcapability colorcontrol ? setcolor hue todouble , saturation todouble // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get colortemperature capability from device instance // step 2 control the device using the apis that supported by colortemperature capability // call colortemperature setcolortemperature with temperature // --------------------------------------------------------------------------------- // todo 6 copy code below device readcapability colortemperature ? setcolortemperature temperature // ================================================================================= video playerlevel 4 10 mins file path app > java > com samsung android matter home sample > feature > device file name televisionviewmodel kt // ================================================================================= // codelab level 4 // step 1 get switch capability from device instance // step 2 get stream onoff value from switch capability // step 3 set _onoff value for ui updating // --------------------------------------------------------------------------------- // todo 1 copy code below device readcapability switch ? onoff? collect { onoff -> _onoff value = onoff } // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get mediaplayback capability from device instance // step 2 get stream mediaplaybackstate value from mediaplayback capability // step 3 set _mediaplaybackstate value for ui updating // --------------------------------------------------------------------------------- // todo 2 copy code below device readcapability mediaplayback ? mediaplaybackstate? collect { mediaplaybackstate -> _mediaplaybackstate value = mediaplaybackstate } // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get switch capability from device instance // step 2 control the device using the apis that supported by switch capability // toggle switch state based on onoff value // onoff == true call switch off // onoff == false call switch on // --------------------------------------------------------------------------------- // todo 3 copy code below device readcapability switch ? let { switch -> if onoff == true { switch off } else { switch on } } // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get mediaplayback capability from device instance // step 2 control the device using the apis that supported by mediaplayback capability // send mediaplayback play/pause/stop/rewind/fastforward command based on controlcommand value // "play" call mediaplayback play and setplaybackstatus with playbackstatus playing // "pause" call mediaplayback pause and setplaybackstatus with playbackstatus paused // "stop" call mediaplayback stop and setplaybackstatus with playbackstatus stopped // "rewind" call mediaplayback rewind and setplaybackstatus with playbackstatus rewinding // "fastforward" call mediaplayback fastforward and setplaybackstatus with playbackstatus fastforwarding // --------------------------------------------------------------------------------- // todo 4 copy code below device readcapability mediaplayback ? let { mediaplayback -> when controlcommand { "play" -> { mediaplayback play mediaplayback setplaybackstatus playbackstatus playing } "pause" -> { mediaplayback pause mediaplayback setplaybackstatus playbackstatus paused } "stop" -> { mediaplayback stop mediaplayback setplaybackstatus playbackstatus stopped } "rewind" -> { mediaplayback rewind mediaplayback setplaybackstatus playbackstatus rewinding } "fastforward" -> { mediaplayback fastforward mediaplayback setplaybackstatus playbackstatus fastforwarding } } } // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get mediatrackcontrol capability from device instance // step 2 control the device using the apis that supported by mediatrackcontrol capability // send mediatrack nexttrack/previoustrack command based on controlcommand value // "nexttrack" call mediatrack nexttrack // "previoustrack" call mediatrack previoustrack // --------------------------------------------------------------------------------- // todo 5 copy code below device readcapability mediatrackcontrol ? let { mediatrack -> when controlcommand { "nexttrack" -> mediatrack nexttrack "previoustrack" -> mediatrack previoustrack } } // ================================================================================= // ================================================================================= // codelab level 4 // step 1 get keypadinput capability from device instance // step 2 control the device using the apis that supported by keypadinput capability // call keypadinput sendkey with key value // --------------------------------------------------------------------------------- // todo 6 copy code below device readcapability keypadinput ? sendkey key // ================================================================================= thermostatlevel 5 13 mins file path app > java > com samsung android matter home sample > feature > device file name thermostatviewmodel kt // ================================================================================= // codelab level 5 // step 1 get thermostatmode capability from device instance // step 2 get stream thermostatmode value from thermostatmode capability // step 3 set _systemmode value for ui updating // --------------------------------------------------------------------------------- // todo 1 copy code below device readcapability thermostatmode ? thermostatmode? collect { thermostatmode -> timber d "viewmodel thermostatmode $thermostatmode" _systemmode value = thermostatmode } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get thermostatfanmode capability from device instance // step 2 get stream thermostatfanmode value from thermostatfanmode capability // step 3 set _fanmode value for ui updating // --------------------------------------------------------------------------------- // todo 2 copy code below device readcapability thermostatfanmode ? thermostatfanmode? collect { fanmode -> _fanmode value = fanmode } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get temperaturemeasurement capability from device instance // step 2 get stream temperature value from temperaturemeasurement capability // step 3 set _temperature value for ui updating // --------------------------------------------------------------------------------- // todo 3 copy code below device readcapability temperaturemeasurement ? temperature? collect { temperature -> _temperature value = temperature } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get thermostatcoolingsetpointbattery capability from device instance // step 2 get stream coolingsetpoint value from thermostatcoolingsetpoint capability // step 3 set _occupiedcoolingsetpoint value for ui updating // --------------------------------------------------------------------------------- // todo 4 copy code below device readcapability thermostatcoolingsetpoint ? coolingsetpoint? collect { coolingsetpoint -> _occupiedcoolingsetpoint value = coolingsetpoint } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get thermostatheatingsetpoint capability from device instance // step 2 get stream heatingsetpoint value from thermostatheatingsetpoint capability // step 3 set _occupiedheatingsetpoint value for ui updating // --------------------------------------------------------------------------------- // todo 5 copy code below device readcapability thermostatheatingsetpoint ? heatingsetpoint? collect { heatingsetpoint -> _occupiedheatingsetpoint value = heatingsetpoint } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get relativehumiditymeasurement capability from device instance // step 2 get stream humidity value from relativehumiditymeasurement capability // step 3 set _humidity value for ui updating // --------------------------------------------------------------------------------- // todo 6 copy code below device readcapability relativehumiditymeasurement ? humidity? collect { humidity -> _humidity value = humidity } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get battery capability from device instance // step 2 get stream battery value from battery capability // step 3 set _batterystatus value for ui updating // --------------------------------------------------------------------------------- // todo 7 copy code below device readcapability battery ? battery? collect { battery -> _batterystatus value = battery } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get thermostatmode capability from device instance // step 2 control the device using the apis that supported by thermostatmode capability // change thermostatmode state based on systemmode value // thermostatsystemmode off call thermostatmode off // thermostatsystemmode cool call thermostatmode cool // thermostatsystemmode heat call thermostatmode heat // thermostatsystemmode auto call thermostatmode auto // --------------------------------------------------------------------------------- // todo 8 copy code below device readcapability thermostatmode ? let { thermostatmode -> when systemmode { thermostatsystemmode off -> thermostatmode off thermostatsystemmode cool -> thermostatmode cool thermostatsystemmode heat -> thermostatmode heat thermostatsystemmode auto -> thermostatmode auto } } // ================================================================================= // ================================================================================= // step 1 get thermostatfanmode capability from device instance // step 2 control the device using the apis that supported by thermostatfanmode capability // change thermostatfanmode state based on fanmode value // thermostatfanmodeenum auto call thermostatfanmode fanauto // thermostatfanmodeenum circulate call thermostatfanmode fancirculate // thermostatfanmodeenum followschedule call thermostatfanmode setthermostatfanmode with followschedule // thermostatfanmodeenum on call thermostatfanmode fanon // --------------------------------------------------------------------------------- // todo 9 copy code below device readcapability thermostatfanmode ? let { thermostatfanmode -> when fanmode { thermostatfanmodeenum auto -> thermostatfanmode fanauto thermostatfanmodeenum circulate -> thermostatfanmode fancirculate thermostatfanmodeenum followschedule -> thermostatfanmode setthermostatfanmode "followschedule" thermostatfanmodeenum on -> thermostatfanmode fanon } } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get thermostatheatingsetpoint capability value from device instance // step 2 increase _occupiedheatingsetpoint value that have current heating value // step 3 if new increased value is under value_max 104 , // call setheatingsetpoint of thermostatheatingsetpoint capability with new increased value // --------------------------------------------------------------------------------- // todo 10 copy code below device readcapability thermostatheatingsetpoint ? let { heatingsetpoint -> val nextvalue = _occupiedheatingsetpoint value!! + 1 if nextvalue < value_max { heatingsetpoint setheatingsetpoint nextvalue } } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get thermostatheatingsetpoint capability value from device instance // step 2 decrease _occupiedheatingsetpoint value that have current heating value // step 3 if new decreased value is over value_min 32 , // call setheatingsetpoint of thermostatheatingsetpoint capability with new decreased value // --------------------------------------------------------------------------------- // todo 11 copy code below device readcapability thermostatheatingsetpoint ? let { heatingsetpoint -> val nextvalue = _occupiedheatingsetpoint value!! - 1 if nextvalue > value_min { heatingsetpoint setheatingsetpoint nextvalue } } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get thermostatcoolingsetpoint capability value from device instance // step 2 increase _occupiedcoolingsetpoint value that have current cooling value // step 3 if new increased value is under value_max 104 , // call setcoolingsetpoint of thermostatcoolingsetpoint capability with new increased value // --------------------------------------------------------------------------------- // todo 12 copy code below device readcapability thermostatcoolingsetpoint ? let { coolingsetpoint -> val nextvalue = _occupiedcoolingsetpoint value!! + 1 if nextvalue < value_max { coolingsetpoint setcoolingsetpoint nextvalue } } // ================================================================================= // ================================================================================= // codelab level 5 // step 1 get thermostatcoolingsetpoint capability value from device instance // step 2 decrease _occupiedcoolingsetpoint value that have current cooling value // step 3 if new decreased value is over value_min 32 , // call setcoolingsetpoint of thermostatcoolingsetpoint capability with new decreased value // --------------------------------------------------------------------------------- // todo 13 copy code below device readcapability thermostatcoolingsetpoint ? let { coolingsetpoint -> val nextvalue = _occupiedcoolingsetpoint value!! - 1 if nextvalue > value_min { coolingsetpoint setcoolingsetpoint nextvalue } } // ================================================================================= noteyou can find related files in android studio by going to edit menu> find > find in files and entering the keyword "codelab" remove the device using removedevice api, you can remove the device from your iot app and the smartthings fabric go to app > java > com samsung android matter home sample > feature > device > base in the baseviewmodel kt file, call the removedevice api to launch the removedevice activity // ================================================================================= // [codelab] device remove from smartthings fabric // step 1 create an instance of matter commissioning client // step 2 call the removedevice api to launch the removedevice activity in home service // step 3 set _intentsender value from return value of removedevice api // todo 1 uncomment the following code blocks // --------------------------------------------------------------------------------- //val commissioningclient = matter getcommissioningclient //val intentsender = commissioningclient removedevice // context, // commissioningclient removedevicerequest deviceid // //_intentsenderforremovedevice value = intentsender // ================================================================================= share the device matter devices can be shared with other matter-compatible iot platforms, such as google home, using home apis without resetting the device while connected to smartthings to perform this operation, it is necessary to enter the commissioning mode without resetting the device in the baseviewmodel kt file, call the sharedevice api to launch the sharedevice activity // ================================================================================= // [codelab] device share to other platforms // step 1 create an instance of matter commissioning client // step 2 call the sharedevice api to launch the sharedevice activity in home service // step 3 set _intentsender value from return value of sharedevice api // todo 1 uncomment the following code blocks // --------------------------------------------------------------------------------- //val commissioningclient = matter getcommissioningclient //val intentsender = commissioningclient sharedevice // context, // commissioningclient sharedevicerequest deviceid // //_intentsenderforsharedevice value = intentsender // ================================================================================= build and run the iot app run the sample app to build and run your iot app, follow these steps using a usb cable, connect your mobile device select the sample iot app from the run configurations menu in the android studio then, select the connected device in the target device menu click run onboard to onboard the virtual device go to the matter virtual device app then, select and set up the virtual device type you want to control click save click start to show the qr code for onboarding go to the sample iot app and click the + button then, onboard the virtual device by scanning its qr code control by sample iot app in the sample iot app, control the virtual device by using its various functions such as on and off for switch you're done! congratulations! you have successfully achieved the goal of this code lab topic now, you can create a matter-compatible iot application with smartthings home apis by yourself! learn more by going to smartthings matter libraries
Develop Mobile Samsung Automation
docsamsung automation studio get started - samsung automation studio beta the automation studio allows you to integrate samsung bixby, smartthings and 3rd party your apis connect it with samsung bixby and smartthings! you can start a free trial the 6th promotion will end when the free trial code we have prepared are exhausted samsung account a samsung account is your gateway to the world of samsung when you sign up for a samsung account, you gain access to apps and services of samsung smartthings support samsung automation studio supports smartthings integration via smartthings node customization bixby voice support bixby voice can execute your flow that designed with "capsule label" node and "capsule result" node securely stored manage and store your flows simply export and import all files are encrypted and securely stored, protect in what matters pre-defined flows start with pre-defined flow templates for a mashing-up various cases get inspiration and create your new flow runtime environment deploy your flows in secured and isolated containers whose healths and lifecycles are managed automatically by the reliable container platform cf bixby capsule support you can create a flow using the capsule label node and capsule result node you can run this flow using the capsule for automation studio we have already developed the capsule for automation studio it is listed on bixby marketplace remote-endpoint makes your business logic more flexible on bixby voice "capsule label" node allows you to call the remote-endpoint without developing a capsule use a remote-endpoint to your capsules? get a paradigm shift when using bixby and its platform for an advanced state of conversational ai and voice jump on the bixby train and be ready for the 500 million, bixby-enabled, samsung devices that ships yearly as these are enabled with remote-endpoints making it more to flexibly code on bixby capsules capsule node decide which name is called through bixby voice without developing a capsule learn more > smartthings support webhook endpoints in this context is a web services application it serves as an api endpoint on the internet, that receives incoming http post requests webhook endpoints must be an https url rapidly build a smartapp by connecting devices and smartthings services easily what is the automation? automation allows the user to control their smartthings ecosystem without any manual intervention an example of an automation is a webhook that uses the smartthings rest api to control and get status notifications from smartthings devices automation node connect easily with the smartthings smartapp using a web hook endpoint deviceprofile node know what capability you need? find the 71 capabilities of smartthings learn more > get started you can start a free trial the 6th promotion will end when the free trial code we have prepared are exhausted *[sign up][1] for a samsung account, if you do not already have one the minimum requirements are samsung account signed up to smartthings or bixby developers get the subscription code development service level get free trial > use our node on your server! you can find our node named "samsung-automation-studio" in node-red community and can install it in node-red you can keep your flows through the import/export npm install node-red-contrib-samsung-automation-studio-nodes self-managed servers limited features learn more > get started - samsung automation studio beta
Learn Code Lab
codelabcontrol a smart bulb objective control a smart light bulb and change its color using bixby home studio overview bixby home studio bhs provides a simple and optimized way for accessing and controlling devices connected to your smartthings account you can quickly create complex diagrams and condition-based flows with bhs's user-friendly graphical user interface gui any device compatible with smartthings can be adjusted, controlled, and updated through bixby home studio for more information, visit getting started with bixby home studio set up your environment you will need the following samsung and smartthings account same email address smart rgb light bulb added to smartthings account virtual switch from smartthings labs if a smart rgb light bulb is not available a go to smartthings app b in the menu, select labs c choose virtual switch and click + to add a virtual switch d enter the name of virtual switch, location, and room notewhen you use a virtual switch, you can only create metadata and test the turning on and off functionality however, a physical smart rgb light bulb is necessary for testing other functions of this code lab activity, such as changing the light bulb color to red smartthings labs feature is available only on android app in us, canada, uk, india, and south korea start your project go to bhs bixbydevelopers com and sign in using your samsung account create a new project select your smartthings location and smart rgb light bulb or virtual switch for the device click create metadata from scratch then, click next choose powerswitch under bixby voice category select the powerswitch-turnoff and powerswitch-turnon voice intents click next input a project name and click done use a sample graph to switch on the bulb sample graphs are various example action flows that you can explore to learn more about the different voice intents, nodes, and smartthings capabilities you can use these sample graphs as starter points for your own devices each sample graph generically handles specific capabilities covered under various user utterances through the different voice intents for example, the turn on device sample graph works for any device it covers a variety of user utterances such as "turn on air conditioner ", "turn on fan ", "turn on speaker ”, and so on follow the steps below to use the turn on device sample graph to switch on the device go to voice intents > powerswitch-turnon > graph click the sample graphs icon on the left sidebar menu to show all the available sample graphs scroll down to see the turn on device sample graph or find it using the search bar drag and drop the sample graph into your powerswitch-turnon graph editor click try it to turn on your light bulb noteif you're using a virtual switch, it will turn on, but you won't be able to see the switch itself however, you can see the state of the virtual switch change from off to on in the smartthings app turn off the light bulb and add an alternative response the turn on device sample graph functions to switch on the device when the start node triggers the command node this graph can be modified to reverse its function, to do that copy the nodes from the powerswitch-turnon graph to the powerswitch-turnoff graph editor click the command node to open the node configuration pane and change the command from on to off right-click on the command node and change its comment to turn off device click try it to turn off the device after the command is performed, the response is either success or execution failed to make the light bulb more responsive, design the graph to provide different responses depending on whether the light bulb is already off or currently on a click the raw button and delete the existing code in the raw graph b copy and paste the following json into it and click add [{"nodeid" "5b648da1-a2c3-4912-baff-a559b968070e","nodever" "1 0","nodetype" "capabilityattribute","isstateful" true,"group" null,"inputports" {"device" {"nodes" [],"portinfo" null}},"triggerports" {"success" {"nodes" ["ccf1cbb8-c99b-439f-8246-bc9e7b7abfbf"],"portinfo" null},"failure" {"nodes" [],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"attribute" {"datatype" "datatype schema afcapabilityattribute","datavalue" {"component" "main","capability" "switch","attribute" "switch","property" {"name" "value","datatype" "datatype primitive afstring"}}},"required" {"datatype" "datatype primitive afboolean","datavalue" true}},"styles" {"x" 415,"y" 360}},{"nodeid" "ccf1cbb8-c99b-439f-8246-bc9e7b7abfbf","nodever" "1 0","nodetype" "equalcomparison","isstateful" true,"group" null,"inputports" {"leftvalue" {"nodes" ["5b648da1-a2c3-4912-baff-a559b968070e"],"portinfo" null},"rightvalue" {"nodes" ["8d9bf8ec-7cb1-4ffe-b4c0-b0424d394027"],"portinfo" null}},"triggerports" {"true" {"nodes" ["593250c4-9c19-4155-8f90-1318f9484aab"],"portinfo" null},"false" {"nodes" ["a9c4d152-eb0d-45d2-a2bd-20217de6fee6"],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"operator" {"datatype" "datatype operator equalcomparisonoperator","datavalue" "equalto"}},"styles" {"x" 585,"y" 332}},{"nodeid" "8d9bf8ec-7cb1-4ffe-b4c0-b0424d394027","nodever" "1 0","nodetype" "constant","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {"value" {"datatype" "datatype primitive afstring","datavalue" "on"}},"styles" {"x" 415,"y" 500}},{"nodeid" "a9c4d152-eb0d-45d2-a2bd-20217de6fee6","nodever" "1 0","nodetype" "responsefeaturealreadyset","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {},"styles" {"x" 635,"y" 480}}] c four nodes were added to the graph an attribute node that receives and passes an on or off value; a constant node with on as its value; an equal comparison node that compares if the attribute value is equal to the constant value; and a response already set node d rewire the graph to make it work properly by clicking the line coming from the start node and pressing the delete key e create a new line from the start node and connect it to the attribute node's trigger port f connect the equal comparison node's true port to the command node's trigger port g click the align button a couple of times to automatically organize the graph h then, click try it while the device is already off or already on, to observe the different responses change the light bulb's color based on time the command node has two capabilities that can adjust the color of light bulb, such as colorcontrol and colortemperature in this step, use these command node capabilities together with the get current datetime node and get datetime attributes node to set the light bulb's color to red or warm, if the current date time is 8 00 pm or later otherwise, the light bulb's color remains blue add the following json into the powerswitch-turnon graph [{"nodeid" "a31659e2-68fc-42b6-8076-01c2cb9fec23","nodever" "1 0","nodetype" "getcurrentdatetime","isstateful" true,"group" null,"inputports" {"__zoneid" {"nodes" [],"portinfo" null}},"triggerports" {"main" {"nodes" ["ea58c225-7d40-45b9-85d6-d8d941de9b2e"],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {},"styles" {"x" 715,"y" 280}},{"nodeid" "ea58c225-7d40-45b9-85d6-d8d941de9b2e","nodever" "1 0","nodetype" "getdatetimeattributes","isstateful" true,"group" null,"inputports" {"input" {"nodes" ["a31659e2-68fc-42b6-8076-01c2cb9fec23"],"portinfo" null}},"triggerports" {"main" {"nodes" ["880416f6-d288-4b97-b763-2abd46bf2737"],"portinfo" null}},"valueports" {"seconds" {"name" "seconds"},"month" {"name" "month"},"hour" {"name" "hour"},"year" {"name" "year"},"minutes" {"name" "minutes"},"timestampinseconds" {"name" "timestampinseconds"},"day" {"name" "day"}},"triggerinports" {},"configurations" {},"styles" {"x" 815,"y" 280}},{"nodeid" "880416f6-d288-4b97-b763-2abd46bf2737","nodever" "1 0","nodetype" "comparablecomparison","isstateful" true,"group" null,"inputports" {"leftvalue" {"nodes" ["gr //node/ea58c225-7d40-45b9-85d6-d8d941de9b2e/value/hour"],"portinfo" null},"rightvalue" {"nodes" ["606796bc-d8ea-4421-942d-91544271615d"],"portinfo" null}},"triggerports" {"true" {"nodes" ["b2ba65ab-5e3e-4615-8d3a-79015a03d7bc"],"portinfo" null},"false" {"nodes" [],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"operator" {"datatype" "datatype operator comparablecomparisonoperator","datavalue" "greaterthanorequalto"}},"styles" {"x" 975,"y" 320}},{"nodeid" "606796bc-d8ea-4421-942d-91544271615d","nodever" "1 0","nodetype" "constant","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {"value" {"datatype" "datatype primitive afinteger","datavalue" 20}},"styles" {"x" 815,"y" 420}},{"nodeid" "2b22b1a1-b9cb-4881-a861-3bf74ccd7847","nodever" "1 0","nodetype" "capabilitycommand","isstateful" true,"group" null,"inputports" {"device" {"nodes" [],"portinfo" null},"1 color" {"nodes" ["2389baa9-db45-4eb3-a40c-1166bf1e620f"],"portinfo" {"datatypes" ["undefined"],"minitems" 1,"maxitems" 1,"iscustomport" true}}},"triggerports" {"success" {"nodes" ["a31659e2-68fc-42b6-8076-01c2cb9fec23"],"portinfo" null},"failure" {"nodes" [],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"commands" {"datatype" "datatype util aflist","datavalue" [{"datatype" "datatype schema afcapabilitycommand","datavalue" {"component" "main","capability" "colorcontrol","command" "setcolor","arguments" [{"datatype" "datatype schema afcommandargument","datavalue" {"name" "color","optional" false,"datatype" "datatype primitive afjsonobject"}}]}}]}},"styles" {"x" 590,"y" 274}},{"nodeid" "2389baa9-db45-4eb3-a40c-1166bf1e620f","nodever" "1 0","nodetype" "constant","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {"value" {"datatype" "datatype primitive afjsonobject","datavalue" {"hue" 55,"saturation" 55}}},"styles" {"x" 675,"y" 440}},{"nodeid" "b2ba65ab-5e3e-4615-8d3a-79015a03d7bc","nodever" "1 0","nodetype" "capabilitycommand","isstateful" true,"group" null,"inputports" {"device" {"nodes" [],"portinfo" null},"1 temperature" {"nodes" ["4d02fcda-df99-4c75-8b0a-73bb67933acd"],"portinfo" {"datatypes" ["undefined"],"minitems" 1,"maxitems" 1,"iscustomport" true}}},"triggerports" {"success" {"nodes" [],"portinfo" null},"failure" {"nodes" [],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"commands" {"datatype" "datatype util aflist","datavalue" [{"datatype" "datatype schema afcapabilitycommand","datavalue" {"component" "main","capability" "colortemperature","command" "setcolortemperature","arguments" [{"datatype" "datatype schema afcommandargument","datavalue" {"name" "temperature","optional" false,"datatype" "datatype primitive afinteger"}}]}}]}},"styles" {"x" 1115,"y" 380}},{"nodeid" "4d02fcda-df99-4c75-8b0a-73bb67933acd","nodever" "1 0","nodetype" "constant","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {"value" {"datatype" "datatype primitive afinteger","datavalue" 500}},"styles" {"x" 975,"y" 478}}] rewire the graph as follows a delete the wire that connects command switch node's success port and response success node's trigger port b connect the command switch node's success port to the command colorcontrol node's trigger port c connect the command colortemperature node's success port to the response success node's trigger port d connect the numerical comparison node's false port to the response success node's trigger port noteadd a constant node with time zone, for example america/new_york, as string value if you want to test this section based on your local time click align then, click try it to see how the light bulb color change based on time you're done! congratulations! you have successfully achieved the goal of this code lab now, you can control a smart light bulb using bixby home studio if you face any trouble, you may download this file control bulb complete code 25 72 kb notewatch this short clip to quickly know how to navigate your way in this code lab and to see how easy it is to use bixby home studio to learn more about bixby, visit developer samsung com/bixby
Learn Code Lab
codelabmatter create a virtual device and make an open source contribution objective learn how to create a matter virtual device, which you can control using the smartthings app also, know how to contribute your code to matter open source overview matter is an open-source connectivity standard for smart home and internet of things iot devices it is a secure, reliable, and seamless cross-platform protocol for connecting compatible devices and systems with one another smartthings provides the matter virtual device app and smartthings home apis to help you quickly develop matter devices and use the smartthings ecosystem without needing to build your own iot ecosystem you can use smartthings home apis to onboard, control, remove, and share all matter devices when building your application other iot ecosystems can use the matter devices onboarded on your iot app through the multi-admin function notethis code lab focuses only on creating a matter virtual device you can control using the smartthings app to learn how to make your controller app, see build a matter iot app with smartthings home apis for detailed information, go to partners smartthings com/matter set up your environment you will need the following host pc running on windows 10 or higher or ubuntu 20 04 x64 android studio latest version recommended java se development kit jdk 11 or later devices connected on the same network mobile device with android 8 0 oreo or higher operating system os mobile device with smartthings app installed matter-enabled smartthings station onboarded with samsung account used for smartthings app initial setup turn on developer mode and enable usb debugging option on your mobile device install a few os-specific dependencies by entering the below command in your terminal window $ sudo apt-get install git gcc g++ pkg-config libssl-dev libdbus-1-dev \ libglib2 0-dev libavahi-client-dev ninja-build python3-venv python3-dev \ python3-pip unzip libgirepository1 0-dev libcairo2-dev libreadline-dev to build the matter virtual device app, install sdk platform 26 and ndk version 22 1 7171670 using sdk manager in android studio after installing ndk, register the ndk path to the env path export android_ndk_home=[ndk path] export path=$path ${android_ndk_home} install kotlin compiler kotlinc version 1 5 10 after installing kotlinc, register the kotlinc path to the env path export kotlinc_home=[kotlinc path]/bin export path=$path ${kotlinc_home} sample code here is a sample code for you to start coding in this codelab download it and start your learning experience! matter virtual device sample code 11 42 mb start your project after downloading the sample code containing the project files, open your android studio and click open to open an existing project locate the downloaded android project from the directory and click ok select and create the device type when you build and run the sample matter virtual device app, you can see the already added on/off switch aside from the switch, other types of devices you can create are already prepared in the sample app noterefer to the matter device library specification for the list of matter devices you can create go to feature > main > java > com matter virtual device app feature main in the mainfragment kt file, select the device type you want to create mainuistate start -> { // =================================================================================== // codelab // todo uncomment the following lines to add your own device type // ----------------------------------------------------------------------------------- val itemlist = listof device onoffswitch, // sample // device occupancysensor, // level 1 8+ mins // device contactsensor, // level 2 8+ mins // device videoplayer, // level 2 10+ mins // device doorlock, // level 3 15+ mins // device extendedcolorlight, // level 3 15+ mins // device windowcovering, // level 4 17+ mins // device thermostat, // level 5 20+ mins // =================================================================================== depending on the device type you selected at this step, the part you need to modify at the next step will vary the level of modification complexity is assigned per each device get cluster value clusters are the functional building block elements of the data model a cluster can be an interface, a service, or an object class, and it is the lowest independent functional element in the data model a matter device supports a set of appropriate clusters, which can interact with your preferred controller such as smartthings this allows for easy information retrieval, behavior setting, event notifications, and more through the viewmodel, get the value of the cluster used in the device you created noteto learn more about clusters, see matter application cluster specification occupancy sensorlevel 1 file path feature > sensor > java > com matter virtual device app feature sensor file name occupancysensorviewmodel kt // =================================================================================== // codelab level 1 // the current status of the occupancy the boolean value is used by the [occupancyfragment] // to react to update ui // todo 1 uncomment the following code blocks // ----------------------------------------------------------------------------------- //private val _occupancy stateflow<boolean> = getoccupancyflowusecase //val occupancy livedata<boolean> // get = _occupancy aslivedata // =================================================================================== // =================================================================================== // codelab level 1 // the current status of the battery the int value is used by the [occupancyfragment] // to react to update fragment's ui // todo 2 uncomment the following code blocks // ----------------------------------------------------------------------------------- //private val _batterystatus mutablestateflow<int> = // getbatpercentremainingusecase as mutablestateflow<int> //val batterystatus livedata<int> // get = _batterystatus aslivedata // =================================================================================== // =================================================================================== // codelab level 1 // triggered by the "occupancy" button in the [occupancyfragment] // [setoccupancyusecase] will update the boolean value of the new occupancy status // todo 3 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodelscope launch { // timber d "current value = ${_occupancy value}" // if _occupancy value { // timber d "set value = false" // setoccupancyusecase false // } else { // timber d "set value = true" // setoccupancyusecase true // } //} // =================================================================================== // =================================================================================== // codelab level 1 // triggered by the "battery" seekbar in the [occupancyfragment] // [batterystatus] store the current status of the battery to indicate the progress // todo 4 uncomment the following code blocks // ----------------------------------------------------------------------------------- //_batterystatus value = progress // =================================================================================== // =================================================================================== // codelab level 1 // triggered by the "battery" seekbar in the [occupancyfragment] // [updatebatteryseekbarprogress] update the current status of the battery to indicate the // progress // [setbatpercentremainingusecase] will update the int value of the new battery status // todo 5 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodelscope launch { // updatebatteryseekbarprogress progress // setbatpercentremainingusecase progress //} // =================================================================================== contact sensorlevel 2 file path feature > sensor > java > com matter virtual device app feature sensor file name contactsensorviewmodel kt // =================================================================================== // codelab level 2 // the current status of the contact the boolean value is used by the [contactsensorfragment] // to react to update ui // todo 1 uncomment the following code blocks // ----------------------------------------------------------------------------------- //private val _statevalue stateflow<boolean> = getstatevalueflowusecase //val statevalue livedata<boolean> // get = _statevalue aslivedata // =================================================================================== // =================================================================================== // codelab level 2 // the current status of the battery the int value is used by the [contactsensorfragment] // to react to update fragment's ui // todo 2 uncomment the following code blocks // ----------------------------------------------------------------------------------- //private val _batterystatus mutablestateflow<int> = // getbatpercentremainingusecase as mutablestateflow<int> //val batterystatus livedata<int> // get = _batterystatus aslivedata // =================================================================================== // =================================================================================== // codelab level 2 // triggered by the "contact" button in the [contactsensorfragment] // [setstatevalueusecase] will update the boolean value of the new contact status // todo 3 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodelscope launch { // timber d "current value = ${_statevalue value}" // if _statevalue value { // timber d "set value = false" // setstatevalueusecase false // } else { // timber d "set value = true" // setstatevalueusecase true // } //} // =================================================================================== // =================================================================================== // codelab level 2 // triggered by the "battery" seekbar in the [contactsensorfragment] // [batterystatus] store the current status of the battery to indicate the progress // todo 4 uncomment the following code blocks // ----------------------------------------------------------------------------------- //_batterystatus value = progress // =================================================================================== // =================================================================================== // codelab level 2 // triggered by the "battery" seekbar in the [contactsensorfragment] // [updatebatteryseekbarprogress] update the current status of the battery to indicate the // progress // [setbatpercentremainingusecase] will update the int value of the new battery status // todo 5 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodelscope launch { // updatebatteryseekbarprogress progress // setbatpercentremainingusecase progress //} // =================================================================================== video playerlevel 2 file path feature > media > java > com matter virtual device app feature media file name videoplayerviewmodel kt // =================================================================================== // codelab level 2 // the current status of the on/off the boolean value is used by the [videoplayerfragment] // to react to update fragment's ui // todo 1 uncomment the following code blocks // ----------------------------------------------------------------------------------- //private val _onoff stateflow<boolean> = getonoffflowusecase //val onoff livedata<boolean> // get = _onoff aslivedata // =================================================================================== // =================================================================================== // codelab level 2 // the current status of the playback state the int value is used by the [videoplayerfragment] // to react to update fragment's ui // todo 2 uncomment the following code blocks // ----------------------------------------------------------------------------------- //private val _playbackstate stateflow<int> = getplaybackstateflowusecase //val playbackstate livedata<int> // get = _playbackstate aslivedata // =================================================================================== // =================================================================================== // codelab level 2 // the current status of the playback speed the int value is used by the [videoplayerfragment] // to react to update fragment's ui // todo 3 uncomment the following code blocks // ----------------------------------------------------------------------------------- //private val _playbackspeed stateflow<int> = getplaybackspeedflowusecase //val playbackspeed livedata<int> // get = _playbackspeed aslivedata // =================================================================================== // =================================================================================== // codelab level 2 // the current status of the key code the enum value is used by the [videoplayerfragment] // to react to update fragment's ui // todo 4 uncomment the following code blocks // ----------------------------------------------------------------------------------- //private val _keycode stateflow<keycode> = getkeycodestateflowusecase //val keycode livedata<keycode> // get = _keycode aslivedata // =================================================================================== // =================================================================================== // codelab level 2 // triggered by the "on/off" button in the [videoplayerfragment] // [setonoffusecase] will update the boolean value of the new on/off status // todo 5 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodelscope launch { // timber d "current value = ${_onoff value}" // if _onoff value { // timber d "set value = false" // setonoffusecase false // } else { // timber d "set value = true" // setonoffusecase true // } //} // =================================================================================== door locklevel 3 file path feature > closure > java > com matter virtual device app feature closure file name doorlockviewmodel kt // =================================================================================== // codelab level 3 // the current status of the lock the boolean value is used by the [doorlockfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 1 copy code below private val _lockstate stateflow<boolean> = getlockstateflowusecase val lockstate livedata<boolean> get = _lockstate aslivedata // ============================================================================== // =================================================================================== // codelab level 3 // the current status of the battery the int value is used by the [doorlockfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 2 copy code below private val _batterystatus mutablestateflow<int> = getbatpercentremainingusecase as mutablestateflow<int> val batterystatus livedata<int> get = _batterystatus aslivedata // ============================================================================== // =================================================================================== // codelab level 3 // triggered by the "lock" button in the [doorlockfragment] // [setlockstateusecase] will update the boolean value of the new lock status // ----------------------------------------------------------------------------------- // todo 3 copy code below viewmodelscope launch { timber d "current lockstate value = ${_lockstate value}" if _lockstate value == lock_state_locked { timber d "set value = unlocked" setlockstateusecase lock_state_unlocked } else { timber d "set value = locked" setlockstateusecase lock_state_locked } } // ============================================================================== // =================================================================================== // codelab level 3 // triggered by the "send alarm" button in the [doorlockfragment] // [sendlockalarmeventusecase] will send alarm event // [setlockstateusecase] will update the boolean value of the unlock status // ----------------------------------------------------------------------------------- // todo 4 copy code below viewmodelscope launch { if !_lockstate value { // if lockstate == locked, send alarm event and change the lockstate to unlocked sendlockalarmeventusecase setlockstateusecase lock_state_unlocked } } // ============================================================================== // =================================================================================== // codelab level 3 // triggered by the "battery" seekbar in the [doorlockfragment] // [batterystatus] store the current status of the battery to indicate the progress // ----------------------------------------------------------------------------------- // todo 5 copy code below _batterystatus value = progress // ============================================================================== // =================================================================================== // codelab level 3 // triggered by the "battery" seekbar in the [doorlockfragment] // [updatebatteryseekbarprogress] update the current status of the battery to indicate the // progress // [setbatpercentremainingusecase] will update the int value of the new battery status // ----------------------------------------------------------------------------------- // todo 6 copy code below viewmodelscope launch { updatebatteryseekbarprogress progress setbatpercentremainingusecase progress } // ============================================================================== extended color lightlevel 3 file path feature > lighting > java > com matter virtual device app feature lighting file name extendedcolorlightviewmodel kt // =================================================================================== // codelab level 3 // the current status of the on/off the boolean value is used by the [extendedcolorlightfragment] // to react to update ui // ----------------------------------------------------------------------------------- // todo 1 copy code below private val _onoff stateflow<boolean> = getonoffflowusecase val onoff livedata<boolean> get = _onoff aslivedata // =================================================================================== // =================================================================================== // codelab level 3 // the current status of the color level the int value is used by the // [extendedcolorlightfragment] // to react to update ui // ----------------------------------------------------------------------------------- // todo 2 copy code below private val _level stateflow<int> = getlevelflowusecase val level livedata<int> get = _level aslivedata // =================================================================================== // =================================================================================== // codelab level 3 // the current status of the color the enum value is used by the [extendedcolorlightfragment] // to react to update ui // ----------------------------------------------------------------------------------- // todo 3 copy code below private val _currenthue stateflow<int> = getcurrenthueflowusecase private val _currentsaturation stateflow<int> = getcurrentsaturationflowusecase val currentcolor livedata<hsvcolor> = combine _currenthue, _currentsaturation { currenthue, currentsaturation -> hsvcolor currenthue, currentsaturation } aslivedata // =================================================================================== // =================================================================================== // codelab level 3 // the current status of the color temperature the int value is used by the // [extendedcolorlightfragment] // to react to update ui // ----------------------------------------------------------------------------------- // todo 4 copy code below private val _colortemperature stateflow<int> = getcolortemperatureflowusecase val colortemperature livedata<int> get = _colortemperature aslivedata // =================================================================================== // =================================================================================== // codelab level 3 // triggered by the "on/off" button in the [extendedcolorlightfragment] // [setonoffusecase] will update the boolean value of the new on/off status // ----------------------------------------------------------------------------------- // todo 5 copy code below viewmodelscope launch { timber d "current value = ${_onoff value}" if _onoff value { timber d "set value = false" setonoffusecase false } else { timber d "set value = true" setonoffusecase true } } // =================================================================================== window coveringlevel 4 file path feature > closure > java > com matter virtual device app feature closure file name windowcoveringviewmodel kt // =================================================================================== // codelab level 4 // the current status of the position/operation the enum value is used by the // [windowcoveringfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 1 copy code below val windowcoveringstatus livedata<windowcoveringstatus> = combine _currentposition, _operationalstatus { currentposition, operationalstatus -> windowcoveringstatus currentposition, operationalstatus } aslivedata // =================================================================================== // =================================================================================== // codelab level 4 // the current status of the battery the int value is used by the [windowcoveringfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 2 copy code below private val _batterystatus mutablestateflow<int> = getbatpercentremainingusecase as mutablestateflow<int> val batterystatus livedata<int> get = _batterystatus aslivedata // =================================================================================== // =================================================================================== // codelab level 4 // triggered by the "windowshade" seekbar in the [windowcoveringfragment] // [settargetpositionusecase] will update the int value of the new target position status // ----------------------------------------------------------------------------------- // todo 3 copy code below viewmodelscope launch { timber d "target position = $percentage" settargetpositionusecase percentage } // =================================================================================== // =================================================================================== // codelab level 4 // triggered by the "open" button in the [fragment_window_covering xml] // [settargetpositionusecase] will update the int value of the open position 100 status // ----------------------------------------------------------------------------------- // todo 4 copy code below viewmodelscope launch { timber d "target position = 100" settargetpositionusecase 100 } // =================================================================================== // =================================================================================== // codelab level 4 // triggered by the "close" button in the [fragment_window_covering xml] // [settargetpositionusecase] will update the int value of the close position 0 status // ----------------------------------------------------------------------------------- // todo 5 copy code below viewmodelscope launch { settargetpositionusecase 0 } // =================================================================================== // =================================================================================== // codelab level 4 // triggered by the "pause" button in the [fragment_window_covering xml] // [settargetpositionusecase] will update the int value of the pause position status // ----------------------------------------------------------------------------------- // todo 6 copy code below viewmodelscope launch { timber d "current position = ${_currentposition value}, target position ${_targetposition value}" if _currentposition value != _targetposition value { settargetpositionusecase _currentposition value } } // =================================================================================== // =================================================================================== // codelab level 4 // triggered by the "battery" seekbar in the [windowcoveringfragment] // [batterystatus] store the current status of the battery to indicate the progress // ----------------------------------------------------------------------------------- // todo 7 copy code below _batterystatus value = progress // =================================================================================== // =================================================================================== // codelab level 4 // triggered by the "battery" seekbar in the [windowcoveringfragment] // [updatebatteryseekbarprogress] update the current status of the battery to indicate the // progress // [setbatpercentremainingusecase] will update the int value of the new battery status // ----------------------------------------------------------------------------------- // todo 8 copy code below viewmodelscope launch { updatebatteryseekbarprogress progress setbatpercentremainingusecase progress } // =================================================================================== thermostatlevel 5 file path feature > hvac > java > com matter virtual device app feature hvac file name thermostatviewmodel kt // =================================================================================== // codelab level 5 // the current status of the temperature the int value is used by the [thermostatfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 1 copy code below private val _temperature mutablestateflow<int> = getlocaltemperatureusecase as mutablestateflow<int> val temperature livedata<int> get = _temperature aslivedata // =================================================================================== // =================================================================================== // codelab level 5 // the current status of the humidity the int value is used by the [thermostatfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 2 copy code below private val _humidity mutablestateflow<int> = getrelativehumidityusecase as mutablestateflow<int> val humidity livedata<int> get = _humidity aslivedata // =================================================================================== // =================================================================================== // codelab level 5 // the current status of the system mode the enum value is used by the [thermostatfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 3 copy code below private val _systemmode stateflow<thermostatsystemmode> = getsystemmodeflowusecase val systemmode livedata<thermostatsystemmode> get = _systemmode aslivedata // =================================================================================== // =================================================================================== // codelab level 5 // the current status of the fan mode the enum value is used by the [thermostatfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 4 copy code below private val _fanmode stateflow<fancontrolfanmode> = getfanmodeflowusecase val fanmode livedata<fancontrolfanmode> get = _fanmode aslivedata // =================================================================================== // =================================================================================== // codelab level 5 // the current status of the cooling setpoint the int value is used by the [thermostatfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 5 copy code below private val _occupiedcoolingsetpoint stateflow<int> = getoccupiedcoolingsetpointflowusecase val occupiedcoolingsetpoint livedata<int> get = _occupiedcoolingsetpoint aslivedata // =================================================================================== // =================================================================================== // codelab level 5 // the current status of the heating setpoint the int value is used by the [thermostatfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 6 copy code below private val _occupiedheatingsetpoint stateflow<int> = getoccupiedheatingsetpointflowusecase val occupiedheatingsetpoint livedata<int> get = _occupiedheatingsetpoint aslivedata // =================================================================================== // =================================================================================== // codelab level 5 // the current status of the battery the int value is used by the [thermostatfragment] // to react to update fragment's ui // ----------------------------------------------------------------------------------- // todo 7 copy code below private val _batterystatus mutablestateflow<int> = getbatpercentremainingusecase as mutablestateflow<int> val batterystatus livedata<int> get = _batterystatus aslivedata // =================================================================================== // =================================================================================== // codelab level 5 // triggered by the "humidity" seekbar in the [thermostatfragment] // [humidity] store the current status of the humidity to indicate the progress // ----------------------------------------------------------------------------------- // todo 8 copy code below _humidity value = progress * 100 // =================================================================================== // =================================================================================== // codelab level 5 // triggered by the "humidity" seekbar in the [thermostatfragment] // [updatehumidityseekbarprogress] update the current status of the humidity to indicate the // progress // [setrelativehumidityusecase] will update the int value of the new humidity status [0 100] // * 100 // ----------------------------------------------------------------------------------- // todo 9 copy code below viewmodelscope launch { updatehumidityseekbarprogress progress setrelativehumidityusecase progress * 100 } // =================================================================================== // =================================================================================== // codelab level 5 // triggered by the "temperature" seekbar in the [thermostatfragment] // [temperature] store the current status of the temperature to indicate the progress // ----------------------------------------------------------------------------------- // todo 10 copy code below _temperature value = progress * 100 // =================================================================================== // =================================================================================== // codelab level 5 // triggered by the "temperature" seekbar in the [thermostatfragment] // [updatetemperatureseekbarprogress] update the current status of the temperature to indicate // the progress // [setlocaltemperatureusecase] will update the int value of the new temperature status // [value] * 100 // ----------------------------------------------------------------------------------- // todo 11 copy code below viewmodelscope launch { updatetemperatureseekbarprogress progress setlocaltemperatureusecase progress * 100 } // ==================================================================================== // =================================================================================== // codelab level 5 // triggered by the "battery" seekbar in the [thermostatfragment] // [batterystatus] store the current status of the battery to indicate the progress // ----------------------------------------------------------------------------------- // todo 12 copy code below _batterystatus value = progress // ==================================================================================== // =================================================================================== // codelab level 5 // triggered by the "battery" seekbar in the [thermostatfragment] // [updatebatteryseekbarprogress] update the current status of the battery to indicate the // progress // [setbatpercentremainingusecase] will update the int value of the new battery status // ----------------------------------------------------------------------------------- // todo 13 copy code below viewmodelscope launch { updatebatteryseekbarprogress progress setbatpercentremainingusecase progress } // ==================================================================================== // =================================================================================== // codelab level 5 // triggered by the "systemmode" popup in the [thermostatfragment] // [setsystemmodeusecase] will update the enum value of the new system mode status // ----------------------------------------------------------------------------------- // todo 14 copy code below viewmodelscope launch { setsystemmodeusecase systemmode } // ==================================================================================== // =================================================================================== // codelab level 5 // triggered by the "fanmode" popup in the [thermostatfragment] // [setfanmodeusecase] will update the enum value of the new fan mode status // ----------------------------------------------------------------------------------- // todo 15 copy code below viewmodelscope launch { setfanmodeusecase fanmode } // ==================================================================================== // =================================================================================== // codelab level 5 // triggered by the "heating plus" button in the [fragment_thermostat xml] // [setoccupiedheatingsetpointusecase] will update the int value of the +1 degree [degree] * // 100 // ----------------------------------------------------------------------------------- // todo 16 copy code below viewmodelscope launch { val nextvalue = _occupiedheatingsetpoint value + 100 timber d "current value = ${_occupiedheatingsetpoint value} set value = $nextvalue" setoccupiedheatingsetpointusecase nextvalue } // ==================================================================================== // =================================================================================== // codelab level 5 // triggered by the "heating minus" button in the [fragment_thermostat xml] // [setoccupiedheatingsetpointusecase] will update the int value of the -1 degree [degree] * // 100 // ----------------------------------------------------------------------------------- // todo 17 copy code below viewmodelscope launch { val nextvalue = _occupiedheatingsetpoint value - 100 timber d "current value = ${_occupiedheatingsetpoint value} set value = $nextvalue" setoccupiedheatingsetpointusecase nextvalue } // ==================================================================================== // =================================================================================== // codelab level 5 // triggered by the "cooling plus" button in the [fragment_thermostat xml] // [setoccupiedcoolingsetpointusecase] will update the int value of the +1 degree [degree] * // 100 // ----------------------------------------------------------------------------------- // todo 18 copy code below viewmodelscope launch { val nextvalue = _occupiedcoolingsetpoint value + 100 timber d "current value = ${_occupiedcoolingsetpoint value} set value = $nextvalue" setoccupiedcoolingsetpointusecase nextvalue } // ==================================================================================== // =================================================================================== // codelab level 5 // triggered by the "cooling minus" button in the [fragment_thermostat xml] // [setoccupiedcoolingsetpointusecase] will update the int value of the -1 degree [degree] * // 100 // ----------------------------------------------------------------------------------- // todo 19 copy code below viewmodelscope launch { val nextvalue = _occupiedcoolingsetpoint value - 100 timber d "current value = ${_occupiedcoolingsetpoint value} set value = $nextvalue" setoccupiedcoolingsetpointusecase nextvalue } // ==================================================================================== noteyou can find related files in android studio by going to edit menu> find > find in files and entering the keyword "codelab" observe cluster value next, use the observe function to keep track whenever there is a change in the cluster value occupancy sensorlevel 1 file path feature > sensor > java > com matter virtual device app feature sensor file name occupancysensorfragment kt // =================================================================================== // codelab level 1 // trigger the processing for updating new occupancy state of the virtual device // todo 1 uncomment the following code blocks // ----------------------------------------------------------------------------------- //binding occupancybutton setonclicklistener { viewmodel onclickbutton } // =================================================================================== // =================================================================================== // codelab level 1 // [onprogresschanged] will update the fragment's ui via viewmodel livedata // [onstoptrackingtouch] will trigger the processing for updating new battery state of the // virtual device // todo 2 uncomment the following code blocks // ----------------------------------------------------------------------------------- //binding occupancysensorbatterylayout titletext text = getstring r string battery //binding occupancysensorbatterylayout seekbardata = // seekbardata progress = viewmodel batterystatus //binding occupancysensorbatterylayout seekbar setonseekbarchangelistener // object seekbar onseekbarchangelistener { // override fun onprogresschanged seekbar seekbar, progress int, fromuser boolean { // viewmodel updatebatteryseekbarprogress progress // } // // override fun onstarttrackingtouch seekbar seekbar {} // // override fun onstoptrackingtouch seekbar seekbar { // viewmodel updatebatterystatustocluster seekbar progress // } // } // // =================================================================================== // =================================================================================== // codelab level 1 // observer on the current occupancy status and react on the fragment's ui // todo 3 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodel occupancy observe viewlifecycleowner { // if it { // binding occupancyvaluetext text = getstring r string occupancy_state_occupied // binding occupancybutton setimageresource r drawable ic_occupied // } else { // binding occupancyvaluetext text = getstring r string occupancy_state_unoccupied // binding occupancybutton setimageresource r drawable ic_unoccupied // } //} // =================================================================================== // =================================================================================== // codelab level 1 // observer on the current battery status and react on the fragment's ui // todo 4 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodel batterystatus observe viewlifecycleowner { // val text string = getstring r string battery_format, it // binding occupancysensorbatterylayout valuetext text = // html fromhtml text, html from_html_mode_legacy //} // =================================================================================== contact sensorlevel 2 file path feature > sensor > java > com matter virtual device app feature sensor file name contactsensorfragment kt // =================================================================================== // codelab level 2 // trigger the processing for updating new contact state of the virtual device // todo 1 uncomment the following code blocks // ----------------------------------------------------------------------------------- //binding contactbutton setonclicklistener { viewmodel onclickbutton } // =================================================================================== /** battery layout */ // =================================================================================== // codelab level 2 // [onprogresschanged] will update the fragment's ui via viewmodel livedata // [onstoptrackingtouch] will trigger the processing for updating new battery state of the // virtual device // todo 2 uncomment the following code blocks // ----------------------------------------------------------------------------------- //binding contactsensorbatterylayout titletext text = getstring r string battery //binding contactsensorbatterylayout seekbardata = seekbardata progress = viewmodel batterystatus //binding contactsensorbatterylayout seekbar setonseekbarchangelistener // object seekbar onseekbarchangelistener { // override fun onprogresschanged seekbar seekbar, progress int, fromuser boolean { // viewmodel updatebatteryseekbarprogress progress // } // // override fun onstarttrackingtouch seekbar seekbar {} // // override fun onstoptrackingtouch seekbar seekbar { // viewmodel updatebatterystatustocluster seekbar progress // } // } // // =================================================================================== // =================================================================================== // codelab level 2 // observer on the current contact status and react on the fragment's ui // todo 3 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodel statevalue observe viewlifecycleowner { // if it { // binding contactvaluetext text = getstring r string contact_state_close // binding contactbutton setimageresource r drawable ic_unoccupied // } else { // binding contactvaluetext text = getstring r string contact_state_open // binding contactbutton setimageresource r drawable ic_occupied // } //} // =================================================================================== // =================================================================================== // codelab level 2 // observer on the current battery status and react on the fragment's ui // todo 4 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodel batterystatus observe viewlifecycleowner { // val text string = getstring r string battery_format, it // binding contactsensorbatterylayout valuetext text = // html fromhtml text, html from_html_mode_legacy } // =================================================================================== video playerlevel 2 file path feature > media > java > com matter virtual device app feature media file name videoplayerfragment kt // =================================================================================== // codelab level 2 // [buttondata] observer on the current on/off status and react on the fragment's ui // [onclicklistener] trigger the processing for updating new on/off state of the virtual device // todo 1 uncomment the following code blocks // ----------------------------------------------------------------------------------- //binding videoplayeronofflayout buttondata = // buttondata // onoff = viewmodel onoff, // ontext = r string on_off_switch_power_on, // offtext = r string on_off_switch_power_off // //binding videoplayeronofflayout button setonclicklistener { viewmodel onclickbutton } // =================================================================================== // =================================================================================== // codelab level 2 // observer on the current playback status and react on the fragment's ui // todo 2 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodel playbackstate observe viewlifecycleowner { state -> // val statetext = convertplaybackstatetostring state // timber d "playbackstate $state $statetext " // binding videoplayerstatelayout valuetext text = statetext //} // =================================================================================== // =================================================================================== // codelab level 2 // observer on the current playback speed and react on the fragment's ui // todo 3 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodel playbackspeed observe viewlifecycleowner { speed -> // binding videoplayerspeedlayout valuetext text = speed tostring //} // =================================================================================== // =================================================================================== // codelab level 2 // observer on the current key code and react on the fragment's ui // todo 4 uncomment the following code blocks // ----------------------------------------------------------------------------------- //viewmodel keycode observe viewlifecycleowner { keycode -> // binding videoplayerkeypadlayout valuetext text = keycode value //} // =================================================================================== door locklevel 3 file path feature > closure > java > com matter virtual device app feature closure file name doorlockfragment kt // =================================================================================== // codelab level 3 // [buttondata] observer on the current lock status and react on the fragment's ui // [onclicklistener] trigger the processing for updating new lock state of the virtual device // ----------------------------------------------------------------------------------- // todo 1 copy code below binding doorlockonofflayout buttondata = buttondata onoff = viewmodel lockstate, ontext = r string door_lock_unlocked, offtext = r string door_lock_locked binding doorlockonofflayout button setonclicklistener { viewmodel onclickbutton } // =================================================================================== // =================================================================================== // codelab level 3 // trigger the processing for sending alarm event // ----------------------------------------------------------------------------------- // todo 2 copy code below binding doorlocksendalarmlayout button setonclicklistener { viewmodel onclicksendlockalarmeventbutton } // =================================================================================== // =================================================================================== // codelab level 3 // [onprogresschanged] will update the fragment's ui via viewmodel livedata // [onstoptrackingtouch] will trigger the processing for updating new battery state of the // virtual device // ----------------------------------------------------------------------------------- // todo 3 copy code below binding doorlockbatterylayout titletext text = getstring r string battery binding doorlockbatterylayout seekbardata = seekbardata progress = viewmodel batterystatus binding doorlockbatterylayout seekbar setonseekbarchangelistener object seekbar onseekbarchangelistener { override fun onprogresschanged seekbar seekbar, progress int, fromuser boolean { viewmodel updatebatteryseekbarprogress progress } override fun onstarttrackingtouch seekbar seekbar {} override fun onstoptrackingtouch seekbar seekbar { viewmodel updatebatterystatustocluster seekbar progress } } // =================================================================================== // =================================================================================== // codelab level 3 // observer on the current battery status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 4 copy code below viewmodel batterystatus observe viewlifecycleowner { val text string = getstring r string battery_format, it binding doorlockbatterylayout valuetext text = html fromhtml text, html from_html_mode_legacy } // =================================================================================== extended color lightlevel 3 file path feature > lighting > java > com matter virtual device app feature lighting file name extendedcolorlightfragment kt // =================================================================================== // codelab level 3 // [buttondata] observer on the current on/off status and react on the fragment's ui // [onclicklistener] trigger the processing for updating new on/off state of the virtual device // ----------------------------------------------------------------------------------- // todo 1 copy code below binding extendedcolorlightonofflayout buttondata = buttondata onoff = viewmodel onoff, ontext = r string on_off_switch_power_on, offtext = r string on_off_switch_power_off binding extendedcolorlightonofflayout button setonclicklistener { viewmodel onclickbutton } // =================================================================================== // =================================================================================== // codelab level 3 // observer on the current color level status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 2 copy code below viewmodel level observe viewlifecycleowner { // min 2 1% , max 255 100% val level int = it tofloat / 100 * 255 toint timber d "level $it" // if level value is 0, user can't distinguish the color // so, set it to half value + half of max binding extendedcolorlightcolorlayout colorboard drawable? alpha = level / 2 + 127 } // =================================================================================== // =================================================================================== // codelab level 3 // observer on the current color status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 3 copy code below viewmodel currentcolor observe viewlifecycleowner { hsvcolor -> val rgbcolor int = colorcontrolutil hue2rgb hsvcolor currenthue tofloat , hsvcolor currentsaturation tofloat timber d "currenthue ${hsvcolor currenthue},currentsaturation ${hsvcolor currentsaturation}" timber d "color #${integer tohexstring rgbcolor }" var level int? = binding extendedcolorlightcolorlayout colorboard drawable? alpha if level == null level = 255 timber d "level $level" binding extendedcolorlightcolorlayout colorboard setimagedrawable bitmapdrawable resources, colorcontrolutil colorboard rgbcolor } // =================================================================================== // =================================================================================== // codelab level 3 // observer on the current color temperature status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 4 copy code below viewmodel colortemperature observe viewlifecycleowner { // min 2580k 2577k , max 7050k 7042k val colortemperature int = 1000000 / it val rgbcolor int = colorcontrolutil kelvin2rgb colortemperature timber d "color temperature $colortemperature $it" timber d "color #${integer tohexstring rgbcolor }" binding extendedcolorlightcolorlayout colorboard setimagedrawable bitmapdrawable resources, colorcontrolutil colorboard rgbcolor } // =================================================================================== window coveringlevel 4 file path feature > closure > java > com matter virtual device app feature closure file name windowcoveringfragment kt // =================================================================================== // codelab level 4 // [onprogresschanged] will update the fragment's ui via viewmodel livedata // [onstoptrackingtouch] will trigger the processing for updating new windowshade state of the // virtual device // ----------------------------------------------------------------------------------- // todo 1 copy code below binding windowcoveringwindowshadeseekbar setonseekbarchangelistener object seekbar onseekbarchangelistener { override fun onprogresschanged seekbar seekbar, progress int, fromuser boolean { val targetpercentage = seekbar progress val text string = getstring r string window_covering_window_shade_format, targetpercentage val percentagetextview = binding windowcoveringwindowshadevaluetext percentagetextview text = html fromhtml text, html from_html_mode_legacy } override fun onstarttrackingtouch seekbar seekbar {} override fun onstoptrackingtouch seekbar seekbar { viewmodel stopmotion seekbar progress } } // ======================================================================================================= // =================================================================================== // codelab level 4 // [onprogresschanged] will update the fragment's ui via viewmodel livedata // [onstoptrackingtouch] will trigger the processing for updating new battery state of the // virtual device // ----------------------------------------------------------------------------------- // todo 2 copy code below binding windowcoveringbatterylayout titletext text = getstring r string battery binding windowcoveringbatterylayout seekbardata = seekbardata progress = viewmodel batterystatus binding windowcoveringbatterylayout seekbar setonseekbarchangelistener object seekbar onseekbarchangelistener { override fun onprogresschanged seekbar seekbar, progress int, fromuser boolean { viewmodel updatebatteryseekbarprogress progress } override fun onstarttrackingtouch seekbar seekbar {} override fun onstoptrackingtouch seekbar seekbar { viewmodel updatebatterystatustocluster seekbar progress } } // ======================================================================================================= // =================================================================================== // codelab level 4 // observer on the current position/operation status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 3 copy code below viewmodel windowcoveringstatus observe viewlifecycleowner { status -> timber d "currentposition ${status currentposition},operationalstatus ${status operationalstatus}" binding windowcoveringwindowshadeseekbar progress = status currentposition val text string = getstring r string window_covering_window_shade_format, status currentposition binding windowcoveringwindowshadevaluetext text = html fromhtml text, html from_html_mode_legacy when status operationalstatus { 0 -> { when status currentposition { 0 -> { binding windowcoveringoperationalstatustext settext r string window_covering_closed } 100 -> { binding windowcoveringoperationalstatustext settext r string window_covering_open } else -> { binding windowcoveringoperationalstatustext settext r string window_covering_partially_open } } } 1 -> { binding windowcoveringoperationalstatustext settext r string window_covering_opening } 2 -> { binding windowcoveringoperationalstatustext settext r string window_covering_closing } else -> {} } } // ======================================================================================================= // =================================================================================== // codelab level 4 // observer on the current battery status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 4 copy code below viewmodel batterystatus observe viewlifecycleowner { val text string = getstring r string battery_format, it binding windowcoveringbatterylayout valuetext text = html fromhtml text, html from_html_mode_legacy } // ======================================================================================================= thermostatlevel 5 file path feature > hvac > java > com matter virtual device app feature hvac file name themostatfragment kt // =================================================================================== // codelab level 5 // [onprogresschanged] will update the fragment's ui via viewmodel livedata // [onstoptrackingtouch] will trigger the processing for updating new temperature state of the // virtual device // ----------------------------------------------------------------------------------- // todo 1 copy code below binding thermostattemperatureseekbar setonseekbarchangelistener object seekbar onseekbarchangelistener { override fun onprogresschanged seekbar seekbar, progress int, fromuser boolean { viewmodel updatetemperatureseekbarprogress progress } override fun onstarttrackingtouch seekbar seekbar {} override fun onstoptrackingtouch seekbar seekbar { viewmodel updatetemperaturetocluster seekbar progress } } // =================================================================================== // =================================================================================== // codelab level 5 // [onprogresschanged] will update the fragment's ui via viewmodel livedata // [onstoptrackingtouch] will trigger the processing for updating new humidity state of the // virtual device // ----------------------------------------------------------------------------------- // todo 2 copy code below binding humiditysensorhumidityseekbar setonseekbarchangelistener object seekbar onseekbarchangelistener { override fun onprogresschanged seekbar seekbar, progress int, fromuser boolean { viewmodel updatehumidityseekbarprogress progress } override fun onstarttrackingtouch seekbar seekbar {} override fun onstoptrackingtouch seekbar seekbar { viewmodel updatehumiditytocluster seekbar progress } } // =================================================================================== // =================================================================================== // codelab level 5 // [onprogresschanged] will update the fragment's ui via viewmodel livedata // [onstoptrackingtouch] will trigger the processing for updating new battery state of the // virtual device // ----------------------------------------------------------------------------------- // todo 3 copy code below binding thermostatbatterylayout titletext text = getstring r string battery binding thermostatbatterylayout seekbardata = seekbardata progress = viewmodel batterystatus binding thermostatbatterylayout seekbar setonseekbarchangelistener object seekbar onseekbarchangelistener { override fun onprogresschanged seekbar seekbar, progress int, fromuser boolean { viewmodel updatebatteryseekbarprogress progress } override fun onstarttrackingtouch seekbar seekbar {} override fun onstoptrackingtouch seekbar seekbar { viewmodel updatebatterystatustocluster seekbar progress } } // =================================================================================== // =================================================================================== // codelab level 5 // observer on the current temperature status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 4 copy code below viewmodel temperature observe viewlifecycleowner { val celsiustemp float = it tofloat / 100 val celsiustext string = getstring r string temperature_celsius_format, celsiustemp binding thermostattemperaturecelsiusvaluetext text = html fromhtml celsiustext, html from_html_mode_legacy val fahrenheittemp float = it tofloat / 100 * 9 / 5 + 32 val fahrenheittext string = getstring r string temperature_fahrenheit_format, fahrenheittemp binding thermostattemperaturefahrenheitvaluetext text = html fromhtml fahrenheittext, html from_html_mode_legacy binding thermostattemperatureseekbar progress = celsiustemp toint } // ========================================================================================== // =================================================================================== // codelab level 5 // observer on the current fan mode status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 5 copy code below viewmodel fanmode observe viewlifecycleowner { timber d "fanmode $it" this fanmode = it binding fancontrolfanmodelayout valuetext text = convertfanmodetostring it } // ========================================================================================== // =================================================================================== // codelab level 5 // observer on the current heating setpoint and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 6 copy code below viewmodel occupiedheatingsetpoint observe viewlifecycleowner { val celsiustemp float = it tofloat / 100 val celsiustext string = getstring r string temperature_celsius_format, celsiustemp binding thermostatsettemperatureheatingcelsiusvaluetext text = html fromhtml celsiustext, html from_html_mode_legacy val fahrenheittemp float = it tofloat / 100 * 9 / 5 + 32 val fahrenheittext string = getstring r string temperature_fahrenheit_format, fahrenheittemp binding thermostatsettemperatureheatingfahrenheitvaluetext text = html fromhtml fahrenheittext, html from_html_mode_legacy } // =================================================================================== // =================================================================================== // codelab level 5 // observer on the current cooling setpoint and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 7 copy code below viewmodel occupiedcoolingsetpoint observe viewlifecycleowner { val celsiustemp float = it tofloat / 100 val celsiustext string = getstring r string temperature_celsius_format, celsiustemp binding thermostatsettemperaturecoolingcelsiusvaluetext text = html fromhtml celsiustext, html from_html_mode_legacy val fahrenheittemp float = it tofloat / 100 * 9 / 5 + 32 val fahrenheittext string = getstring r string temperature_fahrenheit_format, fahrenheittemp binding thermostatsettemperaturecoolingfahrenheitvaluetext text = html fromhtml fahrenheittext, html from_html_mode_legacy } // =================================================================================== // =================================================================================== // codelab level 5 // observer on the current system mode status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 8 copy code below viewmodel systemmode observe viewlifecycleowner { timber d "systemmode $it" this systemmode = it binding thermostatsystemmodelayout valuetext text = convertsystemmodetostring it } // =================================================================================== // =================================================================================== // codelab level 5 // observer on the current humidity status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 9 copy code below viewmodel humidity observe viewlifecycleowner { val humidity int = it / 100 val humiditytext string = getstring r string humidity_format, humidity binding humiditysensorhumiditypercentagevaluetext text = html fromhtml humiditytext, html from_html_mode_legacy binding humiditysensorhumidityseekbar progress = humidity } // =================================================================================== // =================================================================================== // codelab level 5 // observer on the current battery status and react on the fragment's ui // ----------------------------------------------------------------------------------- // todo 10 copy code below viewmodel batterystatus observe viewlifecycleowner { val text string = getstring r string battery_format, it binding thermostatbatterylayout valuetext text = html fromhtml text, html from_html_mode_legacy } // =================================================================================== // =================================================================================== // codelab level 5 // trigger the processing for setting system mode // ----------------------------------------------------------------------------------- // todo 11 copy code below alertdialog builder requirecontext settitle r string thermostat_mode setsinglechoiceitems modelist, convertsystemmodetoindex this systemmode { dialog, which -> timber d "thermostat mode set $which ${modelist[which]} " viewmodel setsystemmode convertindextosystemmode which dialog dismiss } setnegativebutton r string cancel, null show // =================================================================================== // =================================================================================== // codelab level 5 // trigger the processing for setting fan mode // ----------------------------------------------------------------------------------- // todo 12 copy code below alertdialog builder requirecontext settitle r string fan_control_fan_mode setsinglechoiceitems modelist, convertfanmodetoindex this fanmode { dialog, which -> timber d "fan mode set $which ${modelist[which]} " viewmodel setfanmode convertindextofanmode which dialog dismiss } setnegativebutton r string cancel, null show // =================================================================================== build and run the virtual device app to build and run your app, follow these steps using a usb cable, connect your mobile device the minimum os requirement is android 8 0 oreo select the sample virtual device app from the run configurations menu in the android studio then, select the connected device in the target device menu click run you can see the device you created in the matter virtual device app onboard and control the virtual device via the smartthings app onboard to onboard the virtual device select and set up the virtual device type you created click save click start to show the qr code for onboarding then, go to the smartthings app and click the + button then, onboard the virtual device by scanning its qr code control by smartthings app in the smartthings app, control the virtual device by using its various functions such as on and off for switch contribute to matter open source optional notethis step is optional, but you can proceed if you want to know how to contribute your code to matter open source to contribute to matter open source, you need to have the latest code therefore, apart from the project files provided by this code lab activity, you should fork and modify the latest code from matter open source project matter follows the "fork-and-pull" model for accepting contributions to do this sign in or sign up to github fork the matter repository by clicking fork on the web ui for each new feature, clone your fork to the local pc and create a working branch $ git clone https //github com/<username>/connectedhomeip git $ git checkout –b <branch-name> before running the build command, source the environment setup script activate sh at the top level this script takes care of downloading gn, ninja, and setting up a python environment with libraries used to build and test $ source scripts/activate sh build the virtual device app using the build_example py $ /scripts/build/build_examples py --target android-arm64-virtual-device-app build add each modified file to include in the commit then, create a commit $ git add <filename1> <filename1> $ git commit –s noteto contribute to the open source, you must check the integrity of the code for this, checking using restyle is recommended push to your github fork $ git push origin <branch-name> then, submit your pull request by clicking contribute > open pull request on the web ui write a description of the problem, change overview, and test then, sign the contributor license agreement cla so a reviewer can automatically be assigned click open pull request tipsee contributing to matter for more information you're done! congratulations! you have successfully achieved the goal of this code lab topic now, you can create a matter-compatible virtual device and contribute your code to matter open source by yourself! if you're having trouble, you may download this file matter virtual device complete code 11 49 mb learn more by going to smartthings matter libraries
We use cookies to improve your experience on our website and to show you relevant advertising. Manage you settings for our cookies below.
These cookies are essential as they enable you to move around the website. This category cannot be disabled.
These cookies collect information about how you use our website. for example which pages you visit most often. All information these cookies collect is used to improve how the website works.
These cookies allow our website to remember choices you make (such as your user name, language or the region your are in) and tailor the website to provide enhanced features and content for you.
These cookies gather information about your browser habits. They remember that you've visited our website and share this information with other organizations such as advertisers.
You have successfully updated your cookie preferences.