Accessing Sensor Data (Pedometer) on Samsung Gear 2 – Sample Code

DSC_0007

This article provides sample code to access sensor data for the samsung Gear 2 running tizen. The examples provided with the Tizen wearable SDK are definitely sufficient to get you started , but with a catch – Everything is written in object-oriented FUNCTIONAL (enterprise) javascript (even implementing the MVC pattern for cleaner ,clearer code) . For many of us familiar with straightup procedural javascript, it can take immense effort to get a hang of whats going on. So I have written a simple Gear 2 application in  good old procedural javascript (similar performance) which you can import , test and use in your apps. Before you start ensure you are familiar with the structure of Gear 2 apps and  running the sample applications .
Code Can be downloaded from Github

First things First! – Create a New Project.

sensordata

In the Tizen wearable SDK do the following

New > Tizen Weaarable Web Project > Template > Wearable UI > List Application

Enter the name of your project – “SimpleSensor” and click finish.

See also : How to sideload .wgt files on your gear device or emulator.

Modify Your index.html File.

Modify your index.html file .. add 3 paragraph tags to hold a title and pedometer information on calories / number of steps taken.

<!-- Sample Code by Victor Dibia, Dencycom.com May 16, 2014 -->
<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="width=device-width,user-scalable=no"/>
	<title>Wearable UI</title>
	<link rel="stylesheet"  href="lib/tau/themes/default/tau.min.css">
	<!-- load theme file for your application -->
	<link rel="stylesheet"  href="css/style.css">
</head>
<body>
	<div class="ui-page ui-page-active" id="main">
		<header class="ui-header">
			<h2 class="ui-title">Simple Sensor</h2>
		</header>
		<div class="ui-content content-padding">
			<p style="font-size: 25px ; border-bottom: 1px solid #fff; padding-bottom: 10px; ">Pedometer Readings </p>

			<ul class="ui-listview">
			    <p id="calories" style="font-size: 20px "> Calories</p>
				<p id="steps" style="font-size: 20px ">Steps</p>
			</ul>
		</div>
	</div>
</body>
<script type="text/javascript" src="lib/tau/js/tau.min.js"></script>
<!-- load javascript file for your application -->
<script src="js/app.js"></script>
<script src="js/pedo.js"></script>
<script src="js/lowBatteryCheck.js"></script>
</html>

Notice that we have included a javascript file “pedo.js” at the bottom of the html file which contains the javascript code that gets  the sensor information.

Add Javascript Code to Access the Pedometer Sensor and Listen for Changes.

You access the sensor using the “window.webapis.motion object.”


//<!-- Sample Code by Victor Dibia, Dencycom.com May 16, 2014 -->
(function() {
	//alert('pedo here');

	var pedometer = null,
    pedometerData = {},
    CONTEXT_TYPE = 'PEDOMETER';

	if (window.webapis && window.webapis.motion !== undefined) {
        pedometer = window.webapis.motion;
        console.log('Pedometer found');
        start();
    }else {
    	console.log('Pedometer not found');
    }

	 //Start pedomenter ;
	 function getPedometerData(pedometerInfo) {
         var pData = {
             calorie: pedometerInfo.cumulativeCalorie,
             distance: pedometerInfo.cumulativeDistance,
             runDownStep: pedometerInfo.cumulativeRunDownStepCount,
             runStep: pedometerInfo.cumulativeRunStepCount,
             runUpStep: pedometerInfo.cumulativeRunUpStepCount,
             speed: pedometerInfo.speed,
             stepStatus: pedometerInfo.stepStatus,
             totalStep: pedometerInfo.cumulativeTotalStepCount,
             walkDownStep: pedometerInfo.cumulativeWalkDownStepCount,
             walkStep: pedometerInfo.cumulativeWalkStepCount,
             walkUpStep: pedometerInfo.cumulativeWalkUpStepCount,
             walkingFrequency: pedometerInfo.walkingFrequency
         };

         pedometerData = pData;
         return pData;
     }

     /**
      * Return last received motion data
      * @return {object}
      */
     function getData() {
         return pedometerData;
     }

     /**
      * Reset pedometer data
      */
     function resetData() {
         pedometerData = {
             calorie: 0,
             distance: 0,
             runDownStep: 0,
             runStep: 0,
             runUpStep: 0,
             speed: 0,
             stepStatus: '',
             totalStep: 0,
             walkDownStep: 0,
             walkStep: 0,
             walkUpStep: 0,
             walkingFrequency: 0
         };
     }

     /**
      * @param {PedometerInfo} pedometerInfo
      * @param {string} eventName
      */
     function handlePedometerInfo(pedometerInfo, eventName) {
    	 pedometerData = getPedometerData(pedometerInfo)
    	 console.log('Total Steps : ' + pedometerData.totalStep);

    	 document.getElementById("calories").innerHTML =  'Total Steps : ' + pedometerData.totalStep;
    	 document.getElementById("steps").innerHTML = 'Calories Burnt : ' + pedometerData.calorie;

     }

     /**
      * Registers a change listener
      * @public
      */
     function start() {
         resetData();
         pedometer.start(
             CONTEXT_TYPE,
             function onSuccess(pedometerInfo) {
                 handlePedometerInfo(pedometerInfo, 'pedometer.change');
             }
         );
     }

     /**
      * Unregisters a change listener
      * @public
      */
     function stop() {
         pedometer.stop(CONTEXT_TYPE);
     }

     /**
      * Initializes the module
      */
})();

 

