• Learn
    • Code Lab
    • Foldables and Large Screens
    • One UI Beta
    • Samsung Developers Podcasts
  • Develop
    • Mobile/Wearable
    • Galaxy GameDev
    • Galaxy Themes
    • Galaxy Watch
    • Health
    • Samsung Blockchain
    • Samsung DeX
    • Samsung IAP
    • Samsung Internet
    • Samsung Pay
    • Samsung Wallet
    • View All
      • Galaxy AR Emoji
      • Galaxy Accessory
      • Galaxy Edge
      • Galaxy Z
      • Galaxy Performance
      • Galaxy FM Radio
      • Galaxy S Pen Remote
      • Galaxy Sensor Extension
      • PENUP
      • Samsung Automation
      • Samsung Neural
      • Samsung TEEGRIS
      • Samsung eSE SDK
      • Galaxy Watch for Tizen
      • Watch Face Studio
      • One UI Watch for Tizen
      • Galaxy Watch Studio Converter
      • Samsung IAP for Galaxy Watch (Tizen)
    • Visual Display
    • Smart TV
    • Smart Hospitality Display
    • Smart Signage
    • Digital Appliance
    • Family Hub
    • Platform
    • Bixby
    • Knox
    • SmartThings
    • Tizen.NET
  • Design
    • Design System
    • One UI
    • One UI Watch
    • Smart TV
  • Distribute
    • Galaxy Store
    • TV Seller Office
    • Galaxy Store Games
    • Samsung Podcasts
  • Support
    • Developer Support
    • Remote Test Lab
    • Issues and Bugs Channel
    • Samsung Android USB Driver
    • Galaxy Emulator Skin
  • Connect
    • Blog
    • News
    • Forums
    • Events
    • Samsung Developer Conference
    • SDC23
    • SDC22
    • SDC21
    • SDC19 and Previous Events
  • Sign In
Top Global Search Form
Recommendation
  • Blog
  • Code Lab
  • Foldable and Large Screen Optimization
  • Forums
  • Galaxy Emulator Skin
  • Galaxy GameDev
  • Health
  • Remote Test Lab
  • Samsung Developer Conference
  • SDC22
  • Watch Face Studio
