Module: Toybox::Communications

Overview

The Communications Module provides tools for communication.

With the Communications module, widgets and apps will be able to communicate with a mobile phone via Bluetooth Low Energy (BLE). The mobile phone may be sharing data with the device, or it may act as a bridge between the app and the Internet. This allows the device to become part of the Internet of Things.

This module also provides several sets of constants:

  • UNKNOWN_ERROR: Indicates an unknown error.

  • BLE_: Indicates a BLE specific status.

  • INVALID_HTTP_: Indicates an invalid HTTP request or response.

  • NETWORK_: Indicates a network error.

  • HTTP_RESPONSE_CONTENT_TYPE: The expected response from making a web request.

  • REQUEST_CONTENT_TYPE: Used in conjunction with the “Content-Type” header key.

Since:

  • 1.0.0

Supported Devices:

  • All devices

App Types:

  • Widget

  • App

  • Audio Content Provider App

  • Background Services

Requires Permission:

  • Communications

Defined Under Namespace

Classes: ConnectionListener, MailboxIterator, Message, OAuthMessage, PhoneAppMessage

Constant Summary

UNKNOWN_ERROR = 0

Since:

  • 1.0.0

BLE_ERROR = -1

Since:

  • 1.0.0

BLE_HOST_TIMEOUT = -2

Since:

  • 1.0.0

BLE_SERVER_TIMEOUT = -3

Since:

  • 1.0.0

BLE_NO_DATA = -4

Since:

  • 1.0.0

BLE_REQUEST_CANCELLED = -5

Since:

  • 1.0.0

BLE_QUEUE_FULL = -101

Since:

  • 1.0.0

BLE_REQUEST_TOO_LARGE = -102

Since:

  • 1.0.0

BLE_UNKNOWN_SEND_ERROR = -103

Since:

  • 1.0.0

BLE_CONNECTION_UNAVAILABLE = -104

Since:

  • 1.0.0

INVALID_HTTP_HEADER_FIELDS_IN_REQUEST = -200

Since:

  • 1.0.0

INVALID_HTTP_BODY_IN_REQUEST = -201

Since:

  • 1.0.0

INVALID_HTTP_METHOD_IN_REQUEST = -202

Since:

  • 1.0.0

NETWORK_REQUEST_TIMED_OUT = -300

Since:

  • 1.0.0

INVALID_HTTP_BODY_IN_NETWORK_RESPONSE = -400

Since:

  • 1.0.0

INVALID_HTTP_HEADER_FIELDS_IN_NETWORK_RESPONSE = -401

Since:

  • 1.0.0

NETWORK_RESPONSE_TOO_LARGE = -402

Since:

  • 1.0.0

NETWORK_RESPONSE_OUT_OF_MEMORY = -403

Since:

  • 3.0.0

STORAGE_FULL = -1000

Since:

  • 2.2.0

SECURE_CONNECTION_REQUIRED = -1001

Since:

  • 2.3.0

UNSUPPORTED_CONTENT_TYPE_IN_RESPONSE = -1002

Since:

  • 2.4.1

REQUEST_CANCELLED = -1003

Since:

  • 2.4.2

REQUEST_CONNECTION_DROPPED = -1004

Since:

  • 3.0.0

UNABLE_TO_PROCESS_MEDIA = -1005

Since:

  • 3.0.2

UNABLE_TO_PROCESS_IMAGE = -1006

Since:

  • 3.0.3

UNABLE_TO_PROCESS_HLS = -1007

Since:

  • 3.0.10

OAUTH_RESULT_TYPE_URL = 0

How the Oauth token will be returned in the final step.

Since:

  • 1.3.0

OAUTH_SIGNING_METHOD_HMAC_SHA1 = 0

How the Oauth request will be signed

Since:

  • 1.3.0

HTTP_REQUEST_METHOD_GET = 1

Since:

  • 1.2.0

HTTP_REQUEST_METHOD_PUT = 2

Since:

  • 1.2.0

