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.

Since:

1.0.0

App Types:

  • Watch App

  • Audio Content Provider

  • Background

  • Widget

Supported Devices:

Requires Permission:

  • Communications

Classes Under Namespace

Classes: ConnectionListener, MailboxIterator, Message, OAuthMessage, PhoneAppMessage, SyncDelegate

Constant Summary

Enumerators

Name Value Since Description
UNKNOWN_ERROR 0

1.0.0

An unknown error has occurred.

BLE_ERROR -1

1.0.0

A generic BLE error has occurred.

BLE_HOST_TIMEOUT -2

1.0.0

We timed out waiting for a response from the host.

BLE_SERVER_TIMEOUT -3

1.0.0

We timed out waiting for a response from a server.

BLE_NO_DATA -4

1.0.0

Response contained no data.

BLE_REQUEST_CANCELLED -5

1.0.0

The request was cancelled at the request of the system.

BLE_QUEUE_FULL -101

1.0.0

Too many requests have been made.

BLE_REQUEST_TOO_LARGE -102

1.0.0

Serialized input data for the request was too large.

BLE_UNKNOWN_SEND_ERROR -103

1.0.0

Send failed for an unknown reason.

BLE_CONNECTION_UNAVAILABLE -104

1.0.0

No BLE connection is available.

INVALID_HTTP_HEADER_FIELDS_IN_REQUEST -200

1.0.0

Request contained invalid http header fields.

INVALID_HTTP_BODY_IN_REQUEST -201

1.0.0

Request contained an invalid http body.

INVALID_HTTP_METHOD_IN_REQUEST -202

1.0.0

Request used an invalid http method.

NETWORK_REQUEST_TIMED_OUT -300

1.0.0

Request timed out before a response was received.

INVALID_HTTP_BODY_IN_NETWORK_RESPONSE -400

1.0.0

Response body data is invalid for the request type.

INVALID_HTTP_HEADER_FIELDS_IN_NETWORK_RESPONSE -401

1.0.0

Response contained invalid http header fields.

NETWORK_RESPONSE_TOO_LARGE -402

1.0.0

Serialized response was too large.

NETWORK_RESPONSE_OUT_OF_MEMORY -403

3.0.0

Ran out of memory processing network response.

STORAGE_FULL -1000

2.2.0

Filesystem too full to store response data.

SECURE_CONNECTION_REQUIRED -1001

2.3.0

Indicates an https connection is required for the request.

UNSUPPORTED_CONTENT_TYPE_IN_RESPONSE -1002

2.4.1

Content type given in response is not supported or does not match what is expected.

REQUEST_CANCELLED -1003

2.4.2

Http request was cancelled by the system.

REQUEST_CONNECTION_DROPPED -1004

3.0.0

Connection was lost before a response could be obtained.

UNABLE_TO_PROCESS_MEDIA -1005

3.0.2

Downloaded media file was unable to be read.

UNABLE_TO_PROCESS_IMAGE -1006

3.0.3

Downloaded image file was unable to be processed.

UNABLE_TO_PROCESS_HLS -1007

3.0.10

HLS content could not be downloaded. Most often occurs when requested and provided bit rates do not match.

Enumerators

Name Value Since Description
OAUTH_RESULT_TYPE_URL 0

1.3.0

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

Enumerators

Name Value Since Description
OAUTH_SIGNING_METHOD_HMAC_SHA1 0

1.3.0

How the OAuth request will be signed

Enumerators

Name Value Since Description
HTTP_REQUEST_METHOD_GET 1

1.2.0

Specifies a request be executed using the GET method.

HTTP_REQUEST_METHOD_PUT 2

1.2.0

Specifies a request be executed using the PUT method.

HTTP_REQUEST_METHOD_POST 3

1.2.0

Specifies a request be executed using the POST method.

HTTP_REQUEST_METHOD_DELETE 4

1.2.0

Specifies a request be executed using the DELETE method.

Enumerators

Name Value Since Description
HTTP_RESPONSE_CONTENT_TYPE_JSON 0

1.3.0

Content type specifier for response is expected to be a json type. Content type string must be "application/json".

HTTP_RESPONSE_CONTENT_TYPE_URL_ENCODED 1

1.3.0

Content type specifier for response is expected to indicate url encoding. Content type string must be "application/x-www-form-urlencoded".

HTTP_RESPONSE_CONTENT_TYPE_GPX 2

2.2.0

Content type specifier for response is expected to be a gpx type.

HTTP_RESPONSE_CONTENT_TYPE_FIT 3

2.2.0

Content type specifier for response is expected to be a FIT type.

HTTP_RESPONSE_CONTENT_TYPE_AUDIO 4

3.0.0

Content type specifier for response is expected to be an audio type. Content type string must be of the "audio/*" format.

HTTP_RESPONSE_CONTENT_TYPE_TEXT_PLAIN 5

3.0.0

Content type specifier for response is expected to be plain text type. Content type string must be "text/plain"

HTTP_RESPONSE_CONTENT_TYPE_HLS_DOWNLOAD 6

3.0.10

Content type specifier for response is expected to be an HLS data type. Content type string must be either "application/vnd.apple.mpegurl" or "audio/mpegurl".

HTTP_RESPONSE_CONTENT_TYPE_ANIMATION_MANIFEST 7

3.1.0