All Search Form
Recommendation
    Suggestion
      All Search Form
      Filter
      Filter
      Filter
      • ALL
      • DOCS
      • SDK
      • API REFERENCE
      • CODE LAB (9)
      • BLOG
      • NEWS/EVENTS
      • CODE LAB
        api reference code lab blog news/events
      1. Learn
      2. Code Lab

      codelab

      Create a health research app using Samsung Health Stack

      create a health research app using samsung health stack objective create a health research app that collects and processes participant's health data, survey responses, and task results using samsung health stack. overview samsung health stack is an open-source technology stack offering end-to-end solutions for collecting and analyzing data from wearable devices in android and wear os environments. with applications ranging from medical research to clinician services and beyond, this tech stack provides the tools and infrastructure necessary to expedite the development and deployment of health-based studies. the framework includes: samsung health stack app sdk - a software development kit (sdk) for building android and wear os apps capable of collecting data from wearable devices. web portal - a customizable interface for creating surveys, managing team members, tracking participants, and analyzing data. backend services - api endpoints to access and interact with a robust data engine. see samsung health stack descriptions for detailed information. set up your environment you will need the following: installed and running samsung health stack backend system installed samsung health stack web portal firebase private key used during the backend system installation android studio (latest version recommended) android jetpack compose (latest version recommended) samsung galaxy mobile device with health connect app and samsung health app installed samsung galaxy watch synced to the mobile device google account sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! research app sample code (4.09 mb) create a firebase project follow the instructions at firebase.google.com/docs/android/setup to add a firebase project to the firebase account you created during the backend system installation. set applicationid as healthstack.sample and download the resulting google-services.json file from firebase. to learn more, see installing the app sdk - create a firebase project. create a new study sign in to the web portal page you deployed. on the study collection page, click the create new study button. noteonly the account who has team admin role can create a new study. see the role-based access control for more details about the differing levels of access permission granted to different roles. set your study name and logo. then click the continue button to create your study. select the principal investigator role and click the confirm button. the overview page appears like below: to connect your app to the backend system of your web portal, you need to know the id of your study. you can get the study id by opening chrome's developer tools. right-click on the web portal page and select inspect. then, open the network panel. click study settings from the left navigation bar. you can see activities recorded on the network tab. the value after projectid= is the id of the study, which you need to set up in the research app. connect the research app to the backend system in android studio, click open to open the project files of the research app. locate the downloaded android project (codelab-before) from the directory and click ok. copy and paste the downloaded google-services.json from firebase to samples > researchsample module. go to samples > researchsample > res > values, and in the strings.xml file, set the following values to connect the app to the backend system: research_platform_endpoint - backend system’s endpoint, including the port number research_project_id - id of the study created <!-- backend integration --> <string name="research_platform_endpoint">http://you.must.set.backend.url</string> <string name="research_project_id">study_id</string> customize the introduction page and eligibility survey the sample research app already includes introduction page and eligibility survey, which you can customize to align with the objective of your study. to modify the introduction page and eligibility survey questions, go to samples > researchsample > java > healthstack.sample and open the onboardingmodule.kt file. introduction page go to the intromodel constructor within the intro function, and create two introsections as below: overview - "a study on walking over an hour daily versus non-walkers." description - "we want to conduct a study to compare the daily life patterns of people who walk more than an hour each day and those who don't." sections = listof( introsection( "overview", "a study on walking over an hour daily versus non-walkers.", ), introsection( "description", "we want to conduct a study to compare the daily life patterns of people " + "who walk more than an hour each day and those who don’t." ) ) the introduction page would look like as below: eligibility survey part of the onboarding process is asking the participants questions through an eligibility survey to determine their suitability for your study. the eligibility survey consists of three steps: eligibilityintrostep - displays an introduction about the survey eligibilitycheckerstep - displays the eligibility questions eligibilityresultstep - displays the result of the survey based on the answers the eligibilitycheckerstep receives the eligibilityquestions. the questions can be a choicequestionmodel, datatimequestionmodel, or multichoicequestionmodel, depending on the type of survey question model you set. modify the eligibility question pages as below: eligibility question 1 type choicequestionmodel id average_walking_time query how many minutes on average do you spend walking each day? explanation unit: minute candidates listof(0, 30, 60, 90, 120) viewtype slider eligibility question 2 type choicequestionmodel id tracking_device query are you willing to wear a tracking device to monitor your dailywalking activity? candidates listof("yes, i'm willing to use a tracking device", "no, i'm notcomfortable using any tracking device") answer yes, i’m willing to use a tracking device eligibility question 3 type choicequestionmodel id participate query are you available and willing to commit to participating in thestudy for a specified duration? candidates listof("yes, i'm available and willing to commit", "no, i'm notavailable or willing to commit") answer yes, i’m available and willing to commit. private val eligibilityquestions: list<questionmodel<any>> = listof( choicequestionmodel( id = "average_walking_time", query = "how many minutes on average do you spend walking each day?", explanation = "unit: minute", candidates = listof(0, 30, 60, 90, 120), viewtype = slider ), choicequestionmodel( id = "tracking_device", query = "are you willing to wear a tracking device to monitor your daily walking activity?", candidates = listof( "yes, i’m willing to use a tracking device", "no, i’m not comfortable using any tracking device" ), answer = "yes, i’m willing to use a tracking device" ), choicequestionmodel( id = "participate", query = "are you available and willing to commit to participating in the study for a specified duration?", candidates = listof("yes, i’m available and willing to commit", "no, i’m not available or willing to commit"), answer = "yes, i’m available and willing to commit" ) ) you can make a pass condition for each question by setting the answer field. a failed result means the participant is not eligible for the study. after defining eligibility questions, the eligibility survey pages would look like as below: set health data permissions you can request permission to collect health data from your study participants. however, before requesting permissions, your app must first declare them in the manifest. go to researchsample module > res > values. in health_permissions.xml, you can declare permissions to read or write data on health connect for steps, sleepsession, sleepstage, oxygensaturation, and bloodpressure data types. notepermission to read and write heartrate data is already declared in the project. <item>androidx.health.permission.steps.read</item> <item>androidx.health.permission.steps.write</item> <item>androidx.health.permission.sleepsession.read</item> <item>androidx.health.permission.sleepsession.write</item> <item>androidx.health.permission.sleepstage.read</item> <item>androidx.health.permission.sleepstage.write</item> <item>androidx.health.permission.oxygensaturation.read</item> <item>androidx.health.permission.oxygensaturation.write</item> <item>androidx.health.permission.bloodpressure.read</item> <item>androidx.health.permission.bloodpressure.write</item> tipfor more information, see the list of data types and permissions. then, go back to healthstack.sample folder. in researchapplication.kt, request permissions from the participants to collect required health data. val healthdatarequired = listof("heartrate", "sleepsession", "sleepstage", "bloodpressure", "steps", "oxygensaturation") tipsee the list of health data types you can collect on health connect. set sync interval and choose health data to display you can set the sync interval per health data type. however, it is recommended to set a minimum interval of 15 minutes because the app is using android's workmanager. tipto learn more about the workmanager, see periodicworkrequest. in mainactivity.kt, set healthdatasyncspecs as below: health data type sync interval heartrate 15 minutes steps 20 hours sleepsession 1 day sleepstage 1 day oxygensaturation 30 minutes bloodpressure 30 minutes val healthdatasyncspecs = listof( syncmanager.healthdatasyncspec("heartrate", 15, timeunit.minutes), syncmanager.healthdatasyncspec("steps", 20, timeunit.hours), syncmanager.healthdatasyncspec("sleepsession", 1, timeunit.days), syncmanager.healthdatasyncspec("sleepstage", 1, timeunit.days), syncmanager.healthdatasyncspec("oxygensaturation", 30, timeunit.minutes), syncmanager.healthdatasyncspec("bloodpressure", 30, timeunit.minutes), ) you can set which data type to display in the research app. the status card for heart rate is already set to display. to show other status cards, such as sleepsessionstatus, add them to the list of healthdatatodisplay. val healthdatatodisplay = listof(heartratestatus, sleepsessionstatus, taskstatus) run the app, join the study and sync your health data build and run the app on a samsung galaxy mobile device. ensure the samsung health app and health connect app is installed on the device and a galaxy watch is connected. notereset the app to its initial state by clearing its data. go to your phone's settings and then swipe to and tap apps. select or search for the researchsample app. tap storage, tap clear data, and then click ok. in the research app, you can join the study by signing in with your google account after passing the eligibility survey, providing consent, and allowing data access to health connect. the research app shows your heart rate data (bpm) and the time you spent sleeping (hrs) based on the data from your galaxy watch and mobile device. notethe data shows and updates in the app based on the sync interval you set. if you want the heart rate data to display immediately, you can measure your heart rate manually using the galaxy watch. then, click the sync health data button in the research app's settings. check health connect's recent logs if data is not showing or updating. the web portal also displays and processes the data from the research. to see the average heart rate data, go to the overview section. scroll to the participant list table, then click the participant data row. the participant management shows health data collected on average, such as heart rate. create a survey task a survey is a sequence of questions that collect information from the participants in your study. in this step, create a survey task and see the result from the web portal. go to the study management section and expand the task management. open the surveys tab and click the create survey button on the top right corner. set survey title as daily survey. then, write three questions as below: after writing all the survey questions, click the publish button. set the frequency as daily and the publish time as early as possible. then, click the publish button on the bottom right corner. you can find your survey task on the published list. go to the research app and touch the refresh button next to upcoming tasks or today to see the survey you created. answer and complete the survey task. go back to the web portal. click your survey task from the published list. reload the web page or re-login to get the result. you can see the survey report in the responses and analytics tab. create an activity task activities allow researchers to collect specific types of data from users. for this study, add an activity to collect measurements related to manual dexterity. in study management, go to the activities tab and click the create activity button. select motor for the activity category and choose tapping speed. click the create button. click the publish button on the task edit page. set frequency as daily and publish time as early as possible. then, click the publish button. you can find your activity task on the published list. in the research app, touch the refresh button to see the newly added activity. open and perform the activity task. in the web portal, click your activity task from the published list. enter the participant id to see the collected data. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can create your own research app that can collect and process users’ health data, answers to survey and activity task results for research purposes by yourself! to learn more, see samsung health stack.

      https://developer.samsung.com/codelab/health/research-app.html
      1. Learn
      2. Code Lab

      codelab

      Measure skin temperature on Galaxy Watch with Samsung Privileged Health SDK

      measure skin temperature on galaxy watch with samsung privileged health sdk objective create a health app for galaxy watch, operating on wear os powered by samsung, utilizing samsung privileged health sdk to obtain skin temperature measurement results. partnership request in this code lab, you will use a specially prepared mock library. it has limited functionality and uses dummy data instead of real-time data. you will need the full version of the samsung privileged health sdk library to get real values, which is available to samsung partners. apply as a partner by checking out the partner app program for exclusive samsung privileged health sdk access. overview samsung privileged health sdk provides means of accessing and tracking health information contained in the health data storage. its tracking service gives raw and processed sensor data such as accelerometer and body composition data sent by the samsung bioactive sensor. the active sensor of galaxy watch runs powerful health sensors such as photoplethysmogram (ppg), electrocardiogram (ecg), bioelectrical impedance analysis (bia), sweat loss, and spo2. see samsung privileged health sdk descriptions for detailed information. set up your environment you will need the following: galaxy watch5 or newer with updated health platform android studio (latest version recommended) java se development kit (jdk) 17 or later sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! skin temperature tracking sample code (123.64 kb) notethis code lab uses mock library, which has limited functionality with dummy data. data from the mock library is not from the galaxy watch’s real sensor data. you need a full version of the samsung privileged health sdk library to get actual values and it's only available to registered partners. the code lab works using a mock library on the galaxy watch4 or newer, while the official library works using galaxy watch5 or newer. connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that the wi-fi is enabled. from the list of available wi-fi networks, choose and connect to the same one as your pc. turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times. upon successful activation of developer mode, a toast message will display as on the image below. afterwards, developer options will be visible under settings. tap developer options and enable the following options: adb debugging in developer options find wireless debugging turn on wireless debugging check always allow on this network and tap allow go back to developer options and click turn off automatic wi-fi notethere may be differences in settings depending on your one ui version. connect your galaxy watch to android studio go to settings > developer options > wireless debugging and choose pair new device. take note of the wi-fi pairing code, ip address & port. in android studio, go to terminal and type: adb pair <ip address>:<port> <wi-fi pairing code> when prompted, tap always allow from this computer to allow debugging. after successfully pairing, type: adb connect <ip address of your watch>:<port> upon successful connection, you will see the following message in android studio’s terminal: connected to <ip address of your watch> now, you can run the app directly on your watch. turn on developer mode for health platform this step is only applicable to registered partners of samsung privileged health sdk. you can replace priv-health-tracking-mock-2023.aar in app > libs with the real library to receive real sensor data with the application. this requires health platform to be set in developer mode: on your watch go to settings > apps > health platform. quickly tap health platform title for 10 times. this enables developer mode and displays [dev mode] below the title. to stop using developer mode, quickly tap health platform title for 10 times to disable it. 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 (skintemptracking) from the directory and click ok. check tracking capabilities to track the data with the sdk, the device must support skin temperature, like the galaxy watch5. skin temperature tracking can work in 2 modes: batching and on-demand. the tracker type for batching is healthtrackertype.skin_temperature_continuous and healthtrackertype.skin_temperature for on-demand. in this code lab, you are going to use on-demand tracker. in connectionmanager.java, navigate to isskintemperatureavailable() function. use a provided healthtrackingservice object to create a healthtrackercapability instance, and send it to checkavailabletrackers() function, and assign its result to availabletrackers list. gettrackingcapability() returns a healthtrackercapability instance in healthtrackingservice object healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype. public healthtrackercapability gettrackingcapability() provide a healthtrackercapability instance to get a supporting healthtrackertype list. /****************************************************************************************** * [practice 1] check capabilities to confirm skin temperature availability * * ---------------------------------------------------------------------------------------- * * (hint) replace todo 1 with java code * get healthtrackercapability object from healthtrackingservice * send the object to checkavailabletrackers() ******************************************************************************************/ boolean isskintemperatureavailable(healthtrackingservice healthtrackingservice) { if (healthtrackingservice == null) return false; @suppresswarnings("unusedassignment") list<healthtrackertype> availabletrackers = null; //"todo 1" if (availabletrackers == null) return false; else return availabletrackers.contains(healthtrackertype.skin_temperature); } initialization of skin temperature tracker before starting the measurement, initialize the skin temperature tracker by creating a healthtracker object. in skintemperaturelistener.java, navigate to setskintemperaturetracker(). using the provided healthtrackingservice object, create an instance of the healthtracker class of skin_temperature type and assign it to the skintemperaturetracker object. gethealthtracker() with healthtrackertype.skin_temperature as an argument creates a healthtracker instance after a single measurement, the tracker should be stopped when using on-demand measurement. for continuous measurement, use healthtrackertype.skin_temperature_continuous healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype. healthtracker gethealthtracker(healthtrackertype healthtrackertype) create a healthtracker instance for the given healthtrackertype. /******************************************************************************************* * [practice 2] setup skin temperature tracker * * ---------------------------------------------------------------------------------------- * * (hint) replace todo 2 with java code * initialize skintemperaturetracker with proper samsung privileged health sdk functionality * call gethealthtracker() on healthtrackingservice object * use healthtrackertype.skin_temperature as an argument ******************************************************************************************/ void setskintemperaturetracker(healthtrackingservice healthtrackingservice) { //"todo 2" } starting and stopping the tracker for the client app to obtain the data through the sdk, set a listener method on healthtracker. this method is called every time there is new data. healthtrackerhealthtracker enables an application to set an event listener and get tracking data for a specific healthtrackertype. public void seteventlistener(healthtracker.trackereventlistener listener) set an event listener to the healthtracker instance. void starttracker() { if (!ishandlerrunning) { skintemperaturehandler.post(() -> skintemperaturetracker.seteventlistener(skintemperaturelistener)); ishandlerrunning = true; } } after the finished measurement, the on-demand tracker should be stopped. you can do that by unsetting the event listener from healthtracker. healthtrackerhealthtracker enables an application to set an event listener and get tracking data for a specific healthtrackertype. public void unseteventlistener() stop the registered event listener to this healthtracker instance. void stoptracker() { if (skintemperaturetracker != null) skintemperaturetracker.unseteventlistener(); skintemperaturehandler.removecallbacksandmessages(null); ishandlerrunning = false; } process obtained skin temperature data the answer from the healthtrackingservice is asynchronous. the skintemperaturelistener receives the callback containing a data point with all the required information. follow the steps below to get skin temperature data: in skintemperaturelistener.java, go to the updateskintemperature() function and read skin temperature data from datapoint: get skin temperature status using datapoint api (key: valuekey.skintemperatureset.status). get skin temperature value using datapoint api (key: valuekey.skintemperatureset.object_temperature). get ambient temperature value using datapoint api (key: valuekey.skintemperatureset.ambient_temperature) datapointdatapoint provides a map of valuekey and value with a timestamp. public <t>t getvalue(valuekey<t>type) get data value for the given key. private final healthtracker.trackereventlistener skintemperaturelistener = new healthtracker.trackereventlistener() { @override public void ondatareceived(@nonnull list<datapoint> list) { stoptracker(); for (datapoint data : list) { updateskintemperature(data); } } }; /******************************************************************************************* * [practice 3] read values from datapoint object * - get skin temperature status value * - get wrist skin temperature value - it's named "object_temperature" in the library * - get ambient temperature value ------------------------------------------------------------------------------------------- * - (hint) replace todo 3 with parts of code * (1) remove skintemperaturestatus.invalid_measurement and * set status from 'datapoint' object using data.getvalue(valuekey.skintemperatureset.status) * * if status is 'skintemperaturestatus.successful_measurement' then: * (2) set wristskintemperaturevalue from 'datapoint' object using: * data.getvalue(valuekey.skintemperatureset.object_temperature); * (3) set ambienttemperaturevalue from 'datapoint' object using: * data.getvalue(valuekey.skintemperatureset.ambient_temperature); ******************************************************************************************/ void updateskintemperature(datapoint data) { final int status = skintemperaturestatus.invalid_measurement; float wristskintemperaturevalue = 0; float ambienttemperaturevalue = 0; //"todo 3" trackerdatasubject.notifyskintemperaturetrackerobservers(status, ambienttemperaturevalue, wristskintemperaturevalue); } run unit tests for your convenience, you will find an additional unit tests package. this will let you verify your code changes even without using a physical watch. see the instruction below on how to run unit tests: right click on com.samsung.health.skintemptracking (test) and execute run 'tests in 'com.samsung.health.skintemptrackin" command. if you have completed all the tasks correctly, you can see all the unit tests pass successfully. run the app after building the apk, you can run the application on a connected device to measure your skin temperature. once the app starts, allow the app to receive data from the body sensors. afterwards, the screen shows the application. tap the measure button to get your skin temperature. to stop measuring, tap on the stop button. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can create a health app that measures skin temperature by yourself! to learn more about samsung health, visit: developer.samsung.com/health

      https://developer.samsung.com/codelab/health/skin-temperature.html
      1. Learn
      2. Code Lab

      codelab

      Transfer heart rate data from Galaxy Watch to a mobile device with Samsung Privileged Health SDK

      transfer heart rate data from galaxy watch to a mobile device with samsung privileged health sdk objective create a health app for galaxy watch, operating on wear os powered by samsung, to measure heart rate and inter-beat interval (ibi), send data to a paired android phone, and create an android application for receiving data sent from a paired galaxy watch. partnership request in this code lab, you will use a specially prepared mock library. it has limited functionality and uses dummy data instead of real-time data. you will need the full version of the samsung privileged health sdk library to get real values, which is available to samsung partners. apply as a partner by checking out the partner app program for exclusive samsung privileged health sdk access. overview with this code lab, you can measure various health data using samsung privileged health sdk and send it to a paired android mobile device for further processing. using a paired mobile device will make the data more organized by taking advantage of a bigger screen and saving health data to a local database or remote server. see samsung privileged health sdk descriptions for detailed information. set up your environment you will need the following: galaxy watch4 or newer, powered by wear os android mobile device android studio (latest version recommended) java se development kit (jdk) 17 or later sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! heart rate data transfer sample code (196.70 kb) notethis code lab uses mock library, which has limited functionality with dummy data. data from the mock library is not from the galaxy watch’s real sensor data. you need a full version of the samsung privileged health sdk library to get actual values and it's only available to registered partners. connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that the wi-fi is enabled. from the list of available wi-fi networks, choose and connect to the same one as your pc. turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times. upon successful activation of developer mode, a toast message will display as on the image below. afterwards, developer options will be visible under settings. tap developer options and enable the following options: adb debugging in developer options find wireless debugging turn on wireless debugging check always allow on this network and tap allow go back to developer options and click turn off automatic wi-fi notethere may be differences in settings depending on your one ui version. connect your galaxy watch to android studio go to settings > developer options > wireless debugging and choose pair new device. take note of the wi-fi pairing code, ip address & port. in android studio, go to terminal and type: adb pair <ip address>:<port> <wi-fi pairing code> when prompted, tap always allow from this computer to allow debugging. after successfully pairing, type: adb connect <ip address of your watch>:<port> upon successful connection, you will see the following message in the terminal: connected to <ip address of your watch> now, you can run the app directly on your watch. turn on developer mode for health platform this step is only applicable to registered partners of samsung privileged health sdk. you can replace priv-health-tracking-mock-2023.aar in app > libs with the real library to receive real sensor data with the application. this requires health platform to be set in developer mode: on your watch go to settings > apps > health platform. quickly tap health platform title for 10 times. this enables developer mode and displays [dev mode] below the title. to stop using developer mode, quickly tap health platform title for 10 times to disable it. set up your android device click on the following links to setup your android device: enable developer options run apps on a hardware device connect the galaxy watch with you samsung mobile phone start your project after downloading the sample code containing the project files, in android studio click open to open an existing project. locate the downloaded android project (hrdatatransfer-code-lab) from the directory and click ok. parse data from the watch after opening the sample project, you need to parse the ibi data collected while tracking the heart rate-related data. the updatelistener collects datapoint instances from the watch, which contains a collection of valuekey objects. those objects contain heart rate, ibi values, and ibi statuses. there's always one value for heart rate while the number of ibi values vary from 0-4. both ibi value and ibi status lists have the same size. go to the wear > java > data > com.samsung.health.hrdatatransfer. under ibidataparsing.kt, provide the implementation for the function below: /******************************************************************************* * [practice 1] get list of valid inter-beat interval values from a datapoint * - return arraylist<int> of valid ibi values (validibilist) * - if no ibi value is valid, return an empty arraylist * * var ibivalues is a list representing ibivalues (up to 4) * var ibistatuses is a list of their statuses (has the same size as ibivalues) ------------------------------------------------------------------------------- * - (hints) * use local function: isibivalid(status, value) to check validity of ibi * ****************************************************************************/ fun getvalidibilist(datapoint: datapoint): arraylist<int> { val ibivalues = datapoint.getvalue(valuekey.heartrateset.ibi_list) val ibistatuses = datapoint.getvalue(valuekey.heartrateset.ibi_status_list) val validibilist = arraylist<int>() //todo 1 return validibilist } check data sending capabilities for the watch once the heart rate tracker can collect data, set it up so it can send data to a paired android mobile device. first, check if the devices within range have proper capabilities. the capability data type is a string and is used when sending a message on both devices. go to the wear > java > com.samsung.health.hrdatatransfer > data. in capabilityrepositoryimpl.kt, and fill in the function below: /************************************************************************************** * [practice 2] check capabilities for reachable remote nodes (devices) * - return a set of node objects out of all capabilities represented by 2nd function * argument, having the capability represented by 1st function argument. * - return empty set if no node has the capability -------------------------------------------------------------------------------------- * - (hints) * you might want to use filtervalues function on the given allcapabilities map * ***********************************************************************************/ override suspend fun getnodesforcapability( capability: string, allcapabilities: map<node, set<string>> ): set<node> { //todo 2 } the purpose of this exercise is to identify which nodes have the exact capability you are looking for (represented by capability argument). you need those nodes later to send the message to them. encode message for the watch before sending the results of the heart rate and ibi to the paired mobile device, you need to encode the message into a string. go to the wear > java > com.samsung.health.hrdatatransfer > domain. in sendmessageusecase.kt, fill in the function below and use json format to encode the list of results (arraylist<trackeddata>) into a string: /*********************************************************************** * [practice 3] - encode heart rate & inter-beat interval into string * - encode function argument (trackeddata) into json format. * - return the encoded string ----------------------------------------------------------------------- * - (hint) * use json.encodetostring function **********************************************************************/ fun encodemessage(trackeddata: arraylist<trackeddata>): string { //todo 3 } run unit tests for your convenience, you will find an additional unit tests package. this will let you verify your code changes even without using a physical watch or mobile device. see the instruction below on how to run unit tests: right click on com.samsung.health.hrdatatransfer (test), and execute run 'tests in 'com.samsung.health.hrdatatransfer" command. do the same step with the mobile module. if you have completed all the tasks correctly, you will see all the unit tests pass successfully. run the app after building the apks, you can run the applications on your watch to measure heart rate and ibi values, and on your mobile device to collect the data from your watch. once the app starts, allow the app to receive data from the body sensors. afterwards, it shows the application's main screen. to get the heart rate and ibi values, tap the start button. tap the send button to send the data to your mobile device. notethe watch keeps last ~40 values of heart rate and ibi. you’re done! congratulations! you have successfully achieved the goal of this code lab. now, you can create a health app on a watch to measure heart rate and ibi, and develop a mobile app that receives that health data! to learn more about samsung health, visit: developer.samsung.com/health

      https://developer.samsung.com/codelab/health/heart-rate-data-transfer.html
      1. Learn
      2. Code Lab

      codelab

      Measure Blood Oxygen Level on Galaxy Watch

      measure blood oxygen level on galaxy watch objective create a health app for galaxy watch, operating on wear os powered by samsung, utilizing samsung privileged health sdk to trigger and obtain blood oxygen level (spo2) measurement results. partnership request in this code lab, you will use a specially prepared mock library. it has limited functionality and uses dummy data instead of real-time data. to get real values, you will need the full version of the samsung privileged health sdk library, which is available to registered samsung partners. apply as a partner by checking out the partner app program to get exclusive access to the samsung privileged health sdk. overview samsung privileged health sdk provides means of accessing and tracking health information contained in the health data storage. its tracking service gives raw and processed sensor data such as accelerometer and body composition data sent by the samsung bioactive sensor. the latest bioactive sensor of galaxy watch runs powerful health sensors such as photoplethysmogram (ppg), electrocardiogram (ecg), bioelectrical impedance analysis (bia), sweat loss, and spo2. see samsung privileged health sdk descriptions for detailed information. set up your environment you will need the following: galaxy watch4 or newer android studio (latest version recommended) java se development kit (jdk) 11 or later sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! measuring blood oxygen level sample code (122.49 kb) connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that wi-fi is enabled. from the list of available wi-fi networks, choose and connect to the same one as your pc. turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times. upon successful activation of developer mode, a toast message will display as on the image below. afterwards, developer options will be visible under settings. tap developer options and enable the following options: adb debugging in developer options find wireless debugging turn on wireless debugging check always allow on this network and tap allow go back to developer options and click turn off automatic wi-fi notethere may be differences in settings depending on your one ui version. connect your galaxy watch to android studio go to settings > developer options > wireless debugging and choose pair new device. take note of the wi-fi pairing code, ip address & port. in android studio, go to terminal and type: adb pair <ip address>:<port> <wi-fi pairing code> when prompted, tap always allow from this computer to allow debugging. after successfully pairing, type: adb connect <ip address of your watch>:<port> upon successful connection, you will see the following message in android studio’s terminal: connected to <ip address of your watch> now, you can run the app directly on your watch. turn on developer mode for health platform this step is only applicable to registered partners of samsung privileged health sdk. you can replace priv-health-tracking-mock-2023.aar in app/libs with the real library to receive real sensor data with the application. this requires health platform to be set in developer mode: on your watch go to settings > apps > health platform. quickly tap health platform title for 10 times. this enables developer mode and displays [dev mode] below the title. to stop using developer mode, quickly tap health platform title for 10 times to disable it. start your project after downloading the sample code containing the project files, in android studio click open to open existing project. locate the downloaded android project from the directory and click ok. check capabilities for the device to track data with the samsung privileged health sdk, it must support a given tracker type – blood oxygen level. to check this, get the list of available tracker types and verify that the tracker is on the list. in the connectionmanager.java file, navigate to the isspo2available() function, use a provided healthtrackingservice object to create a healthtrackercapability instance, send it to the checkavailabletrackers function, and assign its result to the availabletrackers list. gettrackingcapability() returns a healthtrackercapability instance in the healthtrackingservice object healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype. public healthtrackercapability gettrackingcapability() provide a healthtrackercapability instance to get a supporting health tracker type list. /****************************************************************************************** * [practice 1] check capabilities to confirm spo2 availability * * ---------------------------------------------------------------------------------------- * * (hint) replace todo 1 with java code * get healthtrackercapability object from healthtrackingservice * send the object to checkavailabletrackers() ******************************************************************************************/ public boolean isspo2available(healthtrackingservice healthtrackingservice) { if (healthtrackingservice == null) return false; list<healthtrackertype> availabletrackers = null; //"todo 1" if (availabletrackers == null) return false; else return availabletrackers.contains(healthtrackertype.spo2); } check connection error resolution using samsung privileged health sdk api, resolve any error when connecting to health tracking service. in the connectionmanager.java file, navigate to the processtrackerexception() function, and check if the provided healthtrackerexception object has a resolution. assign the result to hasresolution variable. hasresolution() function in the healthtrackerexception object checks if the api can fix the error healthtrackerexceptionhealthtrackerexception contains error codes and checks the error's resolution. if there is a resolution, solving the error is available by calling resolve(activity). boolean hasresolution() checks whether the given error has a resolution. /******************************************************************************************* * [practice 2] resolve healthtrackerexception error * * ----------------------------------------------------------------------------------------- * * (hint) replace todo 2 with java code * call hasresolution() on healthtrackerexception object ******************************************************************************************/ public void processtrackerexception(healthtrackerexception e) { boolean hasresolution = false; //"todo 2" if (hasresolution) e.resolve(callingactivity); if (e.geterrorcode() == healthtrackerexception.old_platform_version || e.geterrorcode() == healthtrackerexception.package_not_installed) observerupdater.getobserverupdater().notifyconnectionobservers(r.string.novalidhealthplatform); else observerupdater.getobserverupdater().notifyconnectionobservers(r.string.connectionerror); log.e(tag, "could not connect to health tracking service: " + e.getmessage()); } initialize spo2 tracker before the measurement starts, initialize the spo2 tracker by obtaining the proper health tracker object. in the spo2listener.java file, navigate to the init() function. using the provided healthtrackingservice object, create an instance of the spo2 tracker and assign it to the spo2tracker object. gethealthtracker() with healthtrackertype.spo2 as an argument will create a healthtracker instance healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype. healthtracker gethealthtracker(healthtrackertype healthtrackertype) provides a healthtracker instance for the given healthtrackertype. /******************************************************************************************* * [practice 3] initialize spo2 tracker * * ---------------------------------------------------------------------------------------- * * (hint) replace todo 3 with java code * initialize spo2tracker with proper samsung privileged health sdk functionality * call gethealthtracker() on healthtrackingservice object * use healthtrackertype.spo2 as an argument ******************************************************************************************/ void init(healthtrackingservice healthtrackingservice) { //"todo 3" } perform measurement for the client app to start obtaining the data through the sdk, it has to set a listener method on the healthtracker. the application setups the listener when the user taps on the measure button. each time there is new data, the listener callback receives it. after the measurement is completed, the listener has to be disconnected. due to battery drain, on-demand measurement should not last more than 30 seconds. the measurement is cancelled if the final value is not delivered in time. note that the sensor needs a few seconds to warm up and provide correct values, which adds to the overall measurement time. the blood oxygen level values come in the ondatareceived callback of trackereventlistener. in spo2listener.java file, you can see the code for reading the value: private final healthtracker.trackereventlistener spo2listener = new healthtracker.trackereventlistener() { @override public void ondatareceived(@nonnull list<datapoint> list) { for (datapoint data : list) { updatespo2(data); } } }; private void updatespo2(datapoint data) { int status = data.getvalue(valuekey.spo2set.status); int spo2value = 0; if (status == measurement_completed) spo2value = data.getvalue(valuekey.spo2set.spo2); observerupdater.getobserverupdater().notifytrackerobservers(status, spo2value); } run unit tests for your convenience, you can find an additional unit tests package. this lets you verify your code changes even without using a physical watch. see instructions below on how to run unit tests: right click on com.samsung.health.spo2tracking (test) and execute run 'tests in 'com.samsung.health.spo2tracking'' command. if you completed all the tasks correctly, you can see that all the unit tests passed successfully. run the app after building the apk, you can run the application on a connected device to measure blood oxygen level. right after the app is started, it requests for user permission. allow the app to receive data from the body sensors. afterwards, it shows the application's main screen. to get the blood oxygen level, tap on the measure button. to stop the measurement, tap on the stop button. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can create a health app that measures blood oxygen level by yourself! if you're having trouble, you may download this file: measuring blood oxygen level complete code (117.81 kb) to learn more about samsung health, visit: developer.samsung.com/health

      https://developer.samsung.com/codelab/health/blood-oxygen.html
      1. Learn
      2. Code Lab

      codelab

      Measure Blood Oxygen Level and Heart Rate on Galaxy Watch

      measure blood oxygen level and heart rate on galaxy watch objective create a health app for galaxy watch, operating on wear os powered by samsung, utilizing samsung privileged health sdk to trigger and obtain results of simultaneous blood oxygen level (spo2) and heart rate measurements. partnership request in this code lab, you will use a specially prepared mock library. it has limited functionality and uses dummy data instead of real-time data. to get real values, you will need the full version of the samsung privileged health sdk library, which is available to samsung partners. apply as a partner by checking out the partner app program to get exclusive access to the samsung privileged health sdk. overview samsung privileged health sdk provides means of accessing and tracking health information contained in the health data storage. its tracking service gives raw and processed sensor data such as accelerometer and body composition data sent by the samsung bioactive sensor. the latest bioactive sensor of galaxy watch runs powerful health sensors such as photoplethysmogram (ppg), electrocardiogram (ecg), bioelectrical impedance analysis (bia), sweat loss, and spo2. see samsung privileged health sdk descriptions for detailed information. set up your environment you will need the following: galaxy watch4 or newer android studio (latest version recommended) java se development kit (jdk) 11 or later sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! measuring blood oxygen level and heart rate sample code (135.23 kb) connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that wi-fi is enabled. from the list of available wi-fi networks, choose and connect to the same one as your pc. turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times. upon successful activation of developer mode, a toast message will display as on the image below. afterwards, developer options will be visible under settings. tap developer options and enable the following options: adb debugging in developer options find wireless debugging turn on wireless debugging check always allow on this network and tap allow go back to developer options and click turn off automatic wi-fi notethere may be differences in settings depending on your one ui version. connect your galaxy watch to android studio go to settings > developer options > wireless debugging and choose pair new device. take note of the wi-fi pairing code, ip address & port. in android studio, go to terminal and type: adb pair <ip address>:<port> <wi-fi pairing code> when prompted, tap always allow from this computer to allow debugging. after successfully pairing, type: adb connect <ip address of your watch>:<port> upon successful connection, you will see the following message in android studio’s terminal: connected to <ip address of your watch> now, you can run the app directly on your watch. turn on developer mode for health platform this step is only applicable to registered partners of samsung privileged health sdk. you can replace priv-health-tracking-mock-2023.aar in app/libs with the real library to receive real sensor data with the application. this requires health platform to be set in developer mode: on your watch go to settings > apps > health platform. quickly tap health platform title for 10 times. this enables developer mode and displays [dev mode] below the title. to stop using developer mode, quickly tap health platform title for 10 times to disable it. start your project after downloading the sample code containing the project files, in android studio click open to open existing project. locate the downloaded android project from the directory and click ok. establish service connection and check capabilities for the device to track data with the samsung privileged health sdk, it must connect to the service by healthtrackingservice api. after establishing a connection, verify if the required tracker type is available. to check this, get the list of available tracker types and verify that the tracker is on the list. in this code lab, you will utilize blood oxygen level and heart rate trackers. the healthtrackingservice api usage is in the table below. healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype. public void connectservice() establish a connection with samsung's health tracking service. public void disconnectservice() release a connection for samsung's health tracking service. public healthtrackercapability gettrackingcapability() provide a healthtrackercapability instance to get a supporting health tracker type list. initialize multiple trackers before the measurement starts, initialize the spo2 tracker by obtaining the proper health tracker object. in the connectionmanager.java file, navigate to initspo2(), create an oxygen saturation healthtracker instance, and pass it to the spo2listener instance. get the healthtracker object using the healthtrackingservice api. use the healthtrackertype.spo2 type as parameter. healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype. public healthtracker gethealthtracker(healthtrackertype healthtrackertype) provide a healthtracker instance for the given healthtrackertype. pass the healthtracker object to the spo2listener instance object. spo2listener public void sethealthtracker(healthtracker tracker) set healthtracker instance for the given tracker. /******************************************************************************************* * [practice 1] create blood oxygen level health tracker object * - get health tracker object * - pass it to spo2listener ------------------------------------------------------------------------------------------- * - (hint) replace todo 1 with parts of code * (1) get healthtracker object using healthtrackingservice.gethealthtracker() * use healthtrackertype.spo2 type as parameter * (2) pass it to spo2listener using sethealthtracker function ******************************************************************************************/ public void initspo2(spo2listener spo2listener) { //"todo 1 (1)" //"todo 1 (2)" sethandlerforbaselistener(spo2listener); } next, in the connectionmanager.java file, in the initheartrate() function, create a heart rate healthtracker instance, and pass it to the heartratelistener instance. get the healthtracker object using the healthtrackingservice api. use the healthtrackertype.heart_rate type as parameter. pass the healthtracker object to the heartratelistener instance object. heartratelistener public void sethealthtracker(healthtracker tracker) set healthtracker instance for the given tracker. /******************************************************************************************* * [practice 2] create heart rate health tracker object * - get health tracker object * - pass it to heartratelistener ------------------------------------------------------------------------------------------- * - (hint) replace todo 2 with parts of code * (1) get healthtracker object using healthtrackingservice.gethealthtracker() * use healthtrackertype.heart_rate type as parameter * (2) pass it to heartratelistener using sethealthtracker function ******************************************************************************************/ public void initheartrate(heartratelistener heartratelistener) { //"todo 2 (1)" //"todo 2 (2)" sethandlerforbaselistener(heartratelistener); } start and stop trackers for the client app to start obtaining the data through the sdk, set a listener method on healthtracker. this method will be called every time there is new data. after the measurement completes, the listener has to be disconnected. to start measurement in the baselistener.java file, navigate to starttracker() function, and set trackereventlistener as listener healthtracker object. set an event listener on healthtracker object using healthtracking api. use the healthtracker.trackereventlistener object instance as parameter. healthtrackerhealthtracker enables an application to set an event listener and get tracking data for a specific healthtrackertype. public void seteventlistener(healthtracker.trackereventlistener listener) set an event listener to this healthtracker instance. /******************************************************************************************* * [practice 3] start health tracker by setting event listener * - set event listener on health tracker ------------------------------------------------------------------------------------------- * - (hint) replace todo 3 with parts of code * set event listener on healthtracker object using healthtracker.seteventlistener() * use trackereventlistener object as parameter ******************************************************************************************/ public void starttracker() { log.i(app_tag, "starttracker called "); log.d(app_tag, "healthtracker: " + healthtracker.tostring()); log.d(app_tag, "trackereventlistener: " + trackereventlistener.tostring()); if (!ishandlerrunning) { handler.post(() -> { //"todo 3" sethandlerrunning(true); }); } } to stop measurement, unset the trackereventlistener from the healthtracker object in the stoptracker() function. unset the event listener on healthtracker object using healthtracking api. healthtrackerhealthtracker enables an application to set an event listener and get tracking data for a specific healthtrackertype. public void unseteventlistener() stop the registered event listener to this healthtracker instance. /******************************************************************************************* * [practice 4] stop health tracker by removing event listener * - unset event listener on health tracker ------------------------------------------------------------------------------------------- * - (hint) replace todo 4 with parts of code * unset event listener on healthtracker object using healthtracker.unseteventlistener() ******************************************************************************************/ public void stoptracker() { log.i(app_tag, "stoptracker called "); log.d(app_tag, "healthtracker: " + healthtracker.tostring()); log.d(app_tag, "trackereventlistener: " + trackereventlistener.tostring()); if (ishandlerrunning) { //"todo 4" sethandlerrunning(false); handler.removecallbacksandmessages(null); } } process obtained and batching data the response from the platform will be asynchronous with the results you want to obtain. follow the steps below to get blood oxygen level and heart rate data. in the spo2listener.java file, navigate to updatespo2() function, and read spo2 data from datapoint: get the oxygen saturation status using the datapoint api (key: valuekey.spo2set.status). get the oxygen saturation value using the datapoint api (key: valuekey.spo2set.spo2). datapointdatapoint provides a map of valuekeyand value with a timestamp. public <t>t getvalue(valuekey<t> type) get data value for the given key. /******************************************************************************************* * [practice 5] read values from datapoint object * - get blood oxygen level status * - get blood oxygen level value ------------------------------------------------------------------------------------------- * - (hint) replace todo 5 with parts of code * (1) remove spo2status.calculating and * set status from 'datapoint' object using datapoint.getvalue(valuekey.spo2set.status) * (2) set spo2value from 'datapoint' object using datapoint.getvalue(valuekey.spo2set.spo2) * if status is 'spo2status.measurement_completed' ******************************************************************************************/ public void updatespo2(datapoint datapoint) { int status = spo2status.calculating; //"todo 5 (1)" int spo2value = 0; //"todo 5 (2)" trackerdatanotifier.getinstance().notifyspo2trackerobservers(status, spo2value); log.d(app_tag, datapoint.tostring()); } in the heartratelistener.java file, navigate to readvaluesfromdatapoint() function, and read the heart rate data from datapoint: get heart rate status using datapoint api (key: valuekey.heartrateset.heart_rate_status). get heart rate value using datapoint api (key: valuekey.heartrateset.heart_rate). get heart rate ibi value using datapoint api (key: valuekey.heartrateset.ibi_list). get ibi quality using datapoint api (key: valuekey.heartrateset.ibi_status_list). /******************************************************************************************* * [practice 6] read values from datapoint object * - get heart rate status * - get heart rate value * - get heart rate ibi value * - check retrieved heart rate’s ibi and ibi quality values ------------------------------------------------------------------------------------------- * - (hint) replace todo 6 with parts of code * (1) set hrdata.status from 'datapoint' object using datapoint.getvalue(valuekey.heartrateset.heart_rate_status) * (2) set hrdata.hr from 'datapoint' object using datapoint.getvalue(valuekey.heartrateset.heart_rate) * (3) set local variable 'list<integer> hribilist' using datapoint.getvalue(valuekey.heartrateset.ibi_list) * (4) set local variable 'final list<integer> hribistatus' using datapoint.getvalue(valuekey.heartrateset.ibi_status_list) * (5) set hrdata.ibi with the last of 'hribilist' values * (6) set hrdata.qibi with the last of 'hribistatus' values ******************************************************************************************/ public void readvaluesfromdatapoint(datapoint datapoint) { heartratedata hrdata = new heartratedata(); //"todo 6 (1)" //"todo 6 (2)" //"todo 6 (3)" //"todo 6 (4)" //"todo 6 (5)" //"todo 6 (6)" trackerdatanotifier.getinstance().notifyheartratetrackerobservers( hrdata); log.d(app_tag, datapoint.tostring()); } run unit tests for your convenience, you can find an additional unit tests package. this lets you verify your code changes even without using a physical watch. see instructions below on how to run unit tests: right click on com.samsung.health.multisensortracking (test) and execute run 'tests in 'com.samsung.health.multisensortracking'' command. if you completed all the tasks correctly, you can see that all the unit tests passed successfully. run the app after building the apk, you can run the application on a connected device to see blood oxygen level and heart rate values. right after the app is started, it requests for user permission. allow the app to receive data from the body sensors. afterwards, it shows the application's main screen and automatically display the heart rate. to get the blood oxygen level (spo2) value, tap on the measure button. to stop the measurement, tap on the stop button. tap on the details label to see more heart rate data. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can create a health app that measures blood oxygen level and heart rate by yourself! if you're having trouble, you may download this file: measuring blood oxygen level and heart rate complete code (134.82 kb) to learn more about samsung health, visit: developer.samsung.com/health

      https://developer.samsung.com/codelab/health/blood-oxygen-heart-rate.html
      1. Learn
      2. Code Lab

      codelab

      Create a Daily Step Counter on Galaxy Watch

      create a daily step counter on galaxy watch objective create a native app for galaxy watch, operating on wear os powered by samsung, using health platform to read your daily steps. overview health platform provides a unified and straightforward way for accessing a wide range of health and wellness related data. with health platform api, you may easily read and write data stored in health platform on android and wear os powered by samsung. applications can have access to these secured data only with explicit user consent. additionally, users may disable access to the data at any point in time. see health platform descriptions for detailed information. set up your environment you will need the following: galaxy watch4 or newer android studio (latest version recommended) java se development kit (jdk) 11 or later sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! health step count sample code (119.87 kb) turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times. upon successful activation of developer mode, a toast message will display as on the image below. afterwards, developer options will be visible under settings. tap developer options and enable the following options: adb debugging debug over wi-fi turn off automatic wi-fi connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that wi-fi is enabled. from the list of available wi-fi networks, choose and connect to the same one as your pc. when successfully connected, tap a wi-fi network name, swipe down, and note the ip address. you will need this to connect your watch over adb from your pc. connect your galaxy watch to android studio in android studio, go to terminal and type: adb connect <ip address as mentioned in previous step> when prompted, tap always allow from this computer to allow debugging. upon successful connection, you will see the following message in android studio’s terminal: connected to <ip address of your watch> now, you can run the app directly on your watch. start your project after downloading the sample code containing the project files, in android studio click open to open existing project. locate the downloaded android project (stepcount) from the directory and click ok. check dependency and app manifest in the dependencies section of stepcount/app/build.gradle file, see the appropriate dependency for health platform. dependencies { implementation com.google.android.libraries.healthdata:health-data-api:1.0.0-alpha01' // ... } notelibrary might update from time to time. if necessary, choose the version suggested by android studio. request for data permissions before accessing any data through health platform, the client app must obtain necessary permissions from the user. in permissions.java, create a permission instance to trigger relevant permission screen and obtain required consent from end user. data type name: intervaldatatypes.steps read access: accesstype.read /******************************************************************************************* * [practice 1] build permission object grand permissions for read today's steps * - set interval data type of steps * - set read access type ------------------------------------------------------------------------------------------- * - (hint) uncomment lines below and fill todos with * (1) for interval data type: intervaldatatypes.steps * (2) for read access: accesstype.read ******************************************************************************************/ permission stepsreadpermission = permission.builder() //.setdatatype("todo 1 (1)") //.setaccesstype("todo 1 (2)") .build(); make a query to aggregate today’s steps create read request with all necessary information to read data through health platform api. the answer from the platform will be asynchronous with the result from which you can get all the data you are interested in. follow the steps below to get today's steps count: in stepsreader.java, create a readaggregateddatarequest with cumulativeaggregationspec instance: data type name: intervaldatatypes.steps /******************************************************************************************* * [practice 2] build read aggregated data request object for read today's steps * - set interval data type of steps ------------------------------------------------------------------------------------------- * - (hint) uncomment line below and fill todo 2 with * (1) for interval data type: intervaldatatypes.steps ******************************************************************************************/ readaggregateddatarequest readaggregateddatarequest = readaggregateddatarequest.builder() .settimespec( timespec.builder() .setstartlocaldatetime(localdatetime.now().with(localtime.midnight)) .build()) //.addcumulativeaggregationspec(cumulativeaggregationspec.builder("todo 2 (1)").build()) .build(); read cumulative steps count from cumulativedata: set variable steps value to 0l. it is the count of daily steps. get aggregatedvalue object using cumulativedata api. cumulativedataaggregateddata representing total of intervaldata over a period of time (e.g. total steps in a day). public aggregatedvalue gettotal () check the result. if it is not null, get aggregated value using aggregatedvalue api: aggregatedvaluevalue fields aggregated over a period of time. only numeric fields (longfield, doublefield) can be included in aggregation. public long getlongvalue () returns all longfields and their values that are already set. add value to the daily steps result counter. /******************************************************************************************* * [practice 3] read aggregated value from cumulative data and add them to the result * - get aggregatedvalue from cumulativedata object * - get steps count from aggregatedvalue object ------------------------------------------------------------------------------------------- * - (hint) uncomment lines below and replace todo 3 with parts of code * (1) get aggregatedvalue object 'obj' using cumulativedata.gettotal() * (2) get value using obj.getlongvalue() and add to the result ******************************************************************************************/ long steps = 0l; if(result != null) { list<cumulativedata> cumulativedatalist = result.getcumulativedatalist(); if (!cumulativedatalist.isempty()) { for(cumulativedata cumulativedata : cumulativedatalist) { //"todo 3 (1)" //"todo 3 (2)" } } } return steps; run unit tests for your convenience, you will find an additional unit tests package. this will let you verify your code changes even without using a physical watch. see instruction below on how to run unit tests: right click on com.samsung.sdc21.stepcount (test) and execute run 'tests in 'com.samsung.sdc21.stepcount'' command. if you completed all the tasks correctly, you will see all the unit tests passed successfully. run the app after building the apk, you can run the application on a connected device to see real-life aggregated steps count measured by a smartwatch. right after the app is started, it will request for the user permission. allow the app to receive data of the activity. afterwards, the application main screen will be shown. it will automatically display today’s step count. tap on refresh button to read current steps count from health platform. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can create a daily step counter app by yourself! if you're having trouble, you may download this file: health step count complete code (119.79 kb) learn more by going to health platform.

      https://developer.samsung.com/codelab/health/daily-step-counter.html
      1. Learn
      2. Code Lab

      codelab

      Track Deadlift Exercise on Galaxy Watch

      track deadlift exercise on galaxy watch objective create a native app for galaxy watch, operating on wear os powered by samsung, using health services to track deadlift exercise. this app measures repetition count, calories burned, and time spent during the exercise. overview health services provides a simple and unified way for accessing a wide range of health and wellness related data. with health services api, you will no longer need to develop your own algorithms processing sensors data in order to compute metrics like heart rate, steps counts, distance, calories burned, and other more. these are now accessible through health services embedded on wearables operating on wear os powered by samsung. see health platform descriptions for detailed information. set up your environment you will need the following: galaxy watch4 or newer android studio (latest version recommended) java se development kit (jdk) 11 or later sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! health track deadlift sample code (132.83 kb) turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times. upon successful activation of developer mode, a toast message will display as on the image below. afterwards, developer options will be visible under settings. tap developer options and enable the following options: adb debugging debug over wi-fi turn off automatic wi-fi connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that wi-fi is enabled. from the list of available wi-fi networks, choose and connect to the same one as your pc. when successfully connected, tap a wi-fi network name, swipe down, and note the ip address. you will need this to connect your watch over adb from your pc. connect your galaxy watch to android studio in android studio, go to terminal and type: adb connect <ip address as mentioned in previous step> when prompted, tap always allow from this computer to allow debugging. upon successful connection, you will see the following message in android studio’s terminal: connected to <ip address of your watch> now, you can run the app directly on your watch. 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 (deadlift) from the directory and click ok. check dependency and app manifest in the dependencies section of gradle scripts > build.gradle (module :app) file, see the appropriate dependency for health services. dependencies { implementation 'androidx.health:health-services-client:1.0.0-beta03' // ... } notesince the library might update from time to time, it is recommended to choose the version suggested by android studio. in androidmanifest.xml file, note the following: <queries> element <queries> <package android:name="com.google.android.wearable.healthservices" /> </queries> section with requests for necessary permissions <uses-permission android:name="android.permission.body_sensors" /> <uses-permission android:name="android.permission.activity_recognition" /> check capabilities to check what can be measured during an exercise, you need to check its capabilities. go to app > java > com.samsung.sdc21.deadlift. open the deadliftutil.java file and navigate to the checkcapabilities() method. an inner class c definition implements the methods of the futurecallback interface. within this definition, define the onsuccess() method to retrieve the exercise type capabilities: public void onsuccess(exercisecapabilities result) { objects.requirenonnull(result); log.i(tag, "got exercise capabilities"); /*********************************************************************************** * [practice 1] define the onsuccess() method * * - (hint) uncomment lines below and replace todo 1 * call getexercisetypecapabilities() method of result object, * passing already initialized t as an argument: **********************************************************************************/ final exercisetype t = exercisetype.deadlift; // final exercisetypecapabilities capabilities = "todo 1" // final exerciseconfig.builder builder = exerciseconfig.builder(t); // builder.setdatatypes(capabilities.getsupporteddatatypes()); // exerciseconfigbuilder = builder; } next, implement the findcapabilitesfuture() method to get a callback with exercisecapabilities: getcapabilitiesasync() returns the exercisecapabilities of the exerciseclient for the device. static listenablefuture<exercisecapabilities> findcapabilitiesfuture( exerciseclient client) { /******************************************************************************************* * [practice 1] create a listenablefuture object that will get a callback with * with exercise capabilities. choose the correct method from exerciseclient * * - (hint) uncomment line and replace null with todo 2 * for checking capabilities use getcapabilitiesasync() method. ******************************************************************************************/ return null; //"todo 2"; } start the exercise inside the startexercise() method, there is a call to the futures.addcallback() method. this method adds a callback function that executes when the asynchronous operation of starting the exercise completes. set an update callback for the exercise client within the onsuccess() method of the callback function: public void onsuccess(void result) { log.i(tag, "successfully started"); /*************************************************************************** * [practice 2] set an update callback * * - (hint) uncomment lines below and fill todos: * (1) make appropriate call of setupdatecallback method * and pass exerciseupdatelistener object as an argument * (2) change ismeasurementrunning flag value to true **************************************************************************/ // exerciseclient.setupdatecallback("todo 3 (1)"); log.i(tag, "successfully set update listener"); // "todo 3 (2)" } in the deadlift.java file, call the startexercise() method in onbuttonclickhelper(): public void onbuttonclickhelper() { /******************************************************************************************* * [practice 2] start the exercise using a method from deadliftutil.java * * - (hint) uncomment line below and fill todo 4: * call startexercise() method on util object: * ****************************************************************************************/ // "todo 4" } get the results go to the deadliftutil.java file, and in the getnewrepsvalue() method, call the getlatestmetrics() method from the exerciseupdate class to get the data collected during the exercise. store the data in the resultlist, where the last element holds the most up-to-date value of all your repetitions. public long getnewrepsvalue(exerciseupdate update, deltadatatype<long, intervaldatapoint<long>> datatype) { /******************************************************************************************* * [practice 3] get the data collected during exercise * * - (hint) uncomment lines below and fill todo 5 * call getlatestmetrics() method of exerciseupdate object. * then, get the data of appropriate type. * for this, you can use dedicated method getdata(), passing datatype as an argument * ****************************************************************************************/ // final list<intervaldatapoint<long>> resultlist = "todo 5" // if (!resultlist.isempty()) { // final int lastindex = resultlist.size() - 1; // return resultlist.get(lastindex).getvalue(); // } return no_new_value; } run unit tests for your convenience, you will find an additional unit tests package. this will let you verify your code changes even without using a physical watch. see instruction below on how to run unit tests: right click on com.samsung.sdc21.deadlift (test) > deadliftunittest and execute run 'deadliftunittest' command. if you completed all the tasks correctly, you will see all the unit tests passed successfully. run the app after building the apk, you can run the application on a connected device to measure actual deadlift parameters. right after the app is started, it will request for the user permission. allow the app to receive data of the activity. afterwards, the application main screen will be shown. before doing deadlifts, press the start button to track your exercise. when done, tap on the stop button. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can create a deadlift exercise tracker app by yourself! if you're having trouble, you may download this file: health track deadlift complete code (132.42 kb) learn more by going to health platform.

      https://developer.samsung.com/codelab/health/deadlift-tracker.html
      1. Learn
      2. Code Lab

      codelab

      Create a Watch Face Using Tag Expressions

      create a watch face using tag expressions objective learn how to create a watch face that responds based on the date, time, step count, heart rate, and battery level using tag expressions in watch face studio. in this code lab, you will create a basic watch face with complications such as step count, heart rate, and battery level. later, you will improve its functionalities and make it visually dynamic using tag expressions. overview watch face studio is a graphic authoring tool that enables you to create watch faces for wear os. it offers a simple and intuitive way to add images and components, and to configure the watch movement without any coding. watch face studio supports watch faces for the galaxy watch4 or newer version, and other watch devices that run on the same platform. tag expressions are conditions in watch face studio that allows you to customize watch face through dynamic configuration of its movement and data. set up your environment you will need the following: watch face studio galaxy watch4 or newer any supported wear os watch start your project create a new project and input project name. a blank studio will show upon clicking ok. add analog hands and index watch face studio allows you to add components like text, image, shape, analog hands, and index in a watch face. for your watch to have the look and feel of an analog watch, add the following components: time > index time > analog hands > minute time > analog hands > hour notethe index and watch hand images used in this code lab are no longer included in the latest version of the watch face studio. however, you can choose a design for the index and watch hands from available images in the resources folder. you can also create and add your own design. you will see that the hands move automatically and in sync with the device time. select all the newly added components and click group. rename the group as group_analogtime. use a progress bar for seconds a component like a progress bar can be used to show how much of the process is completed and how much is left. in this step, you will use it to show how far or close the next minute is. to use a progress bar as seconds: click add component and select progress bar. rename the component to seconds. move seconds behind group_analogtime. in properties of seconds, do the following: a. adjust the dimension (width and height) to 395. b. align the component to the center. c. drag the background slider to 0%. d. make sure that the type is a circular progress bar; otherwise change it. e. in range setting, change value to 0 and click tags beside it to open the tags window. f. type in [sec]. it means that the value from 0 will increment as the value of the second increases. g. set max value to 59 since it is the maximum value of [sec]. notein this scenario, the progress bar disappears in the canvas as the preview only uses the base value, which is 0. however, the component is still present in run. format and position a digital clock in this step, you will learn how grouping works and affects its components. you will also learn how to format the date and time using tags. to format and position a digital clock, you need to: add a digital clock > time twice. rename them as hour and minute, respectively. add a digital clock > date and rename the component as date. put them in one group and rename it as group_digitaltime. go to the properties of hour and change the text appearance to 80. do the same for minute. adjust the text size of date to 15. adjust the y placements of the individual components to look like the image below. when you change a certain component, it won’t affect other components in the group. format hour to only show the time in hour: a. go to its properties and click the tags button in text field. b. replace text field value with [hour_0_23_z] to show the current hour with leading zero. do the same for minute but replace the text field value with [min_z] to show the current minute in an hour with leading zero. go to group_digitaltime placement properties and align it horizontally. after that, place it to the left. you will see the components adjusted as a group. utilize health features and battery level watch face studio also allows you to utilize data like step count, heart rate, and battery level. follow the steps below to show these real-time data using tags on texts or progress bar: battery level add a circular progress bar and rename the component as battery level. drag the background slider to 0%. go to value properties. replace the value with 0 and, in tags, input or choose [batt_per] to use the current battery percentage as the value. add a circle complication slot and rename it as battery icon. complications are a set of components that can be handled as one group. set the type to fixed and change the default provider to watch battery. select short text as complication type and choose icon + text for layout. select and move battery level and battery icon together to the bottom right. heart rate add a circular progress bar and rename the component as heart rate. drag the background slider to 0%. go to value properties. replace the value with 0 and, in tags, input or choose [hr] to use heart rate as value. set the max value to 240 since it's the maximum heart rate a person can have. add a text component and rename it as heart rate label. in the text field, input heart rate and change the text size to 12. change the y placement to 195. add another text component and rename it as heart rate text. in the text field, input [hr] and change the text size to 30. group heart rate, heart rate label, and heart rate text together. rename the group as group_heartrate. move the group_heartrate placement to the center right. step count add a circular progress bar and rename the component as step count. drag the background slider to 0%. go to value properties. replace the value with 0 and, in tags, input or choose [sc_per] to use the current percentage to the goal of step count. add a circle complication slot and rename it as step count text. set the type to fixed and change the default provider to step count. select short text as complication type and choose text + title for layout. it will now show "steps" as title and step count as text. place the step count text in the center horizontally. select and move step count and step count text together to the top right. select group_digitaltime, group_batterylevel, group_heartrate, group_stepcount, battery icon, and step count text. drag them behind group_analoghands and seconds. by doing this, the analog hands would overlap the components. make use of tag expressions you already have three progress bars that show data of battery level, heart rate, and step count. this time, you will make these features more functional by changing the progress bars' color to red using tag expressions. tag expressions are conditions that allow you to change the rotation, placement, behavior, and opacity of a component based on tag values. it can alter your watch face's appearance dynamically as the tag value changes. tag expressions support different types of operators – arithmetic, relational, logical, and ternary. for this step, you will apply tag expressions on the color opacity. but first, you will have to: duplicate all the circular progress bars (seconds, battery level, heart rate, and step count). move all the duplicates to a new group called group_colorchange. make sure that group_colorchange is behind all other groups. change individual component’s color to #ffffff or white. duplicate this group and rename it as group_background. move it behind group_colorchange. drag the background slider to 16% and remove tags in the value properties of each component of group_background. change group_colorchange color to #ff001e or red. group_colorchange will be used as components underneath when you set the opacity of the main components to 0 using tag expressions. group_background will serve as gap fillers of each progress bar. below are conditions that will trigger the opacity of the main components to become 0 and reveal the duplicated red components: change the color of the battery level to red if the battery level is equal to or less than 20% go to group_batterylevel and select battery level. navigate to color properties. check if the color opacity value is 100. this will serve as the base value. in tags, input [batt_per]<=20?-100:0 to subtract 100 from the base value of opacity if the battery level is equal to or less than 20. otherwise, the base opacity value remains the same. in the run pane, adjust the device > watch battery to 20% or less, and you will see how the color will change to red. change the color of step count to red if the goal hasn't been reached yet and the time is already 18:00 (6:00 pm) or beyond go to group_stepcount and select step count. navigate to color properties. check if the color opacity value is 100. this will serve as the base value. in tags, input ([sc]<[sc_goal])*([hour_0_23]>=18)?-100:0 to subtract 100 from the base value of opacity if the step count is less than the goal, and if the value of hour in a day is 18 or beyond. otherwise, the base opacity value remains the same. play with the time control bar in the run pane and health > steps data to see how the color will change from blue to red. change the color of the heart rate and seconds to red if the heart rate is below or above the normal go to group_heartrate and select heart rate. navigate to color properties. check if the color opacity value is 100. this will serve as the base value. in tags, input ([hr]<60)+([hr]>100)?-100:0 to subtract 100 from the base value of opacity if the heart rate is below or above the normal (60-100). otherwise, it remains the same. do the same for seconds. test it in the run pane by adjusting the health > heart rate to below 60 or above 100, and you will see how the color will change to red. prolong the battery life now that you already know what group and tag expressions are, it's about time for you to use both to your advantage. it is observed that the darker a watch face design is, the longer the battery life can be. to help the watch stay powered even when there’s a little battery left, you will need to decrease the opacity of the watch face when the battery level is equal to or less than 10%. to do this, you have to: select and combine all created groups and components, except for group analogtime, battery icon, and step count text, to a new group called group_watchface. go to group_watchface color properties and change the base opacity value to 20 in tags, input [batt_per]<=10?0:80 to add 0 to the base value of opacity if the battery level is equal to or less than 10. otherwise, it adds 80 to the base value, making the watch face 100% visible. adjust the device > watch battery to 10% or less, and you will see how most components' opacity decreased. choose components for always-on always-on display is a feature that allows your galaxy watch to show the time without checking on it by pressing a button or lifting your hand. in watch face studio, you can choose which group or component to display on the always-on by following these steps: go to the always-on tab, to see the same set of components you added and grouped. click the eye icon next to the group name to hide or make it visible. hide group_watchface, battery icon, and step count text. at this point, your always-on display will display a basic analog watch face whenever your watch is in idle mode. test the watch face to test your watch face, you need to: connect a watch device to the same network as your computer. in watch face studio, select project > run on device. select the connected watch device you want to test with. if your device is not detected automatically, click scan devices to detect your device or enter its ip address manually by clicking the + button. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can create and design a watch face using tag expressions by yourself! if you're having trouble, you may download this file: tag expression complete project (272.71 kb) to learn more about watch face studio, visit: developer.samsung.com/watch-face-studio

      https://developer.samsung.com/codelab/watch-face-studio/tag-expression.html
      1. Learn
      2. Code Lab

      codelab

      Integrate IoT Devices into the SmartThings Ecosystem

      integrate 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) alternatively, you may simply get it by git cloning or downloading a zip file from this github repository. 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)

      https://developer.samsung.com/codelab/smartthings/device-sdk.html
      No Search Results
      No Search results. Try using another keyword.
      • <<
      • <
      • 1
      • >
      • >>
      Samsung Developers
      Samsung Developers
      Quick Link
      • Android USB Driver
      • Code Lab
      • Galaxy Emulator Skin
      • Foldables and Large Screens
      • One UI Beta
      • Remote Test Lab
      • Samsung Developers Podcast
      Family Site
      • Bixby
      • Knox
      • Samsung Pay
      • SmartThings
      • Tizen
      • Samsung Research
      • SamsungOpen Source
      • Samsung Dev Spain
      • Samsung Dev Brazil
      Legal
      • Terms
      • Privacy
      • Open Source License
      • Cookie Policy
      Social Communications
      • Facebook
      • Instagram
      • Twitter
      • YouTube
      • Buzzsprout
      • Rss
      • Linkedin
      • System Status
      • Site Map
      • System Status
      • Site Map
      • facebook
      • instagram
      • twitter
      • youtube
      • buzzsprout
      • rss
      • linkedin

      Copyright © 2023 SAMSUNG. All rights reserved.