HTTP_REQUEST_METHOD_POST = 3

Since:

  • 1.2.0

HTTP_REQUEST_METHOD_DELETE = 4

Since:

  • 1.2.0

HTTP_RESPONSE_CONTENT_TYPE_JSON = 0

Since:

  • 1.3.0

HTTP_RESPONSE_CONTENT_TYPE_URL_ENCODED = 1

Since:

  • 1.3.0

HTTP_RESPONSE_CONTENT_TYPE_GPX = 2

Since:

  • 2.2.0

HTTP_RESPONSE_CONTENT_TYPE_FIT = 3

Since:

  • 2.2.0

HTTP_RESPONSE_CONTENT_TYPE_AUDIO = 4

Since:

  • 3.0.0

HTTP_RESPONSE_CONTENT_TYPE_TEXT_PLAIN = 5

Since:

  • 3.0.0

HTTP_RESPONSE_CONTENT_TYPE_HLS_DOWNLOAD = 6

Since:

  • 3.0.10

REQUEST_CONTENT_TYPE_URL_ENCODED = 0

Specifies a content type of application/x-www-form-urlencoded

Since:

  • 1.2.0

REQUEST_CONTENT_TYPE_JSON = 1

Specifies a content type of application/json

Since:

  • 1.2.0

IMAGE_DITHERING_NONE = 1

Since:

  • 1.2.0

IMAGE_DITHERING_FLOYD_STEINBERG = 2

Since:

  • 1.2.0

Instance Method Summary collapse

Instance Method Details

cancelAllRequestsObject

Cancel all pending JSON and Image requests.

The number of active requests running in parallel is limited in the Connect IQ platform. This call will cancel all outstanding requests.

Since:

  • 1.2.0


3342
3343
# File 'Monkeybrains.rb', line 3342

def cancelAllRequests()
end

emptyMailboxObject

Deprecated.

The emptyMailbox API will be dropped in Connect IQ 4.0.0. Use registerForPhoneAppMessages()

Clear the contents of the mailbox.

Since:

  • 1.0.0


3383
3384
# File 'Monkeybrains.rb', line 3383

def emptyMailbox()
end

encodeURL(url) ⇒ Toybox::Lang::String

Convert a URL String into a percent-encoded string.

The reserved characters in the string will be replaced with their corresponding hex-value pairs. This follows the URI-encoding scheme as detailed by RFC 3986.

Parameters:

Returns:

See Also:

Since:

  • 1.1.2


3015
3016
# File 'Monkeybrains.rb', line 3015

def encodeURL(url)
end

generateSignedOAuthHeader(url, params, requestMethod, signatureMethod, token, tokenSecret, consumerKey, consumerSecret) ⇒ Toybox::Lang::String

Generate the value for the “Authorization” header in an OAuth 1.0a request.

The returned value can be set as the “Authorization” header for makeWebRequest().

Parameters:

Returns:

Since:

  • 1.3.0


3266
3267
# File 'Monkeybrains.rb', line 3266

def generateSignedOAuthHeader(url, params, requestMethod, signatureMethod, token, tokenSecret, consumerKey, consumerSecret)
end

getMailboxToybox::Communications::MailboxIterator

Deprecated.

The getMailbox API will be dropped in Connect IQ 4.0.0. Use registerForPhoneAppMessages()

Get the MailboxIterator for this Application's mailbox.

Returns:

Since:

  • 1.0.0


3364
3365
# File 'Monkeybrains.rb', line 3364

def getMailbox()
end

makeImageRequest(url, parameters, options, responseCallback) ⇒ Object

Request an image through Garmin Connect Mobile.

GCM will scale and dither the image based on the capabilities of the device, but the user will be able to pass additional options (like dithering it down to a one color image)

Examples:

using Toybox.System;
using Toybox.Communications;