Add the Necessary privilege.

You will need to give permissions to your widget/app to access the hardware sensors. You can specify an API, or API groups, accessed and used by the widget in the Privilege tab of the widget configuration editor. The tab serves as a standardized tool to request the binding of an IRI-identifiable runtime component for a widget to use at runtime.

See Also : How to Access Accelerometer Data in Gear 2 Apps

– In your project Click config.xml
– Under the Privileges Tab, Click Add-  http://developer.samsung.com/privilege/healthinfo
This priviledge Allow the application to accessing health data, such as step count abd heart rate measurements from various sensor.

Note: if this privilege is not added, you will get the following error after compiling you project .

SecurityError: The application does not have the privilege to call this method.

After setting the privilege information with the widget configuration editor, you can see the added code in the Source tab.

Test Your Code .

Build your project now and run as Tizen Wearable application. To simulate pedometer data, right click on your emulator > Control Panel > Event Injector > Pedometer > Walk Slowly

sensorda

That’s right , we are in business!!

Gimme That Code!

Entire project can be found on github. Feel free to improve it and add sample code for other sensors.

To Access Other Sensors

You can adapt the code above in accessing other sensors or services such as infrared, heartrate monitor etc . You will need to know which prividege necessary for each service/sensor. You can find this information in the API reference within the help section of the tizen wearable IDE.

sensors

 

About Vykthur

Mobile and Web App Developer and Researcher. Passionate about learning, teaching, and recently - writing.
This entry was posted in Programming, Tutorials, Wearables and tagged , , , , . Bookmark the permalink.
  • zac

    I added healthinfo info privilage but I’m getting PRIVILATE_LEVEL_VIOLATION error when I try to run this on Gear Device (works ok on simulator). Any idea what’s wrong?

    • Vykthur

      Thats odd .. healthinfo priviledge should solve that issue.
      I’d suggest you check to ensure you arent attempting to use other sensors … your config.xml file should resemble the following ..

      SimpleSensor

    • Vykthur

      Hi Zac

      I have done some more testing and this error maybe as a result of certificate issues.
      Ensure you have imported the right code signing certificates into your workspace and ensure you have used the DUID of the device (or test emulator) you are testing on during the certificate generation process.

      I have written a bit about certification and running .wgt files on your device here
      http://denvycom.com/blog/how-to-install-wgt-files-gear2/

      -V

  • Sakura

    Can I access the heart rate monitor in the same way? And also is there any official documentation for the pedometer info obtained in the js.

    • Vykthur

      For the current version of the Gear 2 SDK, , accessing heart rate monitor is NOT supported.
      Documentation for the pedometer info can be found in the SDK Help file …
      In your SDK go to help > help content …

      Tizen Wearable Web App Programming > API References > Device API Reference > System

      • Sakura

        Thank you so much . 🙂

        • Vykthur

          Glad you found it helpful!
          Please feel free to share what you are building for the gear 2 platform.
          -v

          • Sakura

            I am trying to develop a qr scanner in gear 2 using the following link http://www.ephespage.de/artikel/detail/a/n/si/ch/t/jquery-and-html5-based-qr-code-reader.html
            The sample runs fine in browser but in the watch the decoding is throwing an error. Could you help me out please.

          • Vykthur

            Do you mind posting the details of the error ?

          • Guest

            in the text where it shows the result “error decoding qr code” is the message we get wen v try to run in gear2

          • Vykthur

            I have seen that the code you are using – utilizes the webcam to obtain a stream of the qr image. Have you modified this code to use the tizencamera API instead of the webcam ? Does your app accurately display the camera view ?

            You can find the camera API in the Tizen Help file

            Tizen Wearable Web App Programming > API References > Supplementary API Reference

            -V.

          • Sakura

            we went through the reference… is there any sample program in tizen tat uses camera api… could you please share the link or a sample

          • Vykthur

            Hi Sakura,

            In the Tizen Wearable Help file …. Within the Supplementatry API Reference, there is a detailed documentation on the camera api. Also , there is sample code …

            Goto File > New > Tizen Wearable Project > Sample > Web App > Camera

            A full working application on how to use the Camera on the gear.

            Please let me know if there is still difficulty finding it.

            -V.

          • Sakura

            in the paragraph element where the output is to be displayed i am getting error decoding qr code wen i run it in the watch..

  • Shyam

    I am completely new to the Samsung app development . I deployed this code in Samsung Gear S3 , but I am not getting any data over there?
    Does this works for Gear s3 as well?