Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 13 Next »

Create a New Node.js Project

  1. Create and enter a new directory: $ mkdir gumband-example && cd gumband-example

  2. Initialize an npm project: $ npm init

(it’s fine to press ‘enter’ to accept the default values when prompted)

package name: (gumband-example) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC)

Install the Gumband SDK

Add the Gumband npm module: $ npm i -S @deeplocal/gumband-node-sdk

Create an Empty Manifest File

All manifests contain one top level key “manifest” and three child keys “statuses”, “controls”, and “settings”. All of these keys must exist and point to an array (even if empty). Save the file as manifest.json.

{
  "manifest": {
    "statuses": [],
    "controls": [],
    "settings": []
  }
}

Initialize the Gumband SDK

  1. Create a New Exhibit in the Gumband UI

  2. Create a new js file called ‘sample.js’ and initialize a new instance of the Gumband SDK, providing the exhibit id, exhibit token. The exhibit id and token should have been generated in the previous step. The endpoint id identifies the environment in which the exhibit was created:

See this example, which configures the SDK to authenticate itself with an exhibit with an id of 40 from the app environment:

const { Gumband, Sockets } = require('@deeplocal/gumband-node-sdk');

const EXHIBIT_ID = '40';
const EXHIBIT_TOKEN = 'a45ne3...';

const gb = new Gumband(
    EXHIBIT_TOKEN,
    EXHIBIT_ID,
    './manifest.json',
);

gb.on(Sockets.READY, async () => {
    console.log('Gumband Ready!');
});

3. Run the node service: node sample.js. You should see a “Gumband Ready!” message in the terminal, and you should also be able to see the Gumband Exhibit go online/offline in the web UI (note the red/green connection icon directly to the left of the Exhibit name)

The node service now has an open websocket connection with the Gumband cloud instance, and the Gumband SDK instance will emit events that are received through this websocket connection as the cloud instance sends them. Some important events that can be emitted via this websocket connection are:

Event Name

Description

Sockets.READY

Designates that the Gumband SDK is authenticated with the Gumband cloud instance and is listening for events sent through the websocket connection.

Sockets.OP_MODE_RECEIVED

Emitted when the operation mode is changed in the Gumband UI

Sockets.CONTROL_RECEIVED

Emitted when a control is triggered via the Gumband UI

Sockets.SETTING_RECEIVED

Emitted when a setting has changed

Sockets.FILE_UPLOADED

Emitted when a new file has been uploaded to the Gumband UI.

Listeners for these events can be added in the same way that the Sockets.READY event is subscribed to above:

const { Gumband, Sockets } = require('@deeplocal/gumband-node-sdk');

const EXHIBIT_TOKEN = '40';
const EXHIBIT_ID = 'a45ne3...';

const gb = new Gumband(
    EXHIBIT_TOKEN,
    EXHIBIT_ID,
    './manifest.json',
);

gb.on(Sockets.READY, async () => {
    console.log('Gumband Ready!');
});

gb.on(Sockets.OP_MODE_RECEIVED, (payload) => {
    console.log(`received op mode: ${JSON.stringify(payload)}`);
});

gb.on(Sockets.CONTROL_RECEIVED, (payload) => {
    console.log(`received control: ${JSON.stringify(payload)}`);
});

gb.on(Sockets.SETTING_RECEIVED, (payload) => {
    console.log(`received setting: ${JSON.stringify(payload)}`);
});

gb.on(Sockets.FILE_UPLOADED, async (payload) => {
    console.log(payload.fileName);
    await gb.content.sync();
    console.log('done updating files')
});

Handling these websocket events is described in more detail below.

Handling Operating Modes

There are two operating modes your Exhibit can be in: on or off. These are updated in the gumband UI with the large toggle next to the Exhibit name.

Add some more logic to the operation mode callback:

gb.on(Sockets.OP_MODE_RECEIVED, (payload) => {
    console.log(`received op mode: ${JSON.stringify(payload)}`);
    if(payload.value) {
      console.log('OP mode now on');
    } else {
      console.log('OP mode now off');
    }
});

After restarting the node service, if you toggle the op mode on and off in the Gumband UI, you will see the following in the console:

Create, Update, and Read a Status

Now we will create a status. Open your manifest file and add the following example status to the “statuses” array:

{
  "manifest": {
    "statuses": [
      {
        "id": "example_status",
        "type": "String",
        "display": "Example Status",
        "default": "a default value",
        "order": 0
      }
    ],
    "controls": [],
    "settings": []
  }
}
  1. Id is a unique string to name this status (cannot have two with the same value)

  2. Type is the type of value you want this status to hold, in our case a string. This is important since data validation is performed when trying to set statuses

  3. Display is the string that the user will see in the Gumband UI

  4. Default is the default value for your status

  5. Order is the order in which you want this status to be rendered on the Gumband UI in relation to other statuses.

Restart sample.js and navigate to the Gumband UI to see the updated status:

Now update the status value from Exhibit code by using a function provided by the SDK:

gb.on(Sockets.READY, async () => {
  console.log('Gumband READY!');
  
  // Called with the id in the manifest file.
  await gb.setStatus('example_status', 'the new status');
});

Restart sample.js and navigate back to the Gumband Exhibit Overview UI to see that the status has updated in real time:

You can also get a status from the Gumband SDK:

gb.on(Sockets.READY, async() => {
  console.log('Gumband READY!');
  
  // Called with the id in the manifest file.
  await gb.setStatus('example_status', 'the very different status');
  
  const status = await gb.getStatus('example_status');
  
  console.log(status.value);
});

Create and Receive a Control

Similar to creating a status, we will add a control. Open your manifest file and add the following control to the “controls” array:

{
  "manifest": {
    "statuses": [],
    "controls": [
      {
        "id": "reload",
        "type": "Single",
        "display": "Reload",
        "enabledOpMode": "On"
      }
    ],
    "settings": []
  }
}
  1. Id is a unique id for this control

  2. Type indicates how you want the control to be rendered in the Gumband UI - in our case a single button

  3. Display is the text you want to appear on the control - in our case we will use this to “reload” our Exhibit

  4. EnabledOpMode indicates when this control should be active. In our case reload only makes sense when the Exhibit is on but you can imagine that running a homing procedure for a robot might be something you would only do if the Exhibit was off.

Restart sample.js and navigate to the Gumband Exhibit Controls UI to see the newly added control:

Add code to react to incoming Control messages:

gb.on(Sockets.CONTROL_RECEIVED, async(payload) => {
  if (payload.id === "reload") {
    console.log("We should reload our application!");
  }
});

Click the reload button in the Gumband UI to see the console message.

Create, Update, and Receive a Setting

Just like the last two sections, we will start this one by updating the manifest file.

{
  "manifest": {
    "statuses": [],
    "controls": [],
    "settings": [
      {
        "id": "idle_timeout_secs",
        "type": "IntegerInput",
        "display": "Idle Timeout (secs)",
        "default": 30,
        "enabledOpMode": "Off"
      }
    ]
  }
}
  1. Id is the unique id of this setting

  2. Type is the type of value you would like to store, in our case an integer, and we will allow users to enter any integer they like in the UI

  3. Display is the display name you will see in the gumband UI

  4. Default is the value you would like to start with, in our case 30 seconds.

  5. EnabledOpMode again indicates when this setting can be applied. In our case we want to update settings only when the Exhibit is off.

Add code to react to incoming Setting messages:

gb.on(Sockets.SETTING_RECEIVED, async(payload) => {
  if (payload.id === "idle_timeout_secs") {
    console.log(`New idle timeout: ${ payload.value }`);
  }
});

Restart sample.js and navigate to the Settings tab on the Gumband UI

  1. As you can see the box to update this setting is greyed out and uneditable. This is because our operating mode is currently On (indicated by the large toggle with the lightning bolt next to the Exhibit name).

  2. If you toggle operating mode Off the box will become active

  3. Enter a new value and click “Save”.

In your console you will now see:

Add Developer Logging

Add the following log lines to your application code:

gb.on(Sockets.READY, async () => {
    console.log('Gumband Ready!');
    
    gb.logger.debug('This is a debug log');
    gb.logger.info('This is an info log');
    gb.logger.warn('This is a warn log');
    gb.logger.error('This is an error log');
});
  1. Debug logs will stay for 24 hours

  2. Info logs will stay for 72 hours

  3. Warn logs will stay for 1 week

  4. Error logs will only be deleted when a user deletes them

Note: logging must start AFTER Gumband emits the ready state

Restart sample.js and navigate to the Gumband UI “Logs” tab and you should see your logs

Add Events for Reporting

Recording events is extremely easy with the Gumband SDK. To do so add some code similar to the following:

gb.on(Sockets.READY, async (manifest) => {
    console.log('Gumband Ready!');
    
    for (let i=0; i<10; i++) {
      await gb.event.create("Blue Button Press", {});
    }
    
    for (let i=0; i<5; i++) {
      await gb.event.create("Red Button Press", {});
    }
    
    await gb.event.create("Yellow Button Press", {});
});

Allow a minute for the new events to be added to the reporting system and then navigate to the reports tab on the UI. You will see a graph similar to this:

Constructor Paramaters

You can initialize the Gumband SDK with a few parameters:

const gb = new Gumband(
  GB_EXHIBIT_TOKEN,
  GB_EXHIBIT_ID,
  `manifest.json`,
  {
        endpoint: 'custom', // local, dev, stag, or custom (set to 'app' by default)
        customServerIP: 'test.gumband.com', // or an IP address such as '192.168.1.1' (ignored unless endpoint=custom)
        version: 'v1', // api version
        contentLocation: '/path/to/content', // a directory to sync files in or null to not sync content
        skipOrganizationFileSync: false, // whether or not to skip the org level file syncing
        gbttEnabled: false, // or true to enable the hardware MQTT broker (set to false by default)
        gbttPort: 8884, // port for the MQTT broker, defaults to 1883
        noInternetConnection: false, // true if the SDK needs to run in offline mode (set to false by default)
        noInternetHardwareIds: [], // array of offline hardware IDs to accept messages from (without auth)
  }
);
  • version (string): What API version to use. Value should be v1.

  • endpoint (string): What Gumband environment to operate with. Value can be local, dev,stag, app, or custom.

  • customServerIp (string): If endpoint=custom, what DNS name or IP address is the Gumband environment at. Value should be similar to test.gumband.com or 192.168.1.1.

  • contentLocation (string || null): Assets uploaded to Gumband will be synced to the specified folder. Active user must have write permission for this directory. It is advised use an absolute instead of relative path. This value can be set to null to explicitly not sync any files.

  • skipOrganizationFileSync (boolean): Set to false to sync organization level files. Defaults to true.

  • gbttEnabled (boolean): Set to true to run the MQTT broker for hardware communication, defaults to false.

  • gbttPort (number): What port to run the MQTT broker, defaults to 1883.

  • noInternetConnection (boolean): Whether the exhibit will run in offline mode. Default is false. This is mostly useful for when an exhibit is going to run without an internet connection but still wants to communicate with Gumband hardware through MQTT.

  • noInternetHardwareIds (string[]): Specify an array of Gumband hardware IDs to allow to connect to this exhibit. Used in conjunction with noInternetConnection=true. Warning: this will allow any hardware with the specified IDs to send and receive data from the exhibit without authentication.

Constructor Parameter example: contentLocation

The Gumband SDK automatically synchronizes a local content folder and emits an event when files change. The files can be audio, video, configuration files, etc. When the SDK initializes, all content stored in Gumband is synced with your specified content folder locally.

To handle live file changes while the system is running, add a listener for file uploads in sample.js and sync the file content when received:

const gb = new Gumband(
  GB_EXHIBIT_TOKEN,
  GB_EXHIBIT_ID,
  `manifest.json`,
  {
    contentLocation: './content'
  }
);

gb.on(Sockets.READY, async () => {
    console.log('Gumband is ready!');
    
    // Listen for file uploads
    gb.on(Sockets.FILE_UPLOADED, async() => {
      //This is also done automatically when the node application initializes
      await gb.content.sync();
    });
});
  1. Restart sample.js and navigate to the Gumband UI “Content” tab

  2. Select a file and click “Upload”

Your file will appear in the list once it has been uploaded successfully.

Check the content folder for your Exhibit, which should now contain your file.

  • No labels