var image;
var responseCode;

    // Set up the responseCallback function to return an image or null
    function responseCallback(responseCode, data) {
        responseCode = responseCode;
        if (responseCode == 200) {
            image = data;
        } else {
            image = null;
        }
    }

    // wrap the request in a function
    function makeRequest() {
        var url = "http://www.garmin.com/image-path";           // set the image url
        var parameters = null;                                  // set the parameters
        var options = {                                         // set the options
            :palette => [ Gfx.COLOR_ORANGE,                     // set the palette
                          Gfx.COLOR_DK_BLUE,
                          Gfx.COLOR_BLUE,
                          Gfx.COLOR_BLACK ],
            :maxWidth => 100,                                   // set the max width
            :maxHeight => 100,                                  // set the max height
            :dithering => Communications.IMAGE_DITHERING_NONE   // set the dithering
        };

        // Make the image request
        Communications.makeImageRequest(url, parameters, options, method(:responseCallback));
    }

Parameters:

Options Hash (options):

Since:

  • 1.2.0


3241
3242
# File 'Monkeybrains.rb', line 3241

def makeImageRequest(url, parameters, options, responseCallback)
end

makeJsonRequest(url, parameters, options, responseCallback) ⇒ Object

Deprecated.

makeJsonRequest() class will be dropped in Connect IQ 4.0.0. Please use makeWebRequest().

To use Garmin Connect Mobile as a proxy to the web, use makeJsonRequest().

The request is asynchronous; the responseCallback will be called when the request returns.

Parameters:

  • url (Toybox::Lang::String)

    The URL being requested

  • parameters (Toybox::Lang::Dictionary)

    A Dictionary of keys and values

    • Appended to the URL for GET/DELETE request

    • Set as the body for a POST/PUT request

    • These values must be URL encoded

    • Can be null

  • options (Toybox::Lang::Dictionary)

    A Dictionary of options

    • Can be null

  • responseCallback (Toybox::Lang::Method)

    A reference to a callback method which must accept two arguments:

    • responseCode: the server response code

    • data: the Dictionary of content from a successful request of content if the request was successful.

Options Hash (options):

  • :method (Toybox::Lang::Number)

    The HTTP method of the request. This option should be an HTTP_REQUEST_METHOD_* value.

  • :headers (Toybox::Lang::Dictionary)

    A Dictionary of HTTP headers to include in the request

    • The “Content-Type” header for the body of the request can be specified using a REQUEST_CONTENT_TYPE_* value

      • This is only valid for methods PUT and POST (you cannot set a body for a GET or DELETE request)

      • If the content type is not specified, it will default to “application/json” for GET and DELETE requests, and will default to “application/x-www-form-urlencoded” for POST and PUT requests

Since:

  • 1.0.0


3088
3089
# File 'Monkeybrains.rb', line 3088

def makeJsonRequest(url, parameters, options, responseCallback)
end

makeOAuthRequest(requestUrl, requestParams, resultUrl, resultType, resultKeys) ⇒ Object

Request an OAuth sign-in through Garmin Connect Mobile.

A notification will trigger on the phone, that when clicked, provides a web view that shows requestUrl. If the user grants permission to the app, then the callback registered by registerForOAuthMessages() will be called with an OAuthMessage from the OAuth response.

Examples:

using Toybox.Communications;
using Toybox.System;

const CLIENT_ID = "myClientID";
const OAUTH_CODE = "myOAuthCode";
const OAUTH_ERROR = "myOAuthError";

// register a callback to capture results from OAuth requests
Communications.registerForOAuthMessages(method(:onOAuthMessage));

// wrap the OAuth request in a function
function getOAuthToken() {
   status = "Look at OAuth screen\n";
   Ui.requestUpdate();

   // set the makeOAuthRequest parameters
   var params = {
       "scope" => Comm.encodeURL(https://www.serviceurl.com/),
       "redirect_uri" => "http://localhost",
       "response_type" => "code",
       "client_id" => "$.CLIENT_ID"
   };

   // makeOAuthRequest triggers login prompt on mobile device
   Comm.makeOAuthRequest(
       "https://requesturl.com",
       params,
       "http://resulturl.com",
       Comm.OAUTH_RESULT_TYPE_URL,
       {"responseCode" => "OAUTH_CODE", "responseError" => "OAUTH_ERROR"}
   );
}

// implement the OAuth callback method
function onOAuthMessage(message) {
    if (message.data != null) {
        var code = message.data[OAUTH_CODE];
        var error = message.data[OAUTH_ERROR];
    } else {
        // return an error
    }
}
// the OAuth service can now be used with a makeWebRequest() call

Parameters:

  • requestUrl (Toybox::Lang::String)

    The URL to load in the web view to begin authentication

  • requestParams (Toybox::Lang::Dictionary)

    Non-URL encoded parameters for the requestUrl

  • resultUrl (Toybox::Lang::String)

    The URL of the final page of authentication that contains the resultKeys

  • resultType (Toybox::Lang::Number)

    An OAUTH_RESULT_TYPE_* value that specifies the format of the result

  • resultKeys (Toybox::Lang::Dictionary)

    The desired OAuth response values passed to the callback method. The keys map to the actual OAuth response keys, and the values map to the keys of the OAuthMessage data.

Since:

  • 1.3.0


3334
3335
# File 'Monkeybrains.rb', line 3334

def makeOAuthRequest(requestUrl, requestParams, resultUrl, resultType, resultKeys)
end

makeWebRequest(url, parameters, options, responseCallback) ⇒ Object

Use Garmin Connect Mobile as a proxy to the web.

Web requests are asynchronous. The supplied response callback method will be called when the request returns. TVM will select the audio stream with the highest bandwidth that's less than or equal to the maximum This option is only effective when processing HLS content

Examples:

// It is common for developers to wrap a makeWebRequest() call in a function
// as displayed below. The function defines the variables for each of the
// necessary arguments in a Communications.makeWebRequest() call, then passes
// these variables as the arguments. This allows for a clean layout of your web
// request and expandability.
using Toybox.System;
using Toybox.Communications;

   // set up the response callback function
   function onReceive(responseCode, data) {
       if (responseCode == 200) {
           System.println("Request Successful");                   // print success
       }
       else {
           System.println("Response: " + responseCode);            // print response code
       };

   };

   function makeRequest() {
       var url = "https://www.garmin.com";                         // set the url

       var params = {                                              // set the parameters
              "definedParams" => "123456789abcdefg"
       };

       var options = {                                             // set the options
           :method => Communications.HTTP_REQUEST_METHOD_GET,      // set HTTP method
           :headers => {                                           // set headers
                   "Content-Type" => Communications.REQUEST_CONTENT_TYPE_URL_ENCODED},
                                                                   // set response type
           :responseType => Communications.HTTP_RESPONSE_CONTENT_TYPE_URL_ENCODED
       };

       var responseCallback = method(:onReceive);                  // set responseCallback to
                                                                   // onReceive() method
       // Make the Communications.makeWebRequest() call
       Communications.makeWebRequest(url, params, options, method(:onReceive));
  }

Parameters:

Options Hash (options):

  • :method (Toybox::Lang::Number)

    The HTTP method of the request. This should be an HTTP_REQUEST_METHOD_* value.

  • :headers (Toybox::Lang::Dictionary)

    A Dictionary of HTTP headers to include in the request.

    • The “Content-Type” header for the body of the request can be specified using a REQUEST_CONTENT_TYPE_* value.

    • If the content type is not specified, it will default to “application/json” for GET and DELETE requests, and will default to “application/x-www-form-urlencoded” for POST and PUT requests.

    • By default, DELETE requests will have their parameters appended to the URL.

    • Setting the method as DELETE as well as a “Content-Type” header will result in the parameters being set in the body of the request and they will not be appended to the URL.

    • GET requests can only have their parameters appended to the URL, specifying the “Content-Type” header will not set the body.

  • :responseType (Toybox::Lang::Number)

    The format of the response.

    • This should be an HTTP_RESPONSE_CONTENT_TYPE_* value.

    • If HTTP_RESPONSE_CONTENT_TYPE_FIT or HTTP_RESPONSE_CONTENT_TYPE_GPX is given, the system will attempt to download and parse a FIT or GPX file and store the contained data in the device, based on the contents of the file.

    • If not given, the system will use the Content-Type header from the server response to determine the format of the response body. If the Content-Type header from the response is not one of the known HTTP_RESPONSE_CONTENT_TYPE_* types, an error will occur.

  • :context (Toybox::Lang::Object)

    A user-specific context object to be passed to the response callback. The callback will need to accept a third parameter if this value is populated.

  • :mediaEncoding (Toybox::Lang::Number)

    The encoding of the audio content that is being downloaded. Should be a Media.ENCODING_* value.

  • :responseCallback (Toybox::Lang::Method)

    A reference to a callback method which must accept two arguments:

    • responseCode: The server response code or a BLE_* error type

    • data: Dictionary of content from a successful request

  • :maxBandwidth (Toybox::Lang::Number)

    maximum bandwidth.

Since:

  • 1.3.0


3169
3170
# File 'Monkeybrains.rb', line 3169

def makeWebRequest(url, parameters, options, responseCallback)
end

openWebPage(url, params, options) ⇒ Object

Request that GCM issue a phone notification that will open a web page.

This method will push a phone notification that must be accepted by the user. If the used accepts it, a web page defined by this method will be opened in the default browser on the phone.

Examples:

using Toybox.Communications;
Communications.openWebPage(
   "http://www.bing.com/images/search",
   {"q" => "cute kitten"},
   null
);
// passes the url: http://bing.com/images/search?q=cute kitten to the
// browser on the phone

Parameters:

Since:

  • 1.3.0


3498
3499
# File 'Monkeybrains.rb', line 3498

def openWebPage(url, params, options)
end

registerForOAuthMessages(method) ⇒ Object

Register a callback for receiving OAuth messages.

The callback will be called once for each received OAuth message. If there are messages waiting for the app when this function is called, the callback will immediately be called once for each waiting message.

Examples:

using Toybox.Communications;

function onOAuthMessage(message) {
    if (message.data != null) {
        var code = message.data[OAUTH_CODE];
        var error = message.data[OAUTH_ERROR];
    } else {
        // return an error
    }
}
Communications.registerForOAuthMessages(method(:onOAuthMessage));

Parameters:

Since:

  • 1.3.0


3474
3475
# File 'Monkeybrains.rb', line 3474

def registerForOAuthMessages(method)
end

registerForPhoneAppMessages(method) ⇒ Object

Register a callback for receiving Phone App messages.

The callback will be called once for each message received. If there are messages waiting for the app when this function is called, the callback will immediately be called once for each waiting message.

Examples:

using Communications;
// set up somewhere to store the message
var message = new Communications.PhoneAppMessage;
// set up phoneMessageCallback
function phoneMessageCallback(msg) {
   message = msg.data;
}
// register the messages from the callback to capture the results
Communications.registerForPhoneAppMessages(method(:phoneMessageCallback));

Parameters:

See Also:

Since:

  • 1.4.0


3521
3522
# File 'Monkeybrains.rb', line 3521

def registerForPhoneAppMessages(method)
end

setMailboxListener(listener) ⇒ Object

Deprecated.

The setMailboxListner API will be dropped in Connect IQ 4.0.0. Use registerForPhoneAppMessages()

Add a listener for mailbox events.

The listener method is called whenever a new message is received.

Parameters:

  • listener (Toybox::Lang::Method)

    A reference to a callback method which must accept an iterator. The iterator is the mailbox iterator for the app

Since:

  • 1.0.0


3376
3377
# File 'Monkeybrains.rb', line 3376

def setMailboxListener(listener)
end

transmit(content, options, listener) ⇒ Object

Send data across the the BLE link.

Parameters:

Since:

  • 1.0.0


3393
3394
# File 'Monkeybrains.rb', line 3393

def transmit(content, options, listener)
end