Content type specifier for response is expected to be a CIQ animation manifest data type. Content type string must be "application/vnd.garmin.connectiq.animation.manifest".

HTTP_RESPONSE_CONTENT_TYPE_ANIMATION 8

3.1.0

Content type specifier for response is expected to be a CIQ animation data type. Content type string must be "image/vnd.garmin.connectiq.animation".

Enumerators

Name Value Since Description
REQUEST_CONTENT_TYPE_URL_ENCODED 0

1.2.0

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

REQUEST_CONTENT_TYPE_JSON 1

1.2.0

Specifies a content type of application/json

Enumerators

Name Value Since Description
IMAGE_DITHERING_NONE 1

1.2.0

Do not apply dithering to an image.

IMAGE_DITHERING_FLOYD_STEINBERG 2

1.2.0

Apply Floyd-Steinberg dithering to an image.

Instance Method Summary collapse

Instance Method Details

cancelAllRequests()

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

emptyMailbox()

This has been deprecated

This method will be removed in Connect IQ 4.0.0

Clear the contents of the mailbox.

Supported Devices:

See Also:

Since:

1.0.0

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

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

getMailbox()Toybox.Communications.MailboxIterator

This has been deprecated

This method will be removed in Connect IQ 4.0.0

Get the MailboxIterator for this Application's mailbox.

Supported Devices:

Returns:

See Also:

Since:

1.0.0

makeImageRequest(url, parameters, options, responseCallback)

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)

Parameters:

  • url(Toybox.Lang.String)

    The URL of an image to request

  • parameters(Toybox.Lang.Dictionary)

    The Dictionary of keys and values

    • Appended to the URL

    • Can be null

  • options(Toybox.Lang.Dictionary)

    Additional image options

    • :palette(Toybox.Lang.Array)

      The color palette to restrict the image dithering to. Using a smaller palette can reduce the size of the image data to speed up transfers

    • :maxWidth(Toybox.Lang.Number)

      The maximum width an image should be scaled to

    • :maxHeight(Toybox.Lang.Number)

      The maximum height an image should be scaled to

    • :dithering(Toybox.Lang.Number)

      The type of dithering to use when processing the image. Defaults to IMAGE_DITHERING_FLOYD_STEINBERG

  • 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: A BitmapResource from a successful request

Example:

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));
    }

Since:

1.2.0

makeJsonRequest(url, parameters, options, responseCallback)

This has been deprecated

This method will be removed in Connect IQ 4.0.0

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

    • :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

  • 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.

Supported Devices:

See Also:

Since:

1.0.0

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

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.

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.

Example:

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.
   // "responseCode" and "responseError" are the parameters passed
   // to the resultUrl. Check the oauth provider's documentation
   // to determine the correct strings to use.
   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

Since:

1.3.0

makeWebRequest(url, parameters, options, responseCallback)

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.

Parameters:

  • url(Toybox.Lang.String)

    The URL being requested

  • parameters(Toybox.Lang.Dictionary)

    A Dictionary of keys and values.

    • These values should not be URL encoded.

    • Can be null.

  • options(Toybox.Lang.Dictionary)

    A Dictionary of 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.

    • :maxBandwidth(Toybox.Lang.Number)

      maximum bandwidth. 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

    • :fileDownloadProgressCallback(Toybox.Lang.Method)

      a callback method which must accept two parameters

      • totalBytesTransferred: The total number of bytes transferred for the current file download

      • fileSize: The size of the file being downloaded. Note that this can be null if file size cannot be determined from the server.

      • This option is only supported for media file download progress

      • This option is supported since CIQ 3.2.0

  • 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

Example:

// 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));
  }

Since:

1.3.0

Throws:

  • (Toybox.Lang.InvalidOptionsException)

    Raised if a required option for a particular request is omitted

  • (Toybox.Lang.SymbolNotAllowedException)

    Raised if a given :responseType option is not supported for the device the reqest is being made from. An example would be using HTTP_RESPONSE_CONTENT_TYPE_AUDIO on a device that does not support audio content provider apps

notifySyncComplete(errorMessage)

Send a system notification to indicate that the sync completed.

Parameters:

  • errorMessage(Toybox.Lang.String)

    A descriptive error message if a failure occurred. If the sync completes successfully, null should be passed to this method.

Supported Devices:

Since:

3.1.0

notifySyncProgress(percentageComplete)

Send a system notification to indicate overall sync progress.

Parameters:

  • percentageComplete(Toybox.Lang.Number)

    An integer from 0 to 100 indicating the completion percentage.

Supported Devices:

Since:

3.1.0

openWebPage(url, params, options)

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.

Parameters:

Example:

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

Since:

1.3.0

registerForOAuthMessages(method)

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.

Parameters:

Example:

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));

Since:

1.3.0

registerForPhoneAppMessages(method)

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.

Parameters:

Example:

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));

Supported Devices:

See Also:

Since:

1.4.0

setMailboxListener(listener)

This has been deprecated

This method will be removed in Connect IQ 4.0.0

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

Supported Devices:

See Also:

Since:

1.0.0

startSync()

Exit the AppBase and launch it in sync mode.

Supported Devices:

Since:

3.1.0

transmit(content, options, listener)

Send data across the the BLE link.

Parameters:

Supported Devices:

Since:

1.0.0


Generated Oct 21, 2020 12:46:17 PM