Quantcast
Channel: Evothings | RSS Feed
Viewing all 97 articles
Browse latest View live

Evothings Studio 1.1.0 released

$
0
0

Stockholm
December 22, 2014

estimote-beacons-group-small Evothings is proud to announce the release of Evothings Studio version 1.1.0. This version further extends the opportunities to develop great mobile apps for connected devices and the Internet of Things.

Major highlights include support for Estimote Beacons, updated examples for the TI SensorTag, and brand new example apps for ReadBearLab boards.

It is fun and easy to get started

TISensorTag

Making quick prototypes and shiny apps for Beacons and micro-controllers is easier than ever with this release. It is quick to get started!

Download Evothings Studio and try it out yourself!

Summary of new features in Evothings Studio 1.1.0

RedBearLab.nRF51822

New plugins in Evothings Client:

New example applications:

Updated documentation:

New example library functions:

  • Updated EasyBLE library with support for accessing advertisement data
  • Updated TISensorTag library with firmware version access and sensor value calculation
  • Dynamic loading of scripts
  • Utilities for numeric conversions

Bugfixes and improvements:

  • Evothings Workbench detects network switches, and restarts servers when changing network (note that clients must be manually reconnected)
  • Other improvements and bugfixes

See documentation main page for full release notes.


How to develop beacon apps in JavaScript with Evothings Studio and Estimote

$
0
0

Cross post of article posted at the Estimote blog.

Tens of thousands of mobile developers are working with Estimote Beacons to build native micro-location apps. Leveraging local context on mobile devices is one of the hottest trends in tech right now, but what about people working with JavaScript and HTML? Now they also can develop mobile applications on top of the Estimote platform. Evothings Studio is an open-source development tool, specifically designed to create mobile applications for the Internet of Things using JavaScript and HTML. Estimote Beacons are supported out-of-the-box. Read on and get your hands dirty writing your first beacon-enabled app.

EstimoteScanExampleApp

Prototype ideas in real time

Evothings Studio was created to allow you to quickly develop new ideas and designs. You can now build apps in a highly iterative and interactive style. Make changes to the code incrementally and instantly see the result on multiple mobile phones and tablets. Time from coding to testing is just a few seconds, making for a creative flow where you can turn your concept into a prototype in an instant.

Here is how it works: on your computer you run Evothings Workbench, a server that connects to mobile devices running the Evothings Client app. When pressing save in your code editor, changes are detected and the running app is updated on the connected devices.

When the project is ready to ship, you can build a native app to be published on the Apple App Store and Google Play.

Write code in your favorite editor

EstimoteJavaScriptCodeEdit

Evothings Studio comes with two main components:

  • Evothings Client – mobile application that runs JavaScript apps
  • Evothings Workbench – web server with a visual drag-and-drop user interface, which includes a launchpad to organize apps and JavaScript logging and code evaluation tools

The third component is your favorite text editor or IDE.

With Evothings Studio you have the freedom to use any code editor or IDE. As soon as you save a file, changes will be picked up by Evothings Workbench and connected mobile devices will be notified to update the running app.

The live reload mechanism works with all files and formats. For example, if you save an image in Photoshop, the app will update and display the new image.

Hands-on getting started guide

EstimoteBeaconFinderExampleApp1

Included with Evothings Studio is the “Estimote Scan” example app. This app displays beacon data when ranging for beacons.

Here is how to get up and running with the example app:

  • Get a set of Estimote Beacons
  • Download Evothings Studio (this download contains Evothings Workbench, examples and documentation)
  • Install the Evothings Client app on your mobile phone or tablet (get it from Apple App Store or Google Play)
  • Start Evothings Workbench on your computer
  • Make sure your mobile device is on the same WiFi as your computer and that the network allows connections
  • Launch Evothings Client and connect to the Workbench
  • Go to the Workbench and click RUN on the “Estimote Scan” example app
  • The app should now run on the mobile device and start detecting your Estimote Beacons
  • To view/edit the code, click the CODE button which will open a window with the application files
  • Open file index.html, make some changes to the code and save the file, the app now automatically reloads on the connected mobile device

To build a native stand-alone app, see the step-by-step guide below.

Cordova/PhoneGap plugin for Estimote Beacons

Evothings Client comes with a Cordova/PhoneGap plugin for Estimote Beacons. It’s open-source so you’re free to use it in any project.

The same plugin is used both when using Evothings Client and when building an app using the Cordova build system. The difference is that the edit-build-test cycle can be slow and tedious when using the Cordova build tools. What Evothings Studio does is taking the development cycle to warp speed.

The Estimote Beacons plugin currently supports:

  • Ranging for beacons (iOS and Android)
  • Monitoring beacons (iOS and Android)
  • Scanning for beacons using CoreBluetooth (iOS only)

The following is a taste of what the API looks like. Here is how to range for Estimote Beacons:

var region = { identifier: 'MyRegion' }

EstimoteBeacons.startRangingBeaconsInRegion(
   region,
   onBeaconsRanged,
   onError)

function onBeaconsRanged(beaconInfo)
{
   console.log('Number of Estimote Beacons ranged: ' +
       beaconInfo.beacons.length)
}

function onError(error)
{
   console.log('Start ranging error: ' + error)
}

The above region will match all Estimote Beacons that have the default UUID (B9407F30-F5F8-466E-AFF9-25556B57FE6D). The function onBeaconsRanged will be called continuously when there are matching beacons within range, until ranging is stopped. It prints the number of beacons ranged to the debug console.

Monitoring and ranging

EstimoteBeaconFinderExampleApp2

Two basic actions apps can perform defined in the iBeacon standard are region monitoring and ranging. Monitoring, which is enabled by startMonitoringForRegion, tracks entering and exiting regions. Monitoring works in the background or even when the app is killed. Thanks to that, it’s a powerful tool for delivering contextual notifications when the user comes in range of a beacon, even though monitoring itself does not contain any information about proximity.

Ranging, enabled by startRangingBeaconsInRegion, works only in the foreground. It has a fast update rate, and includes proximity and distance information, allowing for for granular insight into users’ behavior and therefore tailoring content more suited to their needs.

Read more about monitoring and ranging on the Estimote Community Portal.

On iOS a third method for detecting beacons is supported, which is called scanning. Scanning is similar to ranging but uses a different underlying implementation than ranging does.

Beacon regions

Regions define which beacons to monitor and range. A region consists of the following:

  • Identifier – a string set by the developer to name the region
  • UUID (Universally Unique Identifier) – a string that identifies the UUID for the beacons in the region (many beacons can share a UUID)
  • Major – the major value is a number that can be used to identify specific beacons (several beacons in a region can have the same major value)
  • Minor – the minor value is a number can be used to identify a specific beacon (the minor value should be unique to one beacon within a region)

Estimote Beacons come predefined with a default UUID and randomly generated major and minor values. Each value can be used by an application to identify beacons or to create ‘regions’: beacon-based geofences. When specifying a beacon region, you can leave out major and minor values to find all beacons with the specified UUID. You can also specify the UUID and major value (when using minor, major must also be given). If you define all three: UUID, major and minor, you will be monitoring for a single beacon with the particular ID.

Understanding how regions works is critical to building iBeacon apps. To learn more about it, read the article on Estimote Community Portal.

When a region is defined in JavaScript, certain default values apply if a field is left out.

Default values are as follows:

  • Region identifier defaults to ‘EstimoteSampleRegion’
  • UUID defaults to ‘B9407F30-F5F8-466E-AFF9-25556B57FE6D’ (Estimote Beacon factory UUID)
  • Major value defaults to null
  • Minor value defaults to null

Here is an example of a simple beacon region that will match all factory configured Estimote Beacons:

var region =
{
    identifier: 'MyRegion'
}

Note that if you set a minor value you must also set a major value. You cannot use minor without major.

Here is an example of a region that defines all fields:

var region =
{
    identifier: 'MyRegion',
    uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D',
    major: 1,
    minor: 2
}

Overview of Estimote plugin and JavaScript API

Start and stop ranging:

EstimoteBeacons.startRangingBeaconsInRegion(
    region,
    successCallback,
    errorCallback)

EstimoteBeacons.stopRangingBeaconsInRegion(
    region,
    successCallback,
    errorCallback)

Start and stop scanning (iOS only):

EstimoteBeacons.startEstimoteBeaconsDiscoveryForRegion(
    region,
    successCallback,
    errorCallback)

EstimoteBeacons.stopEstimoteBeaconDiscovery(
    region,
    successCallback,
    errorCallback)

On iOS 8 it is also required for your app to ask for permission to use location services (on iOS 7 and Android this call does nothing):

EstimoteBeacons.requestAlwaysAuthorization(
    successCallback,
    errorCallback)

To learn more look into the documentation in the JavaScript API file, available on GitHub.

How to access beacon data

When you use ranging or scanning, you have access to a variety of beacon properties. Different properties are available depending on whether ranging or scanning is used. (Note that during monitoring you don’t get data for individual beacons, rather you get data about regions entered and exited.

Properties available on iOS

Properties available both during ranging and scanning:

  • major – major value of the beacon
  • minor – minor value of the beacon
  • color – one of EstimoteBeacons.BeaconColorUnknown, EstimoteBeacons.BeaconColorMint, EstimoteBeacons.BeaconColorIce, EstimoteBeacons.BeaconColorBlueberry, EstimoteBeacons.BeaconColorWhite, EstimoteBeacons.BeaconColorTransparent
  • rssi – number representing the Received Signal Strength Indication

Properties available only when ranging:

  • proximityUUID – UUID of the beacon
  • distance – estimated distance from the beacon in meters
  • proximity – one of EstimoteBeacons.ProximityUnknown, EstimoteBeacons.ProximityImmediate, EstimoteBeacons.ProximityNear, EstimoteBeacons.ProximityFar

Properties available only when scanning:

  • macAddress
  • measuredPower

The full set of properties available on iOS are documented in the Estimote iOS SDK.

Properties available on Android

Properties available when ranging:

  • proximityUUID – UUID of the beacon
  • major – major value of the beacon
  • minor – minor value of the beacon
  • distance – estimated distance from the beacon in meters
  • proximity – one of EstimoteBeacons.ProximityUnknown, EstimoteBeacons.ProximityImmediate, EstimoteBeacons.ProximityNear, EstimoteBeacons.ProximityFar
  • rssi – number representing the Received Signal Strength Indication
  • name – the name advertised by the beacon
  • macAddress
  • measuredPower

The properties available on Android are documented in the Estimote Android SDK.

Beacon data code example

Using the above data you can do all sorts of things based on proximity: identify which beacons are close, how far they are, and so on. Here is an example of how to access the beacon distance property:

var region = { identifier: 'MyRegion' }

EstimoteBeacons.startRangingBeaconsInRegion(
    region,
    onBeaconsRanged,
    onError)

function onBeaconsRanged(beaconInfo)
{
    // Sort beacons by distance.
    beaconInfo.beacons.sort(function(beacon1, beacon2) {
        return beacon1.distance > beacon2.distance })

    // Display distance for the closest beacon.
    var beacon = beaconInfo.beacons[0]
    console.log('Closest beacon is ' + beacon.distance + 'm away')
}

function onError(error)
{
    console.log('Start ranging error: ' + error)
}

Creating a native Estimote app

EstimoteEvothingsStudioScreenshot

Using the Cordova or PhoneGap build system, you can build a native app that can be published on the app stores.

Here is a step-by-step guide for how to build the example app “Estimote Scan” using Cordova.

1. Install the Cordova build system.

2. Create a new Cordova project with the name of your choice, using a command line window.

The following command will create a template Cordova app in the directory “beacondemo”, set the app id to “com.mydomain.beacondemo”, and set the name to “BeaconDemo”:

cordova create beacondemo com.mydomain.beacondemo BeaconDemo

3. Go to the app directory using the command:

cd beacondemo

4. Copy your HTML and JavaScript files to the newly created Cordova project.

In the “beacondemo” folder there is a subfolder called “www”. This is where you put the application’s HTML and JavaScript files. Delete all the files already inside the “www” folder and put your own app’s files in there. If you’re just trying out the build process, you can use the “Estimote Scan” example’s files instead: you’ll find them in the “examples” folder of the Evothings Studio directory.

Copy files in:

examples/estimote-scan

To the directory:

beacondemo/www

The result should look like this:

beacondemo
   www
       app.js
       index.html
       libs
       ui

5. Add the Estimote plugin using the following command; this just needs to be done once:

cordova plugin add https://github.com/evothings/phonegap-estimotebeacons.git

(If you want to use other plugins, you also have to add them to the project.)

6. Add the target platforms you wish to build for (Android and/or iOS); this also only needs to be done once:

cordova platform add android
cordova platform add ios

7. Build the app.

To build and install the app on Android, use these commands:

cordova build android
adb install -r platforms/android/ant-build/BeaconDemo-debug.apk

To build and install the app on iOS, first build an Xcode project:

cordova build ios

Then open and run the generated project using Xcode: platforms/ios/BeaconDemo.xcodeproj

That’s it! You have now built a native stand-alone app.

A nice thing is that you can continue to develop the code using Evothings Workbench and Evothings Client. Just drag and drop this file into the Workbench project list:

beacondemo/www/index.html

Now you can edit and develop your project using the fast Evothings Workbench based workflow, and when you’re ready to build a native version of the app, just execute the cordova build… command as described above.

It may be that you want to use Cordova plugins that are not included with Evothings Client (list of supported plugins). However, you can still use your Cordova app with Evothings Workbench, to take advantage of the fast workflow. Learn a few simple steps to achieve this in the Evothings Cordova Guide.

The Estimote PhoneGap/Cordova plugin also contains an example app you can use as an inspiration for your own apps, along with build instructions.

It’s easy to get started with Estimote Beacons in JavaScript

It is fun and easy to get going. Just order an Estimote Developer Kit, then download Evothings Studio and dive straight into building your beacon projects with JavaScript and HTML. We’d love to hear your thoughts, so don’t hesitate to ask about anything on the Evothings Forum or Twitter, or email info@evothings.com.

Mikael Kindborg, Lead Architect at Evothings

How to get started with Estimote beacon mobile app development in 5 minutes

$
0
0

estimote-beacons-boxPerhaps you already have, or plan to order, a set of Estimote Beacons and want to make some cool apps for them? It can take some time and preparation to get up and running with mobile application development, and the path to a final publishable app is not without challenges. By using Evothings beacon technologies, based on JavaScript and HTML, you can be up and running in just five (5) minutes, and in addition to that build a native app when you are ready to ship!

Evothings Studio comes with an example app for Estimote beacons, which makes it easy to get up and running quickly.

Here is what you do, to be up and running in five minutes:

  • Get a set of Estimote Beacons
  • Download and install Evothings Studio
  • Get the free Evothings Client app from Apple’s App Store or Google Play
  • Make sure you are on a WiFi network that allows connections
  • Launch Evothings Workbench on your computer
  • Launch Evothings Client on your mobile phone(s) and connect to the Workbench
  • Locate the example app “Estimote Scan” in the Workbench project list
  • Click RUN

Now the fun begins! Click CODE. Open a code file in your favorite text editor, make some changes. Pres Save. The app reloads and displays your updates right on your mobile device.

Yes, it is that easy. Go and get Evothings Studio now – it is quick and fun to get up and running!

Also check out the in-depth introduction to development of Estimote apps using JavaScript, where we dig into the details of beacon app development for mobile devices.

Cordova IoT Starter Kit

$
0
0

On this page we have collected information about using the Apache Cordova build system with Evothings Studio. This enables you to build native mobile applications for the Internet of Things (IoT).

Quick introduction to Cordova

Cordova is used to create a native app from an app developed in JavaScript/HTML.

A very useful part of Cordova is the plugin system. Plugins provide access to native device functionality from JavaScript. There are many ready-to-use plugins available. You can also write your own plugins.

Plugins have two parts, a native code implementation (usually written in Objective-C on iOS and Java on Android), and a JavaScript library (shared between platforms).

You can use Evothings Studio without Cordova, but if you want to create native apps it is what you want to use.

What you need to get started

To build apps with Cordova you need to install Cordova itself and also the mobile SDKs (Software Development Kits) for the mobile platforms you wish to deploy your app on. The main platforms used by Evothings are iOS and Android.

Installing Cordova and the SDKs can be a bit time consuming and requires that you can use command line tools. Once installed Cordova is easy to use, so don’t give up.

To help you in installing and using Cordova the Evothings documentation contains a Cordova Build Guide.

The highlights of this guide are:

To summarize, you need to install Cordova on your desktop/laptop machine, and you also need to install the mobile SDKs for the platforms you wish to build apps for. On OS X you can build apps for both iOS and Android. On Windows and Linux you can build apps for Android, but not for iOS (there is no iOS SDK for Windows/Linux).

Useful background knowledge

If you are new to Evothings Studio, read the Introduction in the documentation to get a basic understanding of the development tools used.

Evothings Client is a Cordova app

It can be useful to know that Evothings Client is itself an app built with Cordova.

Evothings Client has a number of plugins included, see the plugin listing in the documentation.

When you build your own Cordova app, you should keep track of which plugins are used by your app so you can add them to the Cordova project (if you are not sure, just ask on the Evothings Forum).

To build Evothings Client is quite complex and currently not documented in a pedagogical way. A Ruby build script is used to handle the build steps, adding plugins, copy resources, etc. The source code for Evothings Client is available on GitHub.

Strategies for app development using Evothings Studio and Cordova

The two main tools in Evothings Studio are Evothings Workbench and Evothings Client. The Workbench provides the live reload workflow used with Evothings Client. You can also use Evothings Workbench and live reload with any Cordova application.

When developing an app with Evothings Studio, you have two options:

Use Evothings Workbench and Evothings Client. Very quick to get started, just install Evothings Workbench and Evothings Client and you are up and running (no need to install Cordova, SDKs and build a native app). You can readily create a Cordova project when needed and place your JavaScript/HTML files there.

Use Evothings Workbench with your custom Cordova app. This is useful when you want to add Cordova plugins that are not included with Evothings Client. If you plan to make a final build and publish your app on the app stores, it can be convenient to create a Cordova project and keep your JavaScript/HTML files in the www folder of the project. Then it is easy to build a native app at any point during the development process. Note that if you use only plugins supported by Evothings Client, you can still use Evothings Client during development.

How to create a Cordova app from an Evothings project

An Evothings project is just a folder with HTML/JavaScript files (and other content such as CSS files and images). The minimal project is just one HTML file.

These are the steps to create a Cordova project from an Evothings app, for example one of the example apps that comes with the Evothings Studio download:

  • Create a Cordova project (using the command line tools)
  • Delete the files in the www folder of the newly created Cordova project
  • Copy (or move) your HTML/JavaScript files to the www folder in the Cordova project
  • Add any plugins needed by your app

Read on in the Cordova Guide to learn the details and see actual command tool examples.

Developing a Cordova app using Evothings Workbench

You can use the live reload mechanism and JavaScript tools available in Evothings with your Cordova app.

There are two options:

Run the files in the Cordova www folder in Evothings Client. For this to work, you must not use any additional plugins to the ones that comes with Evothings Client, so this is not always a practical solution. But it is handy to know that this possibility exists.

Connect to Evothings Workbench from your Cordova app. In this case, enter the address of the Workbench in config.xml and build the app. When you run the app it will connect to the Workbench. If the address changes (if you switch network for example) you need to update config.xml with the new address. So this is a little bit less handy than using Evothings Client, but still very workable. Don’t forget to change config.xml back to the original before shipping the app. Read more about how to setup Cordova for Evothings in the documentation.

For both of the above options, you add the main index.html to the Workbench and run the app in the same way:

  • Drag the www/index.html into the Workbench window
  • Lauch your modified Cordova app or Evothings Client
  • Click RUN in the Workbench

Evothings projects vs. Cordova projects

An Evothings project is just a folder with HTML/JavaScript files and other web content.

A Cordova project has a special folder structure, and the JavaScript/web files goes into the “www” folder.

Here is an overview of the Cordova directory structure.

Plugins and JavaScript files

The JavaScript files for Cordova plugins are bundled with the app by the Cordova build system. These files should not be copied to the www folder, and they should not be included into the HTML file using a script tag.

You only need to include the “cordova.js” file in a script tag. Including “cordova.js” in turn will include the JavaScript files for all the plugins installed in the app.

However, any JavaScript files or libraries that reference a plugin must be present in the www folder (or subfolder) and be included using a script tag.

This can sometimes be confusing and is good to keep in mind. If you want to read the JavaScript source code for a plugin, you can either look in the plugin folder in your Cordova project or browse the source for the plugin online (usually on GitHub).

Useful links

Estimote Starter Kit

$
0
0

In this starter kit, we have collected everything you need to get started with creating apps in JavaScript/HTML for Estimote Beacons. Regardless if you’re a seasoned developer or novice, you’ll learn more about beacons and making beacon-aware apps.

What you need to get started

beacons-in-box
In Estimote Beacons Developer Kit, the beacons come in sets of three units

Here is what you need:

  • Estimote Beacons (order at the Estimote web site)
  • Evothings Studio (download for OS X, Windows or Linux)
  • Evothings Client app (install on iOS or Android phones/tables, get it from Apple App Store or Google Play)
  • WiFi network that allows client connections
  • Basic knowledge of Evothings Studio (you can learn as you go through this tutorial)
  • To build native apps you need the Apache Cordova build tools

Useful background knowledge

If you are new to Evothings Studio, read the Introduction in the documentation to get a basic understanding of the development tools used.

Apache Cordova is a build system for creating native apps developed in HTML/JavaScript. You can use Evothings Studio without Cordova, but if you want to create native apps it is needed. Read more in the Cordova IoT Starter Kit.

Run the Estimote Scan example app

The easiest way to get going is to explore the Estimote Scan example app that comes with the Evothings Studio download:

  • Launch Evothings Workbench on your computer
  • Launch Evothings Client on your mobile phone(s), press SCAN and connect to the Workbench running on your computer
  • Locate the example app “Estimote Scan” in the Workbench project list
  • Click RUN

Then make some changes to the code:

  • Click CODE – this open a file browser with the source code of the app
  • Open a code file in a text editor and make some changes, for example, open index.html and change the h1 header tag text.
  • Save the file
  • The app now reloads on the connected device(s) and displays your updates

Watch the video in the Estimote getting started blog post to see the above steps in action.

How to create your own Estimote app

beacon-in-restaurant
Your beacon app can be used to add information nodes to public places, like shopping malls and restaurants.

An Evothings app is just a folder with HTML/JavaScript files (and other content such as CSS files and images). The minimal project is just one HTML file.

A project should have one main HTML file, which is the file launched when the app starts. This file is typically named “index.html”. Just drag and prop your main HTML file into the Workbench project list and then click RUN.

Here is a summary of the steps to create an app for use with Evothings Studio:

  • Create a folder for the app
  • Create content files (HTML, JavaScript, CSS, etc)
  • Add any JavaScript libraries needed
  • Drag the main HTML file into the Workbench window
  • Click RUN

A quick way to create a custom app is to just copy an example app and modify it. You can use Estimote Scan or Beacon Finder as a starting point.

Note that the JavaScript include files for Cordova plugins are bundled with the Evothings Client app, so these should not be added. Including the link to “cordova.js” will in turn include the JavaScript files for all plugins.

Learn about the Estimote Beacon JavaScript library

The tutorial How to develop beacon apps in JavaScript with Evothings Studio and Estimote is a comprehensible guide to making JavaScript apps for Estimote Beacons, and is recommended reading.

The JavaScript library for Estimote Beacons< is implemented as a Cordova plugin that is open source and available on GitHub:

Beacon Finder example app

The Beacon Finder example app demonstrates more parts of the API compared to the Estimote Scan example.

You can run the Beacon Finder app in Evothings Client, and you can also build a native app using Cordova.

Follow these steps to run Beacon Finder in Evothings Client:

  • Download the files on GitHub (or use git clone)
  • Open the folder examples/beacon-finder/www in a file browser
  • Drag file index.html and drop it in the project list in Evothings Workbench
  • Connect to the Workbench from Evothings Client
  • Click RUN on the project entry
copier-with-beacon
Real-world example, an Estimote beacon attached to copier, could easily be assigned to provide more user information via a clever app!

To create a native Beacon Finder app using Cordova, follow the build instructions on GitHub. Read more about Cordova in the Cordova IoT Starter Kit.

Useful links

  • Estimote company home page
  • Evothings Estimote quick-start guide
  • Evothings Estimote JavaScript tutorial
  • Estimote Cordova plugin
  • Cordova IoT Starter Kit (for building native apps)
  • Evothings download page
  • Evothings forum for Estimote beacons
  • Evothings Studio Starter Kit

    $
    0
    0

    On this page we have collected everything you need to get started with creating mobile apps for the Internet of Things in JavaScript/HTML using Evothings Studio.

    Evothings Studio in a nutshell

    Evothings Studio is a set of open-source development tools for creating mobile applications using web technologies. Evothings Studio is specifically designed for development of applications for the Internet of Things (IoT).

    Here are the tools you use to develop apps with Evothings Studio:

    • Evothings Client – mobile application that runs HTML/JavaScript apps (install from the app stores)
    • Evothings Workbench – web server with a visual drag-and-drop user interface, which includes a launchpad to organize apps and JavaScript logging and code evaluation tools (comes with the Evothings Studio download)
    • Your favorite text editor or IDE code editor (not included with the Evothings Studio download)

    workbench-client-evothings

    With Evothings Studio you have the freedom to use any code editor. As soon as you save a file, changes will be picked up by Evothings Workbench and connected mobile devices will be notified to update the running app. The live reload mechanism works with all files and formats. For example, if you save an image in Photoshop, the app will update and display the new image.

    To make it easy to get started Evothings Workbench comes with a collection of ready-to-use example apps for various IoT devices (Arduino, beacons/iBeacon, TI SensorTag, and many more).

    What you need

    Here is a list of what you need to get going:

    • Laptop/desktop machine running Windows, OS X or Linux
    • Mobile phone or tablet running iOS (iOS 7 or later) or Android (to use Bluetooth Low Energy you need a device with Bluetooth 4.0 or later running Android 4.3 or)
    • WiFi network that allows client connections (network client isolation must be turned off in the router)
    • Evothings Studio tools and examples (download for OS X/Windows/Linux)
    • Evothings Client mobile app (get it from Apple App Store or Google Play)
    • To run the example apps that comes with Evothings Studio you need the hardware used by each example, such as Arduino, Beacons, TI SensorTag, or LightBlue Bean (see the examples documentation for further details)
    • To build native apps you need the open-source Apache Cordova build system

    coffee-stains

    Up and running in 90 seconds

    Take a deep breath and dive right into the quick start guide Getting started with Evothings Studio in 90 seconds.

    It is fun and easy to get up and running!

    Useful background knowledge

    The documentation pages contains information about the tools available in Evothings Studio.

    Apache_Cordova1Apache Cordova is a build system for creating native apps developed in HTML/JavaScript. You can use Evothings Studio without Cordova, but if you want to create native apps it is needed.

    It is useful to know that Evothings Client is itself a Cordova app, developed using Evothings Studio.

    Cordova plugins are code modules that provides native device functionality, such as Bluetooth Low Energy and iBeacon ranging. Evothings Client comes with a number of plugins preinstalled.

    Overview of the Evothings Studio download

    Included with the Evothings Studio download:

    • Evothings Workbench desktop application
    • Example apps
    • Documentation

    Note that Evothings Client is installed from the app stores, and is not included with the download.

    Evothings Workbench runs on top of the node-webkit engine (which includes WebKit and node.js). The node-webkit binary is included with the download (named “EvothingsWorkbench”). All download packages (Windows/OS X/Linux) are basically identical except for the node-webkit binary.

    Here is an overview of some of the files and folders in the unzipped download package:

    documentation - documentation files
    examples - example apps
    hyper - JavaScript code for the Workbench
      server - server code
      settings
        project-list.json - apps show in the Workbench project list
        settings.js - settings you can modify
      ui - user interface code
    node_modules - modules used by node-webkit
    package.json - Workbench application settings

    Goodies

    evothings-studio-illustration

    Evothings Studio gives you several useful tools and goodies:

    • Develop on multiple mobile devices simultaneously – test your app on iOS and Android phones and tablets at the same time
    • Run an app on all connected devices with one click
    • When saving a file all connected devies reload the running app – you get to see the result instantly
    • Freedom to use any editor (live reload works with all editors that save data in HTML/JS/CSS/media files, also HTML editors and image editors)
    • Quickly get started with your own apps copying code from the example apps (code for examples included with the download)
    • Easily send log data from connected devices
    • Evaluate JavaScript code interactively on connected devices, useful for both development and debugging
    • Build native apps using Apache Cordova – no proprietary tools needed, include any Cordova plugins you like
    • Use live reload, logging and interactive code evaluation with any Cordova app – this makes it fast to develop and debug Cordova applications
    • Full source code is available on GitHub (Apache open source licence)

    How live reload works

    To learn more about how reload-on-save works, read the article Hybrid app development made fast.

    One very useful feature is that live reload works with any Cordova app, not only with Evothings Client. This is useful when you want to add Cordova plugins that are not built into Evothings Client.

    Learn more about how to use Evothings Workbench with your custom Cordova app in the Cordova live reload configuration guide.

    Deployment options

    To let others test your app, you have the following alternatives available:

    • Apache Cordova – Build a native app with the Cordova build system. Use the exact same code base as when developing with Evothings Studio.
    • Evothings Client – Place your app code (HTML/CSS/JS) on a web server and run in Evothings Client. Just ask users to get Evothings Client and provide the URL to the app. Evothings Workbench is not needed in this case. Read more about how to share your app.
    • Evothings Studio – In case the other person has Evothings Studio installed you can just send the source code for the app, e.g. in a zip file, or publish it on GitHub.

    How to build native apps

    The Cordova IoT Starter Kit contains information about how to get going with building native apps using Cordova.

    Also check out the Build overview and the Cordova Guide in the Evothings documentation.

    Debugging trick and tips

    Use the Tools window in Evothings Workbench to write log messages using the hyper.log() function.

    Click the “Tools” button in the Workbench menu bar to open this window. Log messages are displayed in the bottom pane.

    This will log the current window width for all connected clients:

    hyper.log('window width: ' + window.innerWidth)

    And this will log the device name and platform (note that the app must include cordova.js for the device object to be available):

    hyper.log('device model: ' + device.model +
        ' platform: ' + device.platform)

    In the top pane of the Tools window you can interactively evaluate JavaScript code on connected devices. This is useful both when developing and debugging an app.

    Initially, the top pane contains some code examples you can try out. In case you have erased the initial contents, click the “Restore” button to get it back.

    When you quit Evothings Workbench the contents of the top pane of the Tools window is saved automatically.

    JavaScript libraries

    One good thing to know is how JavaScript libraries are used. JavaScript library files are included in an app using HTML script tags (typically this is done in index.html).

    There are two kinds of JavaScript libraries used in a Cordova-based mobile app (such as Evothings Client):

    • Cordova libraries
    • JavaScript frameworks and application libraries

    Knowing the differences between these are helpful.

    Cordova libraries

    Cordova libraries are bundled with the app. You never see the JavaScript plugin files in your own application code. If you wish to browse the source code for a plugin, you have to look in the plugin code, which is available in the plugin code repository (usually on GitHub), and in the native project build with Cordova.

    Cordova libraries are included with one single script tag including cordova.js:

    <script src="cordva.js"></script>

    This will in turn include the JavaScript code for all plugins installed in the app.

    JavaScript frameworks and application libraries

    These are libraries used by the application. The JavaScript code for other libraries must either be included with the app and loaded via script tags, or loaded from the network using script tags. However, when loading scripts over the network, the mobile device must be online to work, which may not always be the case. It is recommended that all scripts used are included with the app.

    Evothings JavaScript libraries

    Evothings example applications use several JavaScript libraries related to IoT. These are included in the folder “libs/evothings” with subdirectories.

    The file “libs/evothings/evothings.js” contains functions for loading scripts asynchronously, which can be useful in some circumstances.

    Note that not all example apps have all libraries included, only the libraries actually used are included with each app. All Evothings libraries available can be found on GitHub.

    Useful links

    Getting started with mbed – ARMs new IoT platform and the Nordic Semiconductor nRF51-DK

    $
    0
    0

    mbed-enabled-logo ARM has been quite active recently with various announcements in the IoT space so we decided was time to pull out the various mbed enabled devices we had access to in our office and take the mbed development environment for a spin. This tutorial will walk you through compiling your first mbed application and deploying it to mbed enabled micro-controller. For this tutorial; we will be using the Nordic Semiconductor nRF51 Developer Kit.

    So; what exactly is mbed OS?

    mbed OS is a modern full-stack operating system that is designed specifically for ARM Cortex®-M-based MCUs; … optimised for energy efficiency, connectivity, security and reusable software components, it will become the foundation that enables widespread innovation in the IoT space.
    developer.mbed.org

    ARM hasn’t just launched this initiative; they have been working hard to establish partnerships with various micro-controller hardware providers that utilise the Cortex-M based processors to launch with multiple development boards available – with over fifteen different vendors already providing hardware to developers at the time of writing this post.

    Obtaining mbed enabled hardware

    A number of reference hardware is already available for use with mbed – it is easy to see when a board is mbed enabled as it will typically have the “mbed enabled” logo printed prominently on its PCB.

    mbed-nordic-nrf51-dk

    Creating a mbed developer account

    ARM has created an excellent developer community website that hosts not only information on the platform itself; but they also wrap the various tools required to develop for mbed directly from the browser with a web based IDE – meaning there is no need to download compilers to get started.

    http://developer.mbed.org

    Registration is free and it does not take long to create an account to get started. This is a welcomed relief for those who find other development environments frustrating when it takes hours to download, install and get all the tools and environment set up correctly.

    Add target platforms to your compilation environment

    In order to get started with mbed development; it is important to specify the hardware targets that you wish to target – each micro-controller may be slightly configured differently so in order for the online tools to generate the right binary it is important to select the right hardware to target.

    In our case we are using the Nordic Semiconductor nRF51-DK – when viewing this while logged in it is possible to include this in your environment by clicking on the “Add to your mbed Compiler” button displayed on the page. If you have other mbed enabled devices; you could search for them and add them to your environment as well – you will be able to switch between target platforms just before compiling.

    mbed-select_platform

    Accessing this option in the web based IDE is done by clicking on the target platform (if any) shown in the top right hand corner of the development environment.

    Create your first mbed program

    Within the web based IDE; you can create a new program by clicking on the New button in the menu bar. This will offer you a number of applications that have been uploaded by the hardware manufacturer showing off the various features of the device to compile and deploy to the device. However; let’s take a step back and look at creating a much simpler mbed application – click on the Import button instead.

    mbed-import_program

    For this tutorial we will import the mbed_blinky program; a “Hello World” application utilizing the LED on the development board and goes into an infinite loop by setting the digital out PIN associated to the LED to HIGH (on) and LOW (off) every 200 ms repeatedly showing you the application is running by blinking the LED.

    Within the IDE; it should present a new project with the following main.cpp file:

    #include "mbed.h"
    
    DigitalOut myled(LED1);
    
    int main() {
      while(1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
      }
    }

    It has a very familiar “Arduino” feel to it; but slightly refined – you specify a global variable referring to a DigitalOut object, that is associated to the PIN defined by the constant LED1 and then in the main application loop turn toggle it’s state with a small delay in between.

    Unfortunately; “LED1” may not be correctly defined for every environment so it is important to check the reference pin out to know exactly which PIN to use for the LED’s on the board. For the nRF51-DK, there are four LED’s which are named P0.21, P0.22, P0.23 and P0.24 respectively.

    A simple change is required to the source code:

    - DigitalOut myled(LED1);
    + DigitalOut myled(P0.21); // LED1 (refer to pin-out on back of board)

    Once this is done; you simply select the target platform – in this case it will be the platform named “Nordic nRF51-DK” and then press the “Compile” button within the web based IDE. If everything goes ok; it should offer you the following file for download:

    mbed_blinky_NRF51_DK_.hex

    You have now successfully compiled your first mbed application and are ready to deploy!

    Deploying your mbed application

    When you connect an mbed enabled device to a computer via the USB board it will mount the device as an external storage media device with the name “MBED” or “JLINK” depending on the hardware you are using. In the case of the Nordic Semiconductor nRF51-DK; it is also important to have the Segger J-Link drivers installed as well.

    Deploying the application simply involves copying the hex file to the external storage medium. Once the copying is complete; the device will restart and launch your application – and then the drive will re-mount waiting for the next application to be written to it. Deploying subsequent builds is a matter of repeating the process.

    If you are familiar with other IoT development environments; this may seem a little different initially as typically the local IDE uploads the application to the device automatically. The device will disconnect and automatically reconnect after it tries to load the mbed application onto the device. When unsuccessful, a “fail.txt” file on the external media will be created with additional information as to why it failed to deploy.

    Conclusion

    It is nice to see ARM making a serious effort to make mbed development available to a lot of developers without the need to download and configure compilers – the use of an online IDE environment also means that they can ensure the tools are up-to-date and as devices are added they can be easily accessed by developers.

    There is a lot more to investigate in the developer.mbed.org website and how to specifically take advantage of specific features in various supported micro-controllers. We will continue to look into the platform over the next few days and we may report on our experiences further.

    Currently; the mbed offering is limited to a few basic functions and whatever functionality has been provided by the various micro-controller manufacturers in regards to sample code. ARM has clearly stated it has large plans with the release of mbed v3.0 in the later part of 2015; specifically introducing a number of abstraction layers for connectivity across the various platforms and a more detailed operating system stack including a TLS/DTLS library.

    In any event it is a step in the right direction and it looks to be a great platform for IoT.

    We definitely look forward to mbed v3.0 where the BLE stack across the various mbed devices will be standardised – it will allow us to use a generic BLE protocol from Evothings Studio and build applications for iOS and Android across various hardware providers – something which is unfortunately fragmented a little right now.

    Announcing the release of Evothings Studio 1.1.3

    $
    0
    0

    Stockholm
    March 10, 2015

    linkitone-splash Evothings is happy to announce the release of Evothings Studio version 1.1.3, that offers increased support for Estimote Beacons and Stickers, new supported micro-controllers and stability across various devices. There is plenty of additional API and plugin documentation in addition to brand new examples being added while other examples have been updated.

    We’ve been having lots of fun with the Estimote Beacons and Stickers and there are now two examples covering different use cases that they both allow you to call the Estimote native functions directly from JavaScript (Nearable example is limited to iOS only). Accessing BLE advertisement data using easyble.js now works on both Android and iOS mobile devices. The BLE Scan example also removes any in-active beacons from the list after a short period of grace time.

    One of our partners, MediaTek Labs, have released a comprehensive development board called the LinkIt ONE. We have added a new example for demonstrating the on-board GPS which sends its coordinates over WiFi direct to your phone and positioning the board on a map view. We hope that it will inspire you to do great things with the LinkIt ONE, as it has lots of additional connectivity on-board.

    Documentation of libraries and plugin APIs have been added to the documentation. See the API Overview page for details.

    Download Evothings Studio and try it out yourself!


    Estimote Nearables Starter Kit

    $
    0
    0

    This Starter Kit gets you up and running with creating mobile applications for Estimote Stickers using the JavaScript Nearable API. When you attach a sticker to an object, it becomes a nearable that you can monitor and track. It is easy to write nearable apps using the fast workflow of Evothings Studio. Read on to learn more!

    Estimote Nearables at a glance

    Estimote nearables are based on a new type of beacon technology. The Estimote Stickers product line is the first to support this technology. Stickers are small beacons. When you attach a sticker to an item, it becomes a nearable; a smart object that broadcasts data.

    We have no dog at the office, so we instead attached the Dog Sticker to a remote control. Whenever someone picks it up you get notified!

    nearable-in-action

    In comparison with iBeacon technology, the nearable gives you much more information via the attached Sticker, such as its nearable type, proximity zone, signal strength, along with data from embedded sensors; motion, i.e. acceleration, orientation and temperature.

    With the JavaScript API for nearables, it is very easy also for web developers to get this information from your Stickers.

    Together with Evothings Studio, you can develop nearable apps directly on real mobile devices. When you connect several Evothings Clients to the Evothings Workbench (running on your computer) at the same time, you can simultaneously develop for iPhones and iPads in real time. That means that any changes you make when editing will instantly affect all connected devices each time you save any of the files in your project folder. It is easy to develop mobile applications in JavaScript for Estimote nearables with this fast workflow.

    The nearable functionality is implemented as a Cordova/PhoneGap plugin. This is an open-source plugin you can use to build a native app for publication on the App Store. The plugin also has support for traditional Estimote Beacons.

    What you need to get started

    Here is what you need to get up and running:

    • Estimote Stickers (order at the Estimote web site)
    • Evothings Studio (download for OS X, Windows and Linux)
    • Evothings Client app (install on iOS or Android phones/tables, get it from Apple App Store or Google Play)
    • WiFi network that allows client connections (network client isolation must be disabled)
    • Basic knowledge of Evothings Studio (you can also learn as you go through this tutorial)
    • To build native apps you need the Apache Cordova build tools

    Useful background knowledge

    If you are new to Evothings Studio, read the Introduction in the documentation to get a basic understanding of the development tools used. We also recommend the Evothings Starter Kit.

    Apache Cordova is a build system for creating native apps developed in HTML/JavaScript. You can use Evothings Studio without Cordova, but if you want to create native apps for publishing it is required. Read more in the Cordova IoT Starter Kit.

    Run the Estimote Nearables example app

    The easiest way to get going is to explore the Estimote nearables example app that comes with the Evothings Studio download:

    • Launch Evothings Workbench on your computer
    • Launch Evothings Client on your mobile phone(s), press SCAN and connect to the Workbench running on your computer
    • Locate the example app “Estimote Nearables” in the Workbench project list
    • Click RUN

    Experiment by making some changes to the code:

    • Click CODE – this opens a file browser with the source code of the app
    • Open a code file in a text editor and make some changes, for example, open index.html and change the h1 header tag text.
    • Save the file
    • The app now reloads on the connected device(s) and displays your updates

    How to create your own Nearables app

    An Evothings app is just a folder with HTML/JavaScript files (and other content such as CSS files and images). The minimal project is just a single HTML file.

    A project needs to have a main HTML file, which is the file launched when the app starts. This file is typically named “index.html”. Just drag and drop your main HTML file into the Workbench project list and then click RUN.

    Here is a summary of the steps to create an app for use with Evothings Studio:

    • Create a folder for the app
    • Create content files (HTML, JavaScript, CSS, etc)
    • Add any JavaScript libraries needed
    • Drag the main HTML file into the Workbench window
    • Click RUN

    A quick way to create a custom app is to just copy an example app and modify it. You can use the Estimote Nearables example app as a starting point.

    Note that the JavaScript include files for Cordova plugins are bundled with the Evothings Client app, so these should not be added again. Including the link to “cordova.js” will in turn include the JavaScript files for all plugins.

    In order to build a native app, generate a Cordova project and copy or move your files to the “www” folder in the Cordova project. Read on below for more details and links to documentation pages for how to do this.

    Explore the Nearables JavaScript library

    The GitHub repository for the Estimote Cordova/PhoneGap plugin has documentation for the JavaScript Nearables API.

    There is also JavaScript Nearables reference documentation available (generated using JSDoc).

    The JavaScript library for Estimote Nearables is implemented as a Cordova plugin that is open source and available on GitHub. This plugin supports both Estimote Beacons and Nearables. Additionally, the “Beacon Finder” example app demonstrates both the Estimote Beacon API and the Nearable API.

    Here are links to the plugin:

    Beacon Finder example app

    The Beacon Finder example app demonstrates more parts of the API compared to the Estimote Nearables example. This app demonstrates both how to program for Estimote Beacons and Nearables.

    You can run the Beacon Finder app in Evothings Client, and you can also build a native app using Cordova.

    Follow these steps to run Beacon Finder in Evothings Client:

    • Download the files on GitHub (or use git clone)
    • Open the folder examples/beacon-finder/www in a file browser
    • Drag file index.html and drop it in the project list in Evothings Workbench
    • Connect to the Workbench from Evothings Client
    • Click RUN on the project entry

    To create a native Beacon Finder app using Cordova, follow the build instructions on GitHub. Read more about Cordova in the Cordova IoT Starter Kit.

    Useful links

    Evothings keynote at Embedded Conference Scandinavia Syd

    $
    0
    0

    Malmömässan, Malmö
    March 10-11, 2015

    alexj-photoECS Syd is a two-day conference featuring current topics from the m2m world. Track sessions, demonstrations and workshops around IoT, sensors, security and industrial internet infrastructure.

    Evothings’ VP Community Dr Alex Jonsson will keynote the second conference day @ 1:20PM with a talk about the tale of two large industries, the embedded and the mobile and how they can create great things together just by finding ways to start the conversation.

    More reading on ECS Syd >>

    Create your own mobile application for the MediaTek Linkit ONE

    $
    0
    0

    mediatek-linkit-one
    The Internet of Things is a reality. Right now there are an estimate of 19 million developers working within the IoT industry and the numbers are growing rapidly. Within a couple of years we will be surrounded by products connected to the Internet. The LinkIt ONE has been developed by MediaTek, a fabless semiconductor company providing Systems on Chip (SOC) for wireless communications and connectivity. In this tutorial we will get a chance to explore what the MediaTek LinkIt ONE brings to this space. You will learn how to use the built-in WiFi and GPS chipset to deliver the position of the board to a mobile application using a small HTTP server.

    Overview

    The LinkIt ONE development board is equipped with MediaTek Aster (MT2502) SOC which, according to MediaTek, is the worlds smallest system-on-chip for wearables. It supports GSM, GPRS and Bluetooth LE wireless communication capabilities. The board is also equipped with two companion chipsets; MT5931 (WiFi) and MT3332 (GPS). It is also capable of sending and receiving SMS, play audio files, transfer data over bluetooth and read and write data on a SD card. An interesting feature is that the board is prepared to be powered using a battery. The development kit even comes with a 1000 mAh battery and there are APIs available to get the battery level and charging state.

    Compared to other development kits aimed at the maker community the LinkIt ONE is powerful. The microprocessor is a ARM7 EJ-S which runs at 260 MHz. That is roughly fifteen times faster than an ordinary Arduino Uno. It also has 4MB of RAM and 4MB of flash memory so there is no need to worry about code size.

    If you are curious to learn more about the LinkIt One MediaTek has an excellent developers guide that covers almost everything you need to know in order to start working with their hardware. You can find the guide here.

    Source Code

    You can browse the source code for this tutorial in the Evothings GitHub repository.

    What you need

    • MediaTek LinkIt ONE with GPS antenna & WiFi antenna connected.
    • An iOS or Android smartphone.
    • A computer running Microsoft Windows.

    Step 1 – Hardware

    This tutorial does not require you to build any external circuits at all. However you need to ensure that you connect the GPS and WIFI antenna to the development board according to the picture below. Only the GPS and Wi-Fi antenna is needed in this tutorial.

    mediatek-linkit-one-antenna

    Step 2 – Embedded software

    Preparation

    If you already have installed the LinkIt SDK you can skip this step.

    Before you can start compiling and downloading your software to the board you need to setup the development environment. MediaTek provides an executable that installs all libraries and drivers needed. There is also a detailed step-by-step guide to walk you through the process.

    As for now only Windows is supported. MediaTek has announced future support for Mac OS X and Linux.

    Source code

    This application is a small web server that responds with a JSON object containing the current position regardless of what request it receives. The application is based on two examples (WifiWebServer.ino, GPS.ino) provided by MediaTek that has been merged and modified minimalistically to suit our needs.

    In order to run the application you need to change the WIFI_AP to the name of your access point and the WIFI_PASSWORD to the password of your access point. You also have to provide the encryption of your network in the WIFI_AUTH define.

    In the setup() function the wifi, gps and serial functionality are enabled. You can see the setup function below.

    void setup()
    {
      LTask.begin();
      LWiFi.begin();
      Serial.begin(115200);
      LGPS.powerOn(GPS_GLONASS);
      delay(2000);
    }
    

    In the loop() function the logic of the application is defined. It consists mainly of three parts, one part to ensure that the board is connected to the provided wifi, one part that fetches the position from the GPS chip and the last part that handles any request.

    First let us look more in detail on the part that ensures that the board is connected to the wifi. The logic behind this functionality is defined in the function connectToAccessPoint(). The function first checks to see if it is connect to the access point, if not it will try to connect to it until it succeeds. Once connected to the wifi it will start the server that listens for TCP connections on port 80 and print information about the connection. You can see the implementation below:

    void connectToAccessPoint()
    {
      while (LWiFi.status() != LWIFI_STATUS_CONNECTED)
      {
        if (LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)))
        {
          server.begin();
          printWifiStatus();
        }
        else
        {
          Serial.println("Error - failed to connect to WiFi");
        }
      }
    }
    

    The second part of the code fetches the position, parses the result and stores the positions to the global variables latitude and longitude. We added a scheduling that fetches the position once every 5 seconds. Fetching the position requires three steps, fetch data from GPS chip (LGPS.getData()), parse the result (parseGPGGA()) and finally convert the position to decimal form (convertPostionToDecimalForm()). The parseGPGGA() function has been modified to write the results to global variables instead of local ones. The result from the parseGPGGA() function has to converted from GPGGA format to decimal format. You can read more about that conversion here. The implementation is provided below.

    if (millis() - lastGPSReadTimestamp > gpsReadInterval)
    {
      LGPS.getData(&gpsData);
      parseGPGGA((const char*)gpsData.GPGGA);
      convertPositionToDecimalForm();
      lastGPSReadTimestamp = millis();
    }
    

    The final part of the application sends a JSON-object as response to TCP requests made on port 80. In essence the application awaits a connection and when there is one present it reads every byte in the request until it has received an empty line followed by an ‘\n’. Then the application responds with a JSON object containing the position from the GPS chip.

    Compared to the WifiWebServer tutorial mentioned previously we have modified two parts. First we modified the response. The “Content-Type” header was changed to “application/json” and the “Refresh” header was removed. Also the header “Access-Control-Allow-Origin: *” was added to the response. This is to enable cross domain requests using jQuery which is not usually allowed.

    The other change is that we added a timeout that disconnects the client if there is a delay greater than 1 seconds between bytes received in the request. The implementation can be seen below.

    LWiFiClient client = server.available();
    
    if (client)
    {
      Serial.println("new client");
    
      // an http request ends with a blank line
      boolean currentLineIsBlank = true;
      uint32_t lastReceptionTime = millis();
      while (client.connected())
      {
        if (client.available())
        {
          // we basically ignores client request, but wait for HTTP request end
          int c = client.read();
          lastReceptionTime = millis();
    
          Serial.print((char)c);
    
          if (c == '\n' && currentLineIsBlank)
          {
            Serial.println("send response");
    
            // send a standard http response header
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: application/json");
            client.println("Connection: close");  // close connection after completion 
            client.println("Access-Control-Allow-Origin: *");
            client.println();
            client.print("{\"long\":\"");
            client.print(longitude, 8);
            client.print("\", \"lat\":\"");
            client.print(latitude, 8);
            client.print("\"}");
            client.println();
            break;
          }
          if (c == '\n')
          {
            // you're starting a new line
            currentLineIsBlank = true;
          }
          else if (c != '\r')
          {
            // you've gotten a character on the current line
            currentLineIsBlank = false;
          }
        }
        else
        {
          if (millis() - lastReceptionTime > requestTimeout)
          {
            Serial.println("Error - client timeout, dropping connection...");
            break;
          }
        }
      }
    
      // give the web browser time to receive the data
      delay(500);
    
      // close the connection:
      Serial.println("close connection");
      client.stop();
      Serial.println("client disconnected");
    }
    

    There is also a couple of helper functions which is not covered here since they are not essential.

    Step 3 – Mobile application

    Preparation

    If you already have a fully working copy of Evothings Studio you can skip this step.

    First you have to install the Evothings Studio on your computer. The Evothings Studio consists of two softwares that interacts with each other. You have to install Evothings Workbench on you computer. The software provides you with the interface in which you will perform your development. You also have to install the Evothings Client (iOS, Android) on your smartphone. The client will connect to the workbench and execute the mobile application.

    In order to utilize the Google Maps JavaScript API v3 you need to create an API key. Google describes how to do that here. The API is used to display the position of the LinkIt ONE.

    Source code

    The application fetches the position of the LinkIt ONE from the web server and displays the position on a map.

    The application consists of three files, index.html which contains all the code connected to the user interface, app.css which contains the style sheets of the application and last, app.js which contains all the logic of the application.

    mediatek-linkit-one-startView

    The user interface consists of three views, startView, connectingView and mapView. The startView, see above contains the initial view that is displayed to the user when the application is launched. It makes it possible to connect to the LinkIt ONE board using the IP address. The connectingView is displayed when the user tries to connect to the board. And finally the mapView, which is displayed once the application retrieved a response from the LinkIt ONE board. It contains the map view from the Google Maps API and a disconnect button.

    The app.initializeMap() method is executed when the application and all of its resources has been fully loaded. The method initializes the map provided by the Google Maps JavaScript API. The code that ensures that this happens is placed within the in the index.html and provided below.

    When you press the connect button in the connectingView the method app.connect() is executed. The method hides the connectingView and shows the connectingStatus view. It also defines a recurring timer of 10 seconds, which executes the app.fetchData() method when expiring. And finally the method executes the app.fetchData(). The implementation is provided below.

    app.connect = function() 
    {
      app.IPAdress = $('#IPAdress').val()
    
      $('#startView').hide()
      $('#connectingStatus').text('Connecting to ' + app.IPAdress)
      $('#connectingView').show()
    
      console.log('Trying to connect to ' + app.IPAdress)
    
      app.fetchTimer = 
        setInterval(function() { app.fetchData() }, app.TIME_BETWEEN_REQUESTS)
    
      app.fetchData()
    }
    

    The method app.fetchData() is simply a wrapper that calls the getJSON() method using the app.dataRecived() method as the callback. See the following code:

    app.fetchData = function()
    { 
      console.log('Trying to fetch data...')
    
      $.getJSON('http://' + app.IPAdress, app.dataReceived) 
    }
    

    mediatek-linkit-one-mapView

    When a response is received it is handled by the method app.dataReceived(). First the method shows the view connectingView, see above, if it is visible. It also triggers the event “resize” in the Google Maps API which ensures that the map is redrawn to fit the div. Then the actual data is extracted from the JSON-object which looks like this:

    {"long":18.0374, "lat":59.2030}
    

    The getJSON() method parses and turns the response into a JavaScript object automatically. The extracted longitude and latitude is then used to create a new marker that is added to the Google map view which is centered around the marker. The implementation looks like this:

    app.dataReceived = function(data, textStatus, xhr)
    {
      if ($('#mapView').css('display') == 'none') 
      {
        $('#connectingView').hide()
        $('#mapView').show()
    
        google.maps.event.trigger(app.map, "resize")
        console.log('Showing off')
      }
    
      // Read response
      var longitude = data['long']
      var latitude = data['lat'] 
    
      console.log('Received data - Latitude: ' + latitude + ', Longitude: ' + longitude)
    
      // Remove current marker if available.  
      if (app.marker) 
      {
        app.marker.setMap(null)
      }
    
      // Create a new parker and add it too map.
      var markerPosition = new google.maps.LatLng(latitude, longitude)
      app.marker = new google.maps.Marker({ position: markerPosition })
      app.marker.setMap(app.map)
    
      // Center map around the marker.
      app.map.panTo(app.marker.getPosition())
    }
    

    If you press the disconnect button the <code<app.disconnect() method is executed. It cancels the running timer and hides the mapViewstartView. See the code below.

    app.disconnect = function()
    {
      clearInterval(app.fetchTimer)
    
      $('#mapView').hide()
      $('#startView').show()
    }
    

    The application logic is based around a timer that executes the method app.fetchData() once every 10 seconds. The method simply makes a request to the development board using the jQuery method getJSON(). See the following code.

    Summary

    This tutorial shows how you easily can build your own mobile application that fetches data from your LinkIt ONE using the WiFi interface. There is no time to spare, get a LinkIt ONE and download the source code and Evothings Studio and start to explore the endless possibilities. The tutorial should provide a great starting point for any connected LinkIt ONE project.

    We can not wait to see what you create, please share your creations with either @evothings or our forum.

    Happy tinkering!

    Hands on guide to building a native JavaScript iBeacon app using Cordova

    $
    0
    0

    Kontakt.io beaconThis tutorial shows how to create and build a native iBeacon app written in JavaScript using the Apache Cordova build system. The example app shows how to to range beacons and monitor region enter/exit events. We also explain how to use background notifications on iOS and Android.


    The Cordova iBeacon example app

    The example code for this tutorial is available for download on GitHub. The app runs on both iOS and Android.

    When the app is in the foreground it displays the nearest ranged beacon and a list of region enter/exit events. When the app is running in the background, it displays region enter/exit events as notifications.

    cordova-ibeacon-screenshot-one

    The app displays data for the nearest beacon and a list of region enter/exit events.

    cordova-ibeacon-screenshot-two

    Notifications for region enter/exit events are shown when the app is in the background.

    Overview of iBeacon ranging and monitoring

    For monitoring beacons the plugin cordova-plugin-ibeacon is used.

    Ranging and monitoring are two important concepts when developing beacon apps.

    Ranging continuously displays all beacons found and is active when an app is in the foreground, but not in the background.

    Monitoring only generates events when a region is entered or exited, and works both when the app is in the foreground and in the background.

    A region consists of a beacon UUID, and optional major and minor values. It is common that many beacons share the same UUID. All three values uniquely identify a beacon. You can scan more broadly by specifying only the UUID, or only UUID and major value.

    Here is a code snippet that creates a region and starts monitoring and ranging that region:

    // Create a region object.
    var beaconRegion = new cordova.plugins.locationManager.BeaconRegion(
        region.id,
        region.uuid,
        region.major,
        region.minor);
    
    // Start ranging.
    cordova.plugins.locationManager.startRangingBeaconsInRegion(beaconRegion)
        .fail(errorCallback)
        .done();
    
    // Start monitoring.
    cordova.plugins.locationManager.startMonitoringForRegion(beaconRegion)
        .fail(errorCallback)
        .done();
    

    Ranging and monitoring events will be delivered to delegate functions. Check out the source code in the file www/app.js for an example of how to set up delegate functions for monitoring and ranging.

    For documentation and code examples, visit the cordova-plugin-ibeacon GitHub page.

    How background notifications work

    Background notifications are displayed using the plugin cordova-plugin-local-notifications.

    It is very easy to display a notification:

    cordova.plugins.notification.local.schedule({
        id: 1,
        title: 'Hello World'
        });
    

    New notifications will replace any previous notification with the same id. Use an id counter to display a sequence of notifications. Check out the code in file www/app.js for how this is done.

    Further documentation is found on the GitHub Wiki for the notification plugin.

    Example project setup

    The example project on GitHub consists of a “bare” Cordova project with some minimal settings. What you need to do to build the app is to add plugins and platforms (iOS and/or Android). Plugins and native platform files can take up quite some space, and are therefore not included in the GitHub repo. Below you will learn how to add them.

    HTML and JavaScript code files are found in the www folder. This is the standard location for Cordova application files.

    The file www/index.html contains the UI elements of the app. File www/app.js contains all the JavaScript code for the application. Folder www/libs contains JavaScript libraries used by the app. The folder www/ui contains CSS-files used by Evothings example apps. You can replace the CSS files with your own UI styling or use a JavaScript UI framework to get the desired look and feel.

    Note that the JavaScript library files for the Cordova plugins are implicitly included with cordova.js in www/index.html. The Cordova JavaScript files are not part of the application code in folder www, instead they are provided by the plugins and are automatically added to the app when it is built.

    What you need to modify before the app will work

    Open file www/app.js and edit the variables mRegions and mRegionData to contain the UUIDs and major/minor values of your beacons.

    Install Cordova

    To build native apps you must install both Cordova and Xcode and/or Android SDK depending on which platforms you wish to build for. The Cordova IoT Starter Kit helps you with the installation process.

    How the Cordova project was created

    The following steps have already been performed for the project on GitHub. If you create your Cordova project from scratch, you can use these steps to set up your project.

    First the project was created with this command:

    create cordova-ibeacon com.evothings.cordovaibeacon iBeacon

    Then this line was added to the config.xml file to prevent the view to bounce on scrolling:

    <preference name="DisallowOverscroll" value="true" />

    Finally the files in folder www were deleted and replaced by the example app files.

    Cordova commands to build the app

    To build the app you must have cordova installed (see above).

    Follow these steps to install plugins and build the app.

    Open a command window and go to the app folder, e.g.:

    cd cordova-ibeacon/

    Add plugins (this step is done once):

    cordova plugin add https://github.com/petermetz/cordova-plugin-ibeacon#3.3.0
    cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications#0.8.1

    Note that specific versions of the plugins are added. This is handy to ensure you get a tested version of the plugin. Check the respective plugin repo on GitHub for the current versions and use them in your project.

    Add platform ios if you wish to build for iPhone and iPad (done once):

    cordova platform add ios

    Add platform android if you wish to build apps for Android devices (done once):

    cordova platform add android

    Build the app for the desired platform(s) (do this after each code update):

    cordova build ios
    cordova build android

    For iOS open the Xcode project in folder platforms/ios to deploy and run the app.

    For Android install the app using the adb command (name of APK-file may very depending on the Cordova version used):

    adb install -r platforms/android/ant-build/MainActivity-debug.apk

    Finalising the build

    To get the app ready for publication on the app stores you also want to include custom icons and launch images.

    Use Evothings Studio for a fast workflow

    You can use Evothings Studio to develop Cordova apps with live-reload-on-save. What you do is that you simply hook up your Cordova app to connect to Evothings Workbench by modifying config.xml. Then drag index.html into the Workbench project list and click RUN. Now live reload is enabled!

    Here is a step-by-step guide:

    • Download and run Evothings Workbench on your computer.
    • Open the file config.xml in your Cordova project folder. Edit the content tag to refer to the connect URL displayed at the bottom of the Evothings Workbench project window. This will make the app connect to the Workbench when launched.
    • Here is an example (use actual IP-address displayed in the Workbench window):
      <content src="http://192.168.43.131:4042" />
    • Build the app using one of the following commands and run the app on your phone/tablet:
      cordova build ios
      cordova build android
    • Drag and drop the file index.html to the Workbench project list.
    • Click RUN in the Workbench window. You now have live reload
      enabled, just save the code in your editor and the app reloads.

    Make sure your computer and phone/tablet are on a WiFi network
    that allows connections (client isolation must be off).

    To make it easy to switch between building the production version of the app and the development version that connects to Evothings Workbench you can modify the content tag name and have both tags side by side:

    <xcontent src="index.html" />
    <content src="http://192.168.43.131:4042" />
    

    Learn more

    To learn more read these articles and tutorials:

    It is easy to get started

    Download Evothings Studio and get going right away with creating awesome beacon applications!

    How to make a mobile IoT app for the Facebook Parse data cloud

    $
    0
    0

    evo-parseNow you can create mobile apps in JavaScript that communicate with BLE devices and interact with the Facebook Parse data cloud. In this tutorial we will use a Texas Instruments SensorTag to monitor temperature data and send values to the Parse cloud. Read on to learn more about setting up a Parse account and how to use Evothings Studio to develop an IoT app for the SensorTag that saves cloud data. You can even try out the example if you do not have a SensorTag. It is easy to get started!

    Mobile apps for IoT and cloud data

    A common use case for Internet of Things applications is to collect data from a sensor device and send that data to a cloud service. Examples include health and fitness data, temperature values, or motion tracking data. Commonly BLE devices (Bluetooth Low Energy – Bluetooth Smart) are equipped with sensors and used to track readings. One example of a Sensor device is the Texas Instruments SensorTag.

    When reading data over BLE a mobile application is used to communicate with the sensor device. Thanks to high-level JavaScript libraries, it is easy to set up the BLE communication and read data from the sensors.

    In this tutorial you will learn how to create an app using Evothings Studio that reads temperature values from the SensorTag and sends the data to the Parse cloud.

    Note: If you don’t own a Texas Instruments SensorTag, you can still explore the example code and send data to the Parse cloud. Read on below to learn more.

    What you need

    Here is what you need to get started:

    • Texas Instruments SensorTag – Current example code supports the original CC2541 SensorTag, we are in the process of updating the tisensortag.js library to support the new CC2650 Bluetooth Smart SensorTag. If you do not have a SensorTag, modify the example code as outlined below to try out the Parse cloud functionality.
    • Evothings StudioDownload for OS X, Windows and Linux.
    • Evothings Client app – Install on iOS or Android phones/tablets, get it from Apple App Store or Google Play.
    • WiFi network that allows client connections – Network client isolation must be disabled (that’s a function in a router which prevents two computers and/or phones to find one another)
    • Basic knowledge of Evothings Studio – You can also relax and learn as you go through this tutorial.

    Install Evothings Studio

    The Evothings Studio Starter Kit explains how to install and use Evothings Studio. For the quick version just download the Studio package for your computer and while it’s loading you pick up the Evothings Client free from the app stores.

    Download the example app code

    Download the example code for this tutorial as a zip file. Unzip it and you will find the application files. The app is called “Parse IoT Demo” and contains the code needed to run the app using Evothings Client and Evothings Workbench.

    Set up your Parse account

    Sign up for a Parse account. Then follow the on-screen guides to create a Parse app. The Parse app is a functional unit where you can store data and also add server side code if needed. You can name the app anything you want, we named ours “Evothings Parse”.

    Go to the Quickstart guide and click the “Data” icon. Then click “Web” and then “New project”. You are now presented with the Application ID and JavaScript key and some sample test code.




    Fill in the application IDs in the mobile app

    What you need to do next is to open the file index.html in the mobile app project you’ve downloaded from GitHub.

    Locate the following place in the code and fill in the keys from the Parse web page found under Step 2 (this is the only thing you need to do, no need to do Step 1 or make the SDK test even if they say so):

    // TODO: Insert your Parse Application ID and JavaScript key here.
    Parse.initialize(
        'Parse Application ID',
        'JavaScript key')

    You may also want to make temperature readings more frequent. Default setting in the example is once every minute, which could be reasonable for a production app but does not make for much action when testing. Here is the line to update:

    var temperatureInterval = 60000 // Change to 5000 for 5 second intervals.

    Then save the file index.html

    Run the example app

    To run the app, do as follows:

    • Launch Evothings Workbench
    • Drag the index file index.html to the Workbench project list window, and release
    • Start Evothings Client on your mobile or tablet – you need at least iOS 7 or Android 4.3, and the phone needs to have BLE support.
    • Connect to the Workbench from Evothings Client – Use the same WiFi network for both the Workbench and the mobile and make sure that it allows client connections. Network client isolation must be disabled.
    • Click the RUN button for “Parse IoT Demo” in the Workbench project list.
    • Activate the SensorTag (you currently need the original CC2541 SensorTag, press its side button).
    • Press the on-screen button “Start reading SensorTag”.
    • Now the app should connect to Parse, and start aggregating tag data.

    Inspect data in the Parse Web UI

    Now go to the page where data objects are displayed. The following link should get you there once you’re logged in, choose your newly created Parse project from the list. Select “Core” from the top menu, if the service defaults to “Analytics” and it says you haven’t collected any data yet.

    https://parse.com/apps/

    Click the refresh icon in the upper-right corner to see new incoming values.

    The app saves data by creating objects of type SensorTagReading. There is one new object created for each temperature reading. This may not be the most optimal approach, but hopefully serves the purpose to illustrate the concept of saving sensor data to a data cloud!

    What if I do not have a SensorTag?

    If you do not have a SensorTag you can still test the cloud save functionality.

    First comment out the initialisation of the SensorTag:

    function initialise()
    {
        // initialiseSensorTag()
        initializeParse()
    }

    Next add a timer that writes simulated “temperature” values:

    function initialise()
    {
        // initialiseSensorTag()
        initializeParse()
        initialiseSimulationTimer()
    }
    
    function initialiseSimulationTimer()
    {
        // Timer that updates temperature values.
        setInterval(function() {
            lastTemperatureReading = ((Math.random() * 5) + 20).toFixed(2)
            },
            5000)
    
        // Timer that sends data to the cloud.
        setInterval(onTemperatureTimer, 5000)
    }

    When the app is launched or reloaded, it will automatically start sending simulated values to the Parse cloud. Do not press the “Start” button when using the above code! That will cause errors ;)

    As a next step you can add support for your IoT devices. Visit the Evothings Forum to ask questions and discuss your projects. You can also combine this example with other Evothings examples to create your own apps.

    So many things to parse out there – get started right away

    Download Evothings Studio and get up and running within minutes! Have fun!

    How to use an Arduino Ethernet Shield with the Nordic Semiconductor nRF51-DK

    $
    0
    0

    nrf51-dk-ethernet The Nordic Semiconductor nRF51 Developer Kit, an mbed.org enabled micro-controller, is the first of its kind from Nordic Semiconductor that is compatible with the Arduino UNO rev3 hardware standard – however it lacks any form of on-board Ethernet connectivity.

    It was obvious for us and our hands-on tendencies to figure out exactly how to utilise the Arduino Ethernet Shield and give the nRF51-DK Ethernet support – in this post we’ll show you exactly how we went about doing so!

    Hardware checklist

    In order to walk through this tutorial on your own; you’ll need at least the following equipment:

    It should not be necessary to go into detail what each component is for; the most important thing is you will need to have the nRF51-DK connected to your computer’s USB port for debugging and make sure both are connected to the same network so they can communicate.

    In this tutorial; we will be using a Macbook Pro running Mac OSX 10.9.5 – however, it should be easily adaptable to work with a Windows or Linux environment as well. We are under the assumption that you have previously seen the earlier post where we introduced mbed.org and the nRF51-DK.

    Creating a foundation for our mbed OS application

    In order to create our mbed OS application – we need a simple as possible starting point.

    The simplest starting point that does not bring in too many dependencies is to find a hello world type application – simply press the “Import” button and search for anything of this nature, you should be presented with a list similar to what is shown below. A number of results will be suitable – we only need to have the structure and we’ll be replacing the main.cpp file with our own shortly anyhow.

    nrf41-dk-ethernet-import-program

    We used the most popular example – clicking on the big “Import” button we are presented with:

    nrf41-dk-ethernet-import-program-helloworld

    This is where we can specify the name of our application (mbed-nordic_ethernet) and import it as a program. It is very important to select the checkbox where it asks to update the libraries to the latest revision – failure to do so could result in compiler errors for no reason.

    Integrating an library to support the Ethernet chipset

    A number of micro-controller providers have established integrated Ethernet development boards – such as NXP, freescale and Renesas which the mbed.org team has worked very hard on to provide a generic Ethernet and Socket interfaces that support these boards within the mbed driver layers.

    While investigating the possibility for using such libraries with the nRF51-DK, I came across a question on the mbed.org forums where another developer had asked if the library would support other chipsets; unfortunately the answer provided was:

    No, EthernetInterface is only for the boards listed there, who have an integrated Ethernet peripheral. The F411 does not have this (at least I don’t think it has one, for sure it is not supported). You will need an external ethernet board with its own library.Erik Olieman @ developer.mbed.org

    I also actively participated in the discussion – posting a few suggestions for supporting external boards within the same common Ethernet interface. It would make sense to provide a uniform Ethernet interface regardless if the chipsets are internal or external.

    It was time to do some legwork to see what could be achieved here – not for the faint hearted!

    The first step was to take a look at the Arduino Ethernet Shield hardware specification – as surely there wasn’t going to be a library posted by Arduino for mbed OS on the website. With a bit of digging, via using a magnifying glass to look at the chip manually, searching the internet and finally resorting to the Arduino ethernet driver source code – it was clear the chip being used as a WIZnet 5X00 variant (5100 or 5200 – depending on the revision of the board that you are using).

    After some research; I found a number of libraries that were supposed to support the 5200 variant; however, my board had a 5100 chip and things just didn’t work as expected until finally I came across a WIZnet library that supported all the 5100, 5200 and 5500 chipsets in a single library. It was like finding a needle in a haystack; very welcome as I was on the verge of giving up completely.

    To import this library; use the “Import” button again and search for the “wiznet” library.

    nrf41-dk-ethernet-import-library

    It should be prominently displayed – clicking on the big “Import” button we are presented with:

    nrf41-dk-ethernet-import-library-wiznet

    This is where we can select which program to import it into (mbed-nordic_ethernet) and import it as a library. It is very important to select the checkbox where it asks to update the sub-libraries to the latest revision again – failure to do so could result in compiler errors for no reason.

    Unfortunately; If you look closely at the resulting project – you will see that the WIZnet library also includes a main.cpp and mbed asset. If you try to compile the project in this state – the compiler will complain that there are two main() functions defined. The best thing to do is simply delete the main.cpp that exists within the WIZnet_Library folder – as shown below.

    nrf41-dk-ethernet-import-library-post_actions

    If you are a purist like myself; you could also delete the mbed resource in the library folder – as you can see we obtained that when we imported the hello world program. They may have structured it this way so the library could be imported as a program with a example to start working from.

    In any event; we’ve taken the example provided – fixed a few bugs and made it clearer for you to understand so it will just be a matter of replacing the contents of the main.cpp file within the root of the project to complete this tutorial and keep it as simple as possible.

    Modifying the WIZnet example for the nRF51-DK

    This is where the real fun starts and you get your hands really dirty – but bear with us!

    Since we deleted the main.cpp file earlier – we will need to use a reference copy of the file which is readily available on the mbed.org code repo – inside you will see a little bit of code where you set the platform you wish to target, if you have one of these boards you are good to go!

    /** 
     * Setting the platform to test
     */
      #define LPC
    //#define ST_NUCLEO
    //#define FRDM_KL25Z
    //#define Seeeduino_Arch
    

    Every micro-controller may end up with different pin mappings and we need to let the library know which ones to use. Unfortunately; the Nordic Semiconductor nRF51-DK is not in this list so we are going to have to find the correct pin assignments to make the library work with the hardware.

    The Arduino Ethernet Shield requires pins for its SPI interface and since the shield also has a dual purpose, there is a selector pin to switch modes between the Ethernet and SD card functionalities provided on the shield. In micro-controller speak; we need to find mappings for MOSI, MISO, SCLK, CS (cable select) and RESET so the library knows which pins to send digital signals to.

    Arduino nRF51-DK
    MOSI 11 / ICSP-4 P0_25
    MISO 12 / ICSP-1 P0_28
    SCLK 13 / ICSP-3 P0_29
    CS 10 P0_24
    RESET ICSP-5 P0_0

    The Arduino Ethernet Shield also has an ICSP header; however in testing it was evident these were not interfacable. We do not technically require the RESET pin, but since the library tries to interact with it we just map it to P0_0. The resulting configuration of the spi and eth objects are:

    SPI spi(P0_25, P0_28, P0_29);              // MOSI, MISO, SCLK
    WIZnetInterface eth(&spi, P0_24, P0_0);    // spi, CS, RESET
    

    A modified version of the sample application provided in the library (with a few fixes) and cleaned up for simplicity is below – simply cut and paste this into the main.cpp file within the root of the project. If you have not yet removed the main.cpp file in the WizNet_Library directory – you should do this now to prevent conflicts when compiling.

    /*
     *  Echo program for nRF51-DK with Arduino Ethernet shield using mbed.org
     */
    
    #include "mbed.h"
    #include "WIZnetInterface.h"
    
    #define INFO(x, ...)    printf("[main.cpp:INFO] "x"",     ##__VA_ARGS__);
    #define INFO_NL(x, ...) printf("[main.cpp:INFO] "x"\r\n", ##__VA_ARGS__);
    
    #define USE_DHCP
    #define ECHO_PORT 5000
    
    #ifndef USE_DHCP
    const char *IP_Addr    = "192.168.1.2";
    const char *IP_Subnet  = "255.255.255.0";
    const char *IP_Gateway = "192.168.1.1";    // put your own values here
    #endif
    
    SPI spi(P0_25, P0_28, P0_29);              // MOSI, MISO, SCLK
    WIZnetInterface eth(&spi, P0_24, P0_0);    // spi, CS, RESET
    Serial pc(USBTX,USBRX);
    
    int main()
    {
        uint8_t mac[6];
        
        // set these to match the mac address on the Arduino Ethernet Shield
        mac[0] = 0x90; mac[1] = 0xa2; mac[2] = 0xda; 
        mac[3] = 0x0f; mac[4] = 0x0e; mac[5] = 0x63;  // 90:a2:da:0f:0e:63
        
        INFO_NL("Start");
    #ifdef USE_DHCP
        int ret = eth.init(mac);
    #else
        int ret = eth.init(mac, IP_Addr, IP_Subnet, IP_Gateway); 
    #endif
    
        if (!ret) { INFO_NL("Initialized, MAC: %s", eth.getMACAddress()); } 
        else      { INFO_NL("Error eth.init() - ret = %d", ret); return -1; }
    
        ret = eth.connect();
        if (!ret) { INFO_NL("IP: %s, MASK: %s, GW: %s",
                            eth.getIPAddress(), 
                            eth.getNetworkMask(),
                            eth.getGateway()); } 
        else      { INFO_NL("Error eth.connect() - ret = %d", ret); return -1; }
    
        TCPSocketServer server;
        server.bind(ECHO_PORT);
        server.listen();
    
        while (true) 
        {
            INFO_NL("Wait for new connection...");
            
            TCPSocketConnection client;
            server.accept(client);
            
            INFO_NL("Connection from: %s", client.get_address());
            char buffer[256];
            while (true) 
            {
                int n = client.receive(buffer, sizeof(buffer) - 1);
                if (n <= 2) break;
                buffer[n] = 0;            
                INFO(" %s", buffer);
    
                client.send_all(buffer, n);
            }
            INFO_NL("Connection closed");
    
            client.close();
        }
    }

    The WIZnet library supports three different variants of the W5X00 chipset – by default the assuming the use of the W5500 chipset, which is configured within the header file stored in the libary under WIZnet_Library/WIZNetInterface/WIZnet/wiznet.h – as shown below.

      #define USE_W5500
    //#define USE_W5200
    //#define USE_W5100

    It is vital to change the #define used to match the chipset that is provided with your Arduino Ethernet Shield. If you are running into issues – try the various variants; we had to use W5100.

    Compiling and flashing the program

    Within the compiler view on the mbed.org developer site select the target platform – in this case it will be the platform named “Nordic nRF51-DK” and then press the “Compile” button within the web based IDE. If everything goes ok; it should offer you the following file for download:

    mbed-nordic_ethernet_NRF51_DK.hex

    Simply connect the nRF51-DK to the computer and copy the hex file to the external storage medium that is presented. We covered the deployment process in our previous post with the nRF51-DK. Now that the application has been flashed to the nRF51-DK it is time to see it in action!

    Verification and seeing it in action!

    Ensure that the nRF51-DK is freshly connected to the USB port of your computer; the easiest way to make sure is to disconnected it and reconnected it so that we do not run into any conflicts with the device being busy. After a few seconds, our application should be executing.

    The easiest way to find out if the device has established a network connection is to look at the debugging logs our program has written to the console – to do this, we must establish a connection to the USB port using a serial program; such as screen within a Terminal session.

    $ screen /dev/tty.usbmodem1411
    
    [main.cpp:INFO] Initialized, MAC: 90:A2:DA:0F:0E:63
    [main.cpp:INFO] IP: 192.168.1.136, MASK: 255.255.255.0, GW: 192.168.1.1
    [main.cpp:INFO] Wait for new connection...
    

    Your nRF51-DK may have a different name to /dev/tty.usbmodem1411 however it will be very similar to this; if you are on Mac OSX or Linux they have this type of name, on Windows of course this would be a COMxx port and you could also use a program like HyperTerminal (instead of screen) to establish communication with the board.

    The debugging output shows the board has the IP address of 192.168.1.136. This is all the information we need to know so we can attempt to establish a telnet connection on port 5000 to the device – which of course needs to be done in a separate Terminal session.

    $ telnet 192.168.1.136 5000
    Trying 192.168.1.136...
    Connected to 192.168.1.136.
    Escape character is '^]'.
    

    At this point – we can see the debugging console should have also accepted a connection – simply type some text and whatever you enter will be echoed back to your session and be simultaneously presented in the debugging console. To close the connection; simply press enter twice.

    A screen capture of the debugging console and the communication console is shown below:

    nrf51-dk-ethernet-demo

    You should see something similar – if so you have verified adding Ethernet support to the nRF51-DK.

    Why not take a moment to download Evothings Studio and see if you can write a mobile application that communicates with the nRF51-DK over TCP/IP; a great example called Arduino LED On/Off TCP would not be difficult to modify and get working with the nRF51-DK.

    We would love to continue our series working with the Nordic Semiconductor nRF51-DK; if you would like to see anything specific or have any questions about how to work with these devices and create some cool and interesting products – why not head over to our forums and let us know!

    How to turn a Nordic Semiconductor nRF51-DK into a discoverable beacon using mbed

    $
    0
    0

    nRF51-DKThe Nordic Semiconductor nRF51-DK, an mbed enabled micro-controller is getting a lot of attention from us lately – we first showed you how to get started with mbed and how to connect an Arduino Ethernet Shield to give the device internet connectivity. It was only a matter of time before we started to explore the Bluetooth Smart (BLE) capabilities of mbed and actually write an application to interact with it.

    Hardware and Software checklist

    In order to walk through this tutorial on your own, you’ll need at least the following equipment:

    • Computer (Windows, Mac OSX, Linux)
    • Nordic Semiconductor nRF51-DK
    • a copy of Evothings Studio installed on your computer
    • a mobile phone or device running Evothings Client
    • microUSB communications cable
    • limited skill set with a command line prompt for testing/debugging

    This tutorial will consist of two parts. First of all, we will explain a few details about BLE on mbed and writing an mbed application for the nRF51-DK. In the second part, we will launch an application using Evothings Studio that will allow two-way communication with the nRF51-DK from a mobile device.

    The full source code for this tutorial is available for download (nRF51-dk-ble.zip).

    The primary focus for this tutorial will be on explaining how BLE works within mbed and get an example running on the nRF51-DK device. While a mobile application is provided in the source package – we will not be going into the development specifics and simply use the it as-is.

    nRF51-DK: firmware and mbed development

    Creating a foundation for our mbed OS application

    Much like we did in the previous blog post, we need to create ourselves a foundation to work from.

    The simplest starting point that does not bring in too many dependencies is to find a hello world type application – simply press the “Import” button and search for anything of this nature, you should be presented with a list similar to what is shown below. A number of results will be suitable – we only need to have the structure and we’ll be replacing the main.cpp file with our own shortly anyhow.

    nrf41-dk-ethernet-import-program

    We used the most popular example – clicking on the big “Import” button we are presented with:

    nrf41-dk-bledevice-import-program-helloworld

    This is where we can specify the name of our application (mbed-nordic_bledevice) and import it as a program. It is very important to select the checkbox where it asks to update the libraries to the latest revision – failure to do so could result in compiler errors for no reason.

    Integrating an library to support the Bluetooth Smart (BLE) chipset

    We will be using the high level abstraction Bluetooth Low Energy library provided within the mbed development environment and will also need to pair it with the nRF51822 bluetooth stack and driver for the nRF51-DK hardware.

    Use the “Import” button like earlier and search for the “BLE_API” library.

    nrf41-dk-bledevice-import-library-1

    It should be prominently displayed – clicking on the big “Import” button we are presented with:

    nrf41-dk-bledevice-import-library-ble_api

    This is where we can select which program to import it into (mbed-nordic_bledevice) and import it as a library. It is very important to select the checkbox where it asks to update the sub-libraries to the latest revision again – failure to do so could result in compiler errors for no reason.

    Use the “Import” button again and search for the “nRF51822″ library from Nordic Semiconductor.

    nrf41-dk-bledevice-import-library-2

    It should be prominently displayed – clicking on the big “Import” button we are presented with:

    nrf41-dk-bledevice-import-library-nrf51822

    This is where we can select which program to import it into (mbed-nordic_bledevice) and import it as a library. It is very important to select the checkbox where it asks to update the sub-libraries to the latest revision again – failure to do so could result in compiler errors for no reason.

    Nordic Semiconductor also has put together a simple beacon-like library called Nordic Pucks, however in this tutorial we wanted to keep it as simple as possible and focus on the bare basics. The library was only recently updated and we were having some small issues with it – so we simplified things by doing barebones BLE.

    Creating your first BLE device in mbed

    If you are not up-to-date with how Bluetooth Smart (BLE) works, then it would definitely pay to do a little bit of reading up on the topic. We posted an introduction to BLE a little while ago and it is a great pre-cursor to this tutorial as it covers everything we need to know.

    Great – lets get our hands dirty!

    To get us started; we’ll need to define a name for the device and a service and a number of characteristics that we will need to expose on the device.

    // name of the device 
    const static char DEVICE_NAME[] = "nRF51-DK";
    
    // GATT service and characteristic UUIDs
    const UUID nRF51_GATT_SERVICE     = UUID((uint8_t *)"nRF51-DK        ");
    const UUID nRF51_GATT_CHAR_BUTTON = UUID((uint8_t *)"nRF51-DK button ");
    const UUID nRF51_GATT_CHAR_LED    = UUID((uint8_t *)"nRF51-DK led    ");

    The BLE library provides a great little class called UUID that takes an array of 16 bytes and converts them into UUID objects we can use. It is nice we can define whatever we like here – the resulting human readable UUID’s created are:

    nRF51_GATT_SERVICE:     6e524635-312d-444b-2020-202020202020
    nRF51_GATT_CHAR_BUTTON: 6e524635-312d-444b-2062-7574746f6e20
    nRF51_GATT_CHAR_LED:    6e524635-312d-444b-206c-656420202020

    We will need to know these for when we create our mobile application a little later on. You could use any string – just as long as they are unique. Effectively the class simply takes the 16 byte values and concatenates them to create a 128bit UUID.

    Our goal is to create a single service, with two characteristics – one of them to show the state of the buttons on the device and the other to control the four LEDs present on the board. It gives us the perfect use case to cover both reading a characteristic and writing a a value to a characteristic.

    We do need some global variables for this task however:

    #define CHARACTERISTIC_BUTTON 0
    #define CHARACTERISTIC_LED    1
    #define CHARACTERISTIC_COUNT  2
    
    // our bluetooth smart objects
    BLEDevice           ble;
    GattService        *gatt_service;
    GattCharacteristic *gatt_characteristics[CHARACTERISTIC_COUNT];
    uint8_t             gatt_char_value[CHARACTERISTIC_COUNT];

    We have defined an object for the BLE device itself, a GattService reference and an array of GattCharacteristic references – it has been done like this for simplicity later (which you will see). In this tutorial we are only going to be dealing with characteristics that are single byte – however, you are able to use more if you need. The data will be stored within the array gatt_char_value.

    To create these objects, we simply perform the following:

        // create our button characteristic (read, notify)
        gatt_characteristics[CHARACTERISTIC_BUTTON] = 
          new GattCharacteristic(
                nRF51_GATT_CHAR_BUTTON, 
                &gatt_char_value[CHARACTERISTIC_BUTTON], 1, 1,
                GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | 
                GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);
    
        // create our LED characteristic (read, write)
        gatt_characteristics[CHARACTERISTIC_LED] = 
          new GattCharacteristic(
                nRF51_GATT_CHAR_LED, 
                &gatt_char_value[CHARACTERISTIC_LED], 1, 1,
                GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | 
                GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | 
                GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);
    
        // create our service, with both characteristics
        gatt_service = 
          new GattService(nRF51_GATT_SERVICE, 
                          gatt_characteristics, CHARACTERISTIC_COUNT);

    The characteristic nRF51_GATT_CHAR_BUTTON is one byte long and has both read and notify properties associated with it. This allows anyone to read the value and also subscribe for notifications when the value is changed. The characteristic nRF51_GATT_CHAR_LED is also one byte long and has read and write properties associated with it – this allows anyone read the value and change it.

    Finally we create the service using a reference to the previously defined characteristics.

    The next step is to create our BLEDevice object instance and do the necessary house-keeping so the device correctly advertises itself and is connectable by name.

        // initialize our ble device
        ble.init();
        ble.setDeviceName((uint8_t *)DEVICE_NAME);
    
        // configure our advertising type, payload and interval
        ble.accumulateAdvertisingPayload(
              GapAdvertisingData::BREDR_NOT_SUPPORTED | 
              GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
        ble.accumulateAdvertisingPayload(
              GapAdvertisingData::COMPLETE_LOCAL_NAME, 
              (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
        ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
        ble.setAdvertisingInterval(160); // 100ms
    
        // configure our callbacks
        ble.onDisconnection(onDisconnection);
        ble.onConnection(onConnection);
        ble.onDataWritten(onDataWritten);
    
        // add our gatt service with two characteristics
        ble.addService(*gatt_service);
    
        // start advertising
        ble.startAdvertising();
    
        // let the device do its thing
        for (;;)
        {
          ble.waitForEvent();
        }

    This is the bare bones setup for the most simplest of BLE devices – it is however important that we have some callbacks defined to handle connection, disconnection and have our application be notified when data is read or written to the device. It is important to start advertising again when a device disconnects – otherwise it wont be visible.

    The final step is to put the device in an infinite loop and let the BLE subsystem deal with handling the various events. It is possible to do other things within this loop – it is only important to periodically call waitForEvent() to allow the device to do its thing.

    Defining hooks for monitoring button states and toggling the LEDs

    To monitor the button states; we needcall to utilize a Ticker object once setup periodically calls a function that does all the leg work and changes the characteristic to reflect the button state.

        // start monitoring the buttons and posting new values
        Ticker ticker;
        ticker.attach(monitorButtons, 0.1);  // every 10th of a second

    We can place this just before the infinite loop, but not before we start advertising the device as we’ll need to have the device active when the callback is called.

    // define our digital in values we will be using for the characteristic
    DigitalIn button1(P0_17);
    DigitalIn button2(P0_18);
    DigitalIn button3(P0_19);
    DigitalIn button4(P0_20);
    
    uint8_t button_new_value = 0;
    uint8_t button_old_value = button_new_value;
    
    void monitorButtons() 
    {
        // read in the buttons, mapped into nibble (0000 = all off, 1111 = all on)
        button_new_value = 0;
        button_new_value |= (button1.read() != 1); button_new_value <<= 1;
        button_new_value |= (button2.read() != 1); button_new_value <<= 1;
        button_new_value |= (button3.read() != 1); button_new_value <<= 1;
        button_new_value |= (button4.read() != 1); 
          
        // set the updated value of the characteristic if data has changed
        if (button_new_value != button_old_value)
        {
            ble.updateCharacteristicValue(
                  gatt_characteristics[CHARACTERISTIC_BUTTON] -> getValueHandle(),
                  &button_new_value, sizeof(button_new_value));
            button_old_value = button_new_value;
        }
    }

    The buttons are represented by the digital pins P0_17, P0_18, P0_19 and P0_20 – we simply configure some DigitalIn objects to interface with them and read their values and create an integer from the various states. When none of the buttons are pressed, this value will be zero (0000 in binary) and when all of them are pressed it will be fifteen (1111 in binary) – a total of sixteen possibilities depending on which buttons are pressed simultaneously.

    Publishing the value over BLE only needs to be done when it changes from its current value and it simply involves invoking the updateCharacteristicValue function using the characteristic handle, providing the new value and its size in bytes.

    The LED handling is not much different:

    DigitalOut led1(P0_21);
    DigitalOut led2(P0_22);
    DigitalOut led3(P0_23);
    DigitalOut led4(P0_24);
    
    uint8_t led_value = 0;
    
    void onLedDataWritten(const uint8_t* value, uint8_t length) 
    {
        // we only care about a single byte
        led_value = value[0];
    
        // depending on the value coming through; set/unset LED's
        if ((led_value & 0x01) != 0) led1.write(0); else led1.write(1);
        if ((led_value & 0x02) != 0) led2.write(0); else led2.write(1);
        if ((led_value & 0x04) != 0) led3.write(0); else led3.write(1);
        if ((led_value & 0x08) != 0) led4.write(0); else led4.write(1);
    }

    In this case; we are using the DigitalOut object and the digital pings P0_21, P0_22, P0_23 and P0_24. Depending on the individual bits that are set or not in the value, we can determine the state the LED needs to be (ON or OFF).

    The question your asking now is: “When does the onLedDataWritten callback function get called?”

    We mentioned earlier the notion of creating some callback functions that occur when particular events occur on the device – one of them was to respond when data has been written to the device:

    void onDataWritten(const GattCharacteristicWriteCBParams *context) 
    {
      // was the characteristic being written to nRF51_GATT_CHAR_LED? 
      if (context -> charHandle == 
          gatt_characteristics[CHARACTERISTIC_LED] -> getValueHandle())
      {
        onLedDataWritten(context -> data, context -> len);
      } 
    }

    We simply need to check the context of the event and determine if the characteristic that was modified was in fact the one represented by nRF51_GATT_CHAR_LED. If it is; then the onLedDataWritten function is called with the data and length of the information provided.

    Compiling and flashing the program

    Within the compiler view on the mbed.org developer site select the target platform – in this case it will be the platform named “Nordic nRF51-DK” and then press the “Compile” button within the web based IDE. If everything goes ok; it should offer you the following file for download:

    mbed-nordic_bledevice_NRF51_DK.hex

    Simply connect the nRF51-DK to the computer and copy the hex file to the external storage medium that is presented. We covered the deployment process in our previous post with the nRF51-DK. Now that the application has been flashed to the nRF51-DK it is time to see it in action!

    Verification and making sure it is working!

    Ensure that the nRF51-DK is freshly connected to the USB port of your computer; the easiest way to make sure is to disconnected it and reconnected it so that we do not run into any conflicts with the device being busy. After a few seconds, our application should be executing.

    The easiest way to find out if the device has established a network connection is to look at the debugging logs our program has written to the console – to do this, we must establish a connection to the USB port using a serial program; such as screen within a Terminal session.

    We should see something like the following:

    $ screen /dev/tty.usbmodem1411
    
    >> nRF51-DK start
    >> initialized device 'nRF51-DK'
    >> configured advertising type, payload and interval
    >> registered for callbacks
    >> added GATT service with two characteristics
     : 6e524635-312d-444b-2020-202020202020
      :: 6e524635-312d-444b-2062-7574746f6e20
      :: 6e524635-312d-444b-206c-656420202020
    >> device advertising
    >> monitoring button state
    >> waiting for events 

    Your nRF51-DK may have a different name to /dev/tty.usbmodem1411 however it will be very similar to this; if you are on Mac OSX or Linux they have this type of name, on Windows of course this would be a COMxx port and you could also use a program like HyperTerminal (instead of screen) to establish communication with the board.

    The nRF51-DK should now be ready for use – to validate it is discoverable and connectable, you can use any BLE discovery application on compatible hardware – we even have an example that does just this.

    nRF51-DK: mobile application in Evothings Studio

    Install Evothings Studio

    The Evothings Studio Starter Kit explains how to install and use Evothings Studio. For the quick version just download the Studio package for your computer and while it’s loading you pick up the Evothings Client free from the app stores.

    Deploy the nRF51-DK Evothings application

    Locate the index.html file within the source code bundle you downloaded earlier and drag it into the Evothings Workbench window. The program Nordic Semiconductor nRF51-DK should appear in the list of applications available from the workbench.

    Start the Evothings Client application on your mobile device and scan and connect to the workbench. Once connected you can then press the RUN button to deploy the application on your mobile device.

    nRF51-dk-ble

    At this point you can connect to the nRF51-DK device, turn on and off each of the LEDs and press the hardware buttons to your hearts content and see the values being reflected on the mobile device. There is also some logging on the console when a button is pressed or the LED characteristic is written to.

    We have kept the coverage of the mobile application development to a minimum – the focus was to figure out BLE on mbed with the nRF51-DK – you can take a look at a few examples we have done previously. You are more than willing to poke around the source code and see how it is put together.

    If you have any questions, do not hesitate to post them in our forum.

    Happy tinkering!


    Evothings Studio 1.2 officially released

    $
    0
    0

    Stockholm
    May 7, 2015

    Evothings Studio 1.2 officially released – Get started to build mobile apps for IoT in just five minutes!

    This release has several new examples and templates, supporting various new forms of hardware.

    Evothings Studio now supports the new TI SensorTag CC2650 for developing wearables and other sensor-centric applications. Our TI SensorTag JavaScript library (supporting both CC2650 and CC2541) has been refactored and extended to become even more capable and developer-friendly. API design is as much about usability as UI design.

    Our friends at ARM mbed have courteously contributed with examples covering mbed Custom GAP and mbed Custom GATT services, allowing Evothings support for devices compliant with the mbed architecture, like the Nordic Semiconductor nRF51 DK BLE developer kit.

    You’ll also find a brand new Apache Cordova getting-started example that shows how to use the phone’s on-board accelerometer to create events like controlling graphics, and with vibration! A goodie for HTML5 UI craftsmen is that the FastClick library (for cleverly circumventing the infamous 300ms touch event) is now included in all examples, to support a great user experience.

    Explore these links to get started with the new release:

    Download Evothings Studio
    evothings.com/download

    Evothings Studio documentation
    evothings.com/doc

    Release notes
    evothings.com/doc/studio/release-notes.html

    TI SensorTag examples
    evothings.com/doc/examples/ble-ti-sensortag-accelerometer.html
    evothings.com/doc/examples/ble-ti-sensortag-sensors.html
    evothings.com/doc/examples/ble-ti-sensortag-cc2650-demo.html

    ARM mbed examples
    evothings.com/evothings.com/doc/examples/mbed-custom-gap.html
    evothings.com/evothings.com/doc/examples/mbed-custom-gatt.html

    Apache Cordova accelerometer example
    http://evothings.com/evothings.com/doc/examples/cordova-accelerometer.html

    Give Evothings Studio a go right away — it takes just 5 minutes to get started with building amazing IoT apps!
    evothings.com/download (and our developer apps at the public app stores, search for “evothings”)

    We’re most excited to hear what you think and any new things you’ve been working on. We’re evothings on Twitter and we love feedback!

    TI SensorTag Starter Kit

    $
    0
    0

    TISensorTagCC2650_FrontIn this Starter Kit you will find everything needed to get started with creating mobile applications in JavaScript for the TI Bluetooth Smart SensorTag. With the SensorTag and Evothings Studio it is very easy to prototype and develop novel mobile IoT applications that can use all sorts of sensor data available to produce many types of applications. Read on to find out how to get started!

    IoT made easy with the TI SensorTag

    The TI Bluetooth Smart SensorTag is a new type of smart device that packs many different sensors into a small battery-powered unit. You can use the SensorTag for a wide variety of IoT applications.

    It is perfect to use the device for quick prototyping, for example new kinds of fitness applications, various sensor-based alarms, interaction devices that use the accelerometer/gyroscope, game controllers, smartwatch prototypes, sports sensors and much more. For all these, mobile applications play a central role to display information to the end user.

    With Evothings Studio it is easy to prototype and develop IoT applications that use the SensorTag. Use the open-source Evothings JavaScript library for the Bluetooth Smart SensorTag to get started quickly – it takes care of all the heavy lifting and both iOS and Android are supported. Find out the details below.

    The Bluetooth Smart SensorTag uses Bluetooth Low Energy (BLE) to communicate with a mobile phone or tablet. There are also upcoming versions for WiFi and for 6LoWPAN/ZigBee. Support for these will be added to the Evothings Studio as they become available.

    What you need to get started

    Here is what you need to get up and running:

    • TI Bluetooth Smart SensorTag (order at the TI web site)
    • Evothings Studio (download for OS X, Windows and Linux)
    • Evothings Client app (install on iOS or Android phones/tablets, get it from Apple App Store or Google Play)
    • WiFi network that allows client connections (network client isolation must be disabled)
    • Basic knowledge of Evothings Studio (you can also learn as you go through this tutorial)
    • To build an application to distribute yourself you will need the Apache Cordova build tools

    Good to know

    If you are new to Evothings Studio, take a moment to read the Introduction in the documentation to get a basic understanding of the development tools used. We also recommend reviewing the Evothings Starter Kit.

    Apache Cordova is a build system for creating native apps developed in HTML5 and JavaScript. You can use Evothings Studio without Cordova as we provide the Evothings Client app to run your applications in, but if you want to create your own application for publishing it is required. We have written a lot more on this topic in the Cordova IoT Starter Kit.

    Run the example apps

    Try out the TI SensorTag Accelerometer example

    The quickest way to get started with the device and the development environment is to explore the SensorTag example apps that comes with the Evothings Studio download:

    • Launch Evothings Workbench on your computer
    • Launch Evothings Client on your mobile phone(s), press SCAN and connect to the Workbench running on your computer
    • Locate the example app “TI SensorTag Accelerometer” in the Workbench project list
    • Click RUN
    • Activate the SensorTag by clicking the activate button on the tag (see picture below)
    • Hold the SensorTag with front side up and tilt it to move the Evothings Logo on the screen.

    TISensorTagCC2650_Instructions

    Make changes to the code

    Next step is to try out making some changes to the code:

    • Click CODE – this opens a file browser with the source code of the app
    • Open file index.html in a text editor and make some changes to the code. For example, change size of the #sprite element by changing the CSS width to this: width: 100px;
    • Save the file
    • The app will reload on all the connected mobile device(s) and reflect the updates

    You can also change the image file sprite.svg to your own image. Any image file (PNG, JPG, GIF) work just fine, but remember to update the image reference in the HTML code, for example:

    <img id="sprite" src="MyImage.png" />

    Explore more example apps

    You should also explore the other example apps for the SensorTag. Here is a quick overview of the examples:

    • TI SensorTag Accelerometer – move a UI object using the accelerometer (this example uses the high-level library tisensortag.js)
    • TI SensorTag Sensors – displays all the sensors available (uses the high-level library tisensortag.js)
    • TI SensorTag Demo – Charts sensor data on an HTML5 canvas (this is a low-level example that writes/read directly to the BLE services and characteristics of the SensorTag)

    The TI SensorTag JavaScript library

    The SensorTag high-level JavaScript library is in file tisensortag.js – it uses the easyble.js library which in turn uses the underlying native cordova-ble plugin. It has been written in a way to work transparently with the original SensorTag and the latest one available from TI.

    On the Evothings API overview page you will find more information about these libraries and links to technical documentation.

    A good way to get started is to examine the TI SensorTag Sensors example app that comes with Evothings Studio and see how the tisensortag.js library is used. This example is quite elaborate, and for a smaller example check out TI SensorTag Accelerometer.

    How to create a custom SensorTag app

    An Evothings application is just a folder with HTML/JavaScript files (and other assets such as CSS files and images). The minimal project is just a single HTML file.

    A project needs to have a main HTML file, which is the file launched when the app starts. This file is typically named “index.html”. Simply drag and drop your main HTML file into the Workbench project list, it will be added seamlessly and then click RUN to start it.

    Here is a quick summary of the steps required to create an app for use with Evothings Studio:

    • Create a folder for the app
    • Create content files (HTML, JavaScript, CSS, etc)
    • Add any JavaScript libraries needed
    • Drag the main HTML file into the Workbench window
    • Click RUN

    A quick and easy way to create a custom application is to just copy an example app and modify it. You can use the one of the SensorTag example app, or any of the example apps as a starting point.

    Build a native app

    In order to build a native app, you will need to generate a Cordova project and copy or move your files to the “www” folder in the Cordova project. Read more about Cordova and how it works in the Cordova IoT Starter Kit.

    Useful links

    Get started now – up and running in 5 minutes

    With Evothings Studio it is easy to prototype and develop IoT applications. Download Evothings Studio now and spend 5 minutes to get started. Order the TI SensorTag and familiarize yourself with Evothings Studio to be ready to hack away upon delivery of the device!

    Using extra Cordova plugins with Evothings Studio

    $
    0
    0
    The app that utilizes the Cordova SMS plugin.

    The app that utilizes the Cordova SMS plugin.

    Evothings Client is essentially an app made using Apache Cordova; it works by making use of a number of selected Cordova plugins that mostly cover the needs of today’s IoT developer. These plugins come prepackaged with the Evothings Client that can be downloaded from the app stores. However, there can be a scenario where you need to integrate your own custom Cordova plugin or use extra plugins from the Cordova plugin registry. In such cases, you can build your own Evothings Client by making use of the Evothings repositories already available on GitHub.

    In this tutorial, we will build a custom Evothings Client app from the source code and in the mean time we will integrate an extra Cordova SMS Plugin from the Cordova Plugins Registry.

    Downloading the dependency packages

    First, we need to install the following packages on our computer:

    • Node.js with npm module (latest version)
    • Ruby with redcarpet gem (latest version)
    • Cordova (version 5.0)
    • Git

    On Windows, choose the option of using Git from the Windows Command Prompt during Git installation, because this makes things easier.

    For building the app for Android also the following are needed:

    For building the app for iOS also the following are needed:

    • OS X
    • Xcode

    Next, clone the following Evothings Client repositories in a same-level directory:

    Clone these repositories using Git commands or use a Git GUI Client, downloading them as zip files will lead to git errors at build time. For example, in the command line write the following commands:

    
    git clone https://github.com/evothings/evothings-client
    git clone https://github.com/evothings/evothings-examples
    Both repositories should be placed in a same-level directory.

    Both repositories should be placed in a same-level directory.

    Creating a Local Configuration file

    Next, create a new file called localConfig.rb inside the evothings-client directory and paste the below ruby script in the file:

    
    @extraPlugins = [ {
    :name => 'com.cordova.plugins.sms',
    :remote => 'https://github.com/cordova-sms/cordova-sms-plugin'
    } ]

    In the name attribute, provide the ID of the new plugin and give URL of plugin’s git repository in remote attribute.

    The optional localConfig.rb allows you to specify some other options as well. You can also download or clone the plugin locally and specify its path like below:

    
    {:name => 'com.cordova.plugins.sms', :location => '../cordova-sms-plugin'}

    If a plugin is available in Cordova plugin registry, simply specifying it’s ID in name attribute will do all the work:

    
    {:name=>'com.cordova.plugins.sms'}

    If you want the script to first try fetching the plugin from local directory and if not found then go to a remote location and clone the plugin, and also want to document it just like other plugins included in Evothings Client, specify the options like below:

    
    {
    :name => 'com.cordova.plugins.sms', :doc => MarkdownDocumenter.new('readme.md'), :location => '../cordova-sms-plugin', :remote => 'https://github.com/cordova-sms/cordova-sms-plugin'
    }

    Running the Build Script

    Now, find a ruby script called “workfile.rb” in the evothings-client directory. Running this file does all the magic, i.e. it fetches all the required plugins and does all the necessary configurations to get Evothings Client in ship-shape.

    To run workfile.rb, open your favorite command line console and run the following command:

    ruby workfile.rb

    This will build the Evothings Client app for you, by default the command will build the app for Android.

    Note that on Windows you should either run the command from within the Git Bash shell, or in the Git installation choose the option of using Git from the Windows Command Prompt, otherwise Git won’t be found by the script.

    Build Script Options

    You may want to build the client app for iOS or Windows Phone 8 or may want to clean the target platform and build again. Conveniently, the workfile.rb script can handle all these requirements; following is the list of build switches that you can use:

    c – clean target platform before building
    ca – clean everything before building (removes platforms, plugins and documentation)
    i – install after building
    android – build Android
    wp8 – build Windows Phone 8
    ios – build iOS
    doc – build documentation instead of Cordova app

    Examples will be:

    ruby workfile.rb
    ruby workfile.rb i
    ruby workfile.rb c i
    ruby workfile.rb ios
    ruby workfile.rb c ios

    Please note that you can only build for one platform during one run, in order to build for another platform, try running the command again with a platform specific switch.

    The build command can take a few minutes to create a successful build, however, the good thing is that you can see continuous progress in your command line console.

    Once done, you can find the build package for your phone in the evothings/client/platform directory or can use the ‘i’ switch again (if you haven’t already) to install the client directly to your test phone or simulator/emulator.

    Testing the SMS Plugin

    As our custom Evothings Client is ready now, it’s time to test the SMS plugin we just installed.

    Follow these steps:

    • Download and install Evothings Workbench on your computer.
    • Use the newly installed custom Evothings Client to connect to the Workbench.
    • Download the example Vanilla SMS app from its Github repository and save it to your preferred location.
    • Drag the example’s index.html file into the Evothings Workbench projects list and press the Run button. The Vanilla SMS example app will start within Evothings Client.
    • Enter a mobile number, text message and press the Send SMS button; the app will open the native SMS app with the number and message already passed into it.
    • Now open the index.html in your favorite code editor and analyze the sendSms function, this function is responsible for sending the SMS.

    Note that SMS messages can be sent directly on Android by passing an empty intent in the configuration options, but for iOS and WP8, SMS has to go through the native operating system apps.

    Similarly, if you need any other plugin, you can add that to Evothings Client as well. This will allow you to complete your IoT app utilizing all kinds of functionality offered by extra plugins while still making full use of live reload feature of Evothings Studio.

    JavaScript tutorial for IoT apps – How to structure your code

    $
    0
    0

    When you are new to creating mobile apps in HTML and JavaScript you may run into questions about how to structure your code and how to load libraries. In this tutorial we take a look at how to structure the code on a fundamental level. Read on to learn more!

    How to structure mobile application code

    When you are new to JavaScript you might wonder how to structure your code.

    The convention is to use index.html as the starting point of the app. From there you load cordova.js and other JavaScript files.

    While you can include JavaScript code directly into index.html, it is often handy to place the code in one or more separate JavaScript files. This makes it easier to structure the code and get an overview of the application, especially if the app is large.

    Hands on example – the “TI SensorTag Accelerometer” demo app

    Let’s look at an example. The demo app TI SensorTag Accelerometer that comes with Evothings Studio has a fairly large chunk of JavaScript code in index.html. Let’s move this code to a separate file to make the index.html file shorter and cleaner.

    As a reference, here is the original index.html file. Now we wish to move the JavaScript code between the script tags in index.html to a separate file called app.js.

    The content of app.js would then look like this:

    // Globals.
    var sprite
    var sensortag
    
    function initialise()
    {
        initialiseSprite()
        initialiseSensorTag()
    }
    
    function initialiseSprite()
    {
        sprite = SpriteManager.makeSprite()
        sprite.setDOMElement(document.getElementById('sprite'))
    }
    
    function displaySprite()
    {
        sprite.whenLoaded(function()
        {
            sprite.show()
            sprite.setCenterX(SpriteManager.getPlayfieldWidth() / 2)
            sprite.setCenterY(SpriteManager.getPlayfieldHeight() / 2)
        })
    }
    
    function moveSprite(dx, dy)
    {
        var x = sprite.getCenterX() + dx
        var y = sprite.getCenterY() - dy
    
        x = Math.min(x, SpriteManager.getPlayfieldWidth())
        x = Math.max(x, 0)
    
        y = Math.min(y, SpriteManager.getPlayfieldHeight())
        y = Math.max(y, 0)
    
        sprite.setCenterX(x)
        sprite.setCenterY(y)
    }
    
    function initialiseSensorTag()
    {
        // Create SensorTag CC2650 instance.
        sensortag = evothings.tisensortag.createInstance(
            evothings.tisensortag.CC2650_BLUETOOTH_SMART)
    
        // Uncomment to use SensorTag CC2541.
        //sensortag = evothings.tisensortag.createInstance(
        //    evothings.tisensortag.CC2541_BLUETOOTH_SMART)
    
        // Set up callbacks and sensors.
        sensortag
            .statusCallback(statusHandler)
            .errorCallback(errorHandler)
            .accelerometerCallback(accelerometerHandler, 100)
    }
    
    function connect()
    {
        sensortag.connectToNearestDevice()
    }
    
    function disconnect()
    {
        sensortag.disconnectDevice()
        displayStatus('Disconnected')
        sprite.hide()
    }
    
    function statusHandler(status)
    {
        displayStatus(status)
    
        if (evothings.tisensortag.ble.status.SENSORTAG_ONLINE == status)
        {
            displaySprite()
        }
    }
    
    function errorHandler(error)
    {
        if (evothings.easyble.error.DISCONNECTED == error)
        {
            displayStatus('Disconnected')
            sprite.hide()
        }
        else
        {
            displayStatus('Error: ' + error)
        }
    }
    
    function accelerometerHandler(data)
    {
        var values = sensortag.getAccelerometerValues(data)
        var dx = values.x * 50
        var dy = values.y * 50 * -1
        moveSprite(dx, dy)
    }
    
    function displayStatus(status)
    {
        document.getElementById('status').innerHTML = status
    }
    
    document.addEventListener(
        'deviceready',
        function() { evothings.scriptsLoaded(initialise) },
        false)
    

    Note that script tags are not used in .js files, only in .html files.

    In index.html, remove the script tags for the code we moved to app.js, and instead add this script tag:

    <script src="app.js"></script>

    The script tags in index.html now look like this:

    <script src="cordova.js"></script>
    <script src="libs/evothings/evothings.js"></script>
    <script src="libs/evothings/tisensortag/tisensortag.js"></script>
    <script src="SpriteManager.js"></script>
    <script src="app.js"></script>

    Where should I place the script tags?

    It is considered best practice to place the script tags in the head-section of index.html, or close to the end of the file, last before the closing </body> tag.

    When loading HTML files from a web server, putting the script tags last in the file can speed up the display of the web page. In a mobile app the files are usually included with the app itself, so nothing needs to be downloaded when the app is launched. Still it can be considered good practise to include JS files last in index.html.

    Global names and namespaces

    When you include a .js file using a script tag, any functions or global variables that happens to have the same names as any object in the previously included file(s) are overwritten. If you are not careful this can cause lots of problems.

    You can think of the script tags as putting the separate JavaScript files in one big file and loading that (this is not what happens, it is just a picture to help understanding the end result). If you would use one function name in a file, and then further down the file define a new function with the same name, the previous function would get overwritten.

    Here is an example:

    function sayHello()
    {
        console.log('Hello World 1')
    }
    
    function sayHello()
    {
        console.log('Hello World 2')
    }
    
    sayHello()
    

    This would print “Hello World 2″ since the second definition of sayHello would overwrite the first one.

    Using namespaces is one way to solve this problem. In JavaScript objects are commonly used to create namespace. An object in JavaScript is a dictionary. For example, the “evothings” object is used as a namespace that holds the Evothings library objects and functions.

    Here is an example from the above program code:

    sensortag = evothings.tisensortag.createInstance(
        evothings.tisensortag.CC2650_BLUETOOTH_SMART)

    Here we can see that the object/namespace “evothings” has a child object/namespace that is called “tisensortag”. “createInstance” is a function in this namespace and “CC2650_BLUETOOTH_SMART” is a constant value in the namespace.

    By using a namespace, the number of functions and variables that you may accidentally overwrite are greatly reduced. Instead of hundreds, it is now only one, the “evothings” object.

    JavaScript platforms like Node.js have an even better way to define namespaces, but Node.js is (not yet) used for mobile app development. There are namespace libraries that can be used for mobile development, but they can be a bit cumbersome to use. For the Evothings example apps, we have used a simplistic model that relies on a single global object for identifying the namespace.

    Function references and closures

    JavaScript programmers often make use of a programming construct called a function references. This means that you refer to a function without calling the function. You state the name of the function but it is not called. This is very handy for passing a function to some other function, that will call it later. Frequently an “anonymous function”, also called a “closure”, is used to pass a function to another function.

    Let’s have a look again at the “TI SensorTag Accelerometer” example app. Last in the code we moved to the file app.js, you will find these important lines of code:

    document.addEventListener(
        'deviceready',
        function() { evothings.scriptsLoaded(initialise) },
        false)
    

    Normally, when you include a JavaScript file using a script tag, all the code in that file is loaded at once (this is called “synchronous loading”). However, the Evothings TI SensorTag library uses a feature called “asynchronous loading”, which loads code in parallel with the code in the remaning script tags in index.html.

    This above code snippet delays the call to the function initialise until all parts of the Evothings TI SensorTag library have been loaded and are ready to use.

    If we would call initialise directly, like this, the program may not work (do NOT do this), because initialise might then run before the SensorTag library was fully loaded:

    initialise() // Do not do this

    In addition, note the difference between putting parens after the function name and leaving them out. Adding the parens calls the function immediately. Stating the function name without parens passes a reference to the function so that it can be called later. This is what happens in the document.addEventListener code snippet.

    That is, do NOT do this mistake (note the parens after initialise, this will call initialise right away, not what we want):

    function() { evothings.scriptsLoaded(initialise()) }

    This is how it should be (initialise is not called now, called later by the Evothings library loader):

    function() { evothings.scriptsLoaded(initialise) }

    Lets look at the code again, this time with some comments to clarify:

    // We call the function "addEventListener" which is part of
    // the object "document".
    document.addEventListener(
        // The event we want to listen for is "deviceready", which is
        // specified as a string. In JavaScript you can use singe or
        // double quote marks for specifying strings.
        'deviceready',
        // Here we pass in an anonymous function as a parameter
        // (a function without a name). This function will be called
        // later when the "deviceready" event happens. Some code in
        // the JavaScript framework will call this, we don't have to
        // bother about where this happens, JavasScript takes care of it.
        function() { evothings.scriptsLoaded(initialise) },
        // false indicates that the event should not "bubble", but it is
        // not that important for this example.
        false)
    

    Finally we will have look at the function with no name (breaking it up on multiple lines for readability):

    // The function have no name, and this is called an "anonymous function" or "closure".
    function()
    {
        // When the anonymous function is called, the function
        // "scriptsLoaded" which is defined on the object "evothings"
        // is evaluated. The function "initialize" is passed as a
        // parameter. The "scriptsLoaded" function will call the
        // "initialize" function  when all Evothings library have
        // been loaded.
        evothings.scriptsLoaded(initialise)
    }
    

    Links and further reading

    Here are examples of JavaScript tutorials:

    Getting started guides for Evothings Studio:

    Call to action – Get started with Evothings Studio

    Hope the above helps you understanding how to structure the code of your IoT apps and using Evothings libraries!

    Download Evothings Studio right away and get started with app development for the Internet of Things in minutes. It is fast and fun to get up and running!

    happy_final_small

    5 reasons to keep your eyes open for Eddystone™ beacons

    $
    0
    0

    Eddystone LighthouseHello IoT developers and beacon lovers! Eddystone™ is a new potentially disruptive beacon standard recently announced by Google.

    There is every reason to believe that Eddystone is going to take the beacon community by storm. It is open, it is an alternative to Apple’s iBeacon, it is supported by Google as well as the major beacon vendors. And it is ready to use.

    Here are 5 reasons to keep your eyes open for Eddystone.

    1. It is ready to use

    Eddystone is here now. It is not a future standard that may eventually happen. It has already happened. This means that you can start developing apps for Eddystone today, order beacons and start deploying them.

    At Evothings we are busy including Eddystone into Evothings Studio (stay ready for the upcoming release of Evothings Studio 2.0). This is great news for all JavaScript developers!

    2. It is supported by major beacon vendors

    Major beacon vendors such as Estimote, Kontakt.io, Radius Networks, BluVision and BKON already have Eddystone beacons and SDKs in place.

    This means that both hardware and software development tools are available for Eddystone right from the start.

    3. It is an open standard that innovates use of broadcasted data

    Eddystone is a specification of an open beacon protocol, released under the Apache license.

    Eddystone beacons broadcast messages using Bluetooth Low Energy (BLE). What is special is that broadcasted messages are flexible, there are different types of frames sent out, enabling multiple messages types.

    Three frame types are defined by the standard:

    • URL – The frame contains a URL that can be used by the application to link to content. This enables the “Physical Web”.
    • UID – The frame consists of a unique identifier the application can use to trigger actions and display information. A mobile app can display data stored locally or dynamically fetch data from a server.
    • Telemetry – The frame contains information such as battery level, temperature, and uptime. This data can be used to monitor the “health” of large (and small) beacon installations.

    The use of different frame types is an innovation compared to iBeacon, which uses only one type of frame.

    Additional frames could be used. As an example, iBeacon frames could be broadcasted in addition to the Eddystone specific frames. This would make Eddystone beacons work with both iBeacon apps and Eddystone apps.

    4. It is totally cross platform

    Since the specification is open, libraries and applications can be implemented on all mobile platforms that are capable of using Bluetooth Low Energy (BLE). Implementations for Android and iOS are already available, for example in the SDKs from Estimote and Kontakt.io.

    Furthermore, Google has announced support for Eddystone and the Physical Web in it’s mobile Chrome browser. This means that you can explore Eddystone beacons in an easy way.

    This is great news for all web developers and at Evothings we are working on wide support for also creating native Eddystone apps using JavaScript.

    5. Google enters the beacon industry at full scale

    Interestingly, Google kept Eddystone “under the radar” until the release two weeks ago. It is as if a fully featured beacon ecosystem suddenly materialised right in front of our eyes!

    Not only are beacon vendors announcing support for Eddystone. Google presents a new beacon platform with support for fleet diagnostics, Proximity Beacon API, Nearby API, and Places API.

    There are also example apps from Google, for both iOS and Android.

    The future does look interesting for beacon developers!

    It is easy to get started with Evothings Studio

    Evothings Studio already has support for iBeacon and Estimote beacons and nearables. Eddystone is on the way.

    Get ready to learn beacon app development using JavaScript, download Evothings Studio and get up and running in minutes. It is app development made fast and fun!

    happy_final_small
    Viewing all 97 articles
    Browse latest View live