5— Using Nomad to Broadcast Particle Data

Publish and subscribe using the Particle Event Stream and a Photon

For people who want to build Nomad sensor nodes, we have sample documents in /particle that will help you start to build your publisher and start subscribing, even doing logic on the data and actuating a response!

In this portion we'll just teach you how to reach data from your particle event stream and get the data into a browser through the help of nomad.


Heads Up! This Guide is Gonna get Real Nerdy Real Quick!

This guide assumes you have at least a small bit of knowledge on how to work with particle and wire things up correctly. Particle has a ton of great documentation on their site. We'll be using the Particle Build Web IDE to interface with Particle Photons.


The Setup — A Beam Break Detection Example

For this tutorial, we're going to set your photon up according to this photon documentation example, which can be completed using the components you'll find in the core photon development kit. If you don't care about this, just skip to step 2 to see how Nomad communicates with the Particle API.

1— Getting your particle running and pinned up

Once you have your particle photon setup on your phone per the documentation directions, we'll disconnect it from power so we can wire it up with out pinout for the prototype. We're going to let you use your plugging-things-into-other-things skills here, so follow the particle documentation to get things pinned up and flash the example firmware they give you to your device using the Particle Build IDE.

I'm pasting their fritzing diagram here:

Ask Yourself:

  • Is your photon setup per the directions?
  • Did you re-connect the particle back to power?
  • Did you flash the example code to your Device?

2— Getting the Publishing Nomad Node Running

The particle-base-with-nomad.js file contains everything you need to create a Nomad node that broadcasts your photon's particle event stream. You will need to know:

  • Your Particle Account Credentials (Email, Password)
  • Your Particle Device ID, You can get this from your particle phone app by selecting your particle or the Particle Build IDE
  • Your Particle API Access Token, You can get this from the settings tab in your Particle Build IDE

We're listing the code here for quick access:

const Nomad = require('nomad-stream')              // Includes the nomad js
const Particle = require('particle-api-js')        // Includes the particle api js
const credentials = require('./particle-login')    // Requires your particle credentials without exposing them

const deviceID = 'YOUR_PARTICLE_DEVICE_ID'         // This is your particle's Device ID, find it in your particle app, or from the Build IDE interface
const events = ['your_event']                      // These are the names of the events you want to track from the Event Stream

const particle = new Particle()
const node = new Nomad()

let instance = null
let token = null
let stream = null
let publish = null

const privKey = 'YOUR_BIG_LONG_PRIVATE_KEY'

/* This is optional, but if you don't provide a private key,
your Node's subscription ID will be different every time you restart your node.
If you comment this out, remember to take it out of the node.start() function below. */

node.start(privKey)
  .then(() => {
    return particle.login(credentials)            // Sends a request to the particle API to login
  })
  .then(response => {
    token = response.body.access_token            // Gets an access token from the particle API on success
    console.log(`Got token: ${token}`)
    return particle.getEventStream({ deviceId: deviceID, name: events[0], auth: token })   // Gets the particle event stream
  })
  .then(stream => {
    stream.on('event', data => {
      node.publish(JSON.stringify(data))         // Converts the data to a string and streams it whenever new events come through
      console.log(data)
    })
  })
  .catch(err => {
    console.log(err)
  }) 

Breaking Down the Code

The first part of the code is just requirements for access to the particle api and including nomad in your app.

const Nomad = require('nomad-stream')              // Includes the nomad js
const Particle = require('particle-api-js')        // Includes the particle api js
const credentials = require('./particle-login')    // Requires your particle credentials without exposing them

particle-login.json is comprised of your personal login credentials for your particle account (Or whatever account that has access to the particles themselves.) Since this is node.js code, we can require this on the server side and it doesn't get exposed, which is pretty handy, since we're going to use it to authenticate with the api and get an access token so we can interact with your particles.

A template for particle-login.json would be:

{
  "username": "[email protected]",
  "password": "your_super_secret*password!123",
   "access_token": "YOUR_ACCESS_TOKEN",         // This can be retrieved from the settings region of the Particle Build IDE
  "token_type": "bearer",
  "expires_in": 7776000,
  "refresh_token": "b5b901e8760164e134199bc2c3dd1d228acf2d90"
}

Providing a private key for your node is optional, but if you don't provide one, your nomad node will have a different subscription ID every time it's restarted. You can generate some throwaway private keys here for the demo.

const privKey = 'YOUR_BIG_LONG_PRIVATE_KEY'

/* This is optional, but if you don't provide a private key,
your Node's subscription ID will be different every time you restart your node.
If you comment this out, remember to take it out of the node.start() function below. */

node.start(privKey)

In the particle documentation code example we're referencing, you name the event that fires when the beam is broken, so in the events[] array, you'll replace your_event with your unique event name. Note, this MUST match the name in your particle event stream, or else the api won't know what event to grab data for.

const deviceID = 'YOUR_PARTICLE_DEVICE_ID'         // This is your particle's Device ID, find it in your particle app, or from the Build IDE interface
const events = ['your_event']                      // These are the names of the events you want to track from the Event Stream

The following series of promises makes a request to the particle API to obtain an authorization token which it uses to read the particle event stream for your specific device. It then inserts the JSON output into a variable, data and then converts it to a string and streams it every time a new particle event occurs.

.then(() => {
return particle.login(credentials) // Sends a request to the particle API to login
})
.then(response => {
token = response.body.access_token // Gets an access token from the particle API on success
console.log(`Got token: ${token}`)
return particle.getEventStream({ deviceId: deviceID, name: events[0], auth: token }) // Gets the particle event stream
})
.then(stream => {
stream.on('event', data => {
node.publish(JSON.stringify(data)) // Converts the data to a string and streams it whenever new events come through
console.log(data)
})
})
.catch(err => {
console.log(err)
})

Now that you understand what's going on, let's start IPFS:

ipfs daemon

Then In a new terminal window, run the code we just wrote:

node particle-base-with-nomad.js

The publisher will generate an id, print it, and start publishing messages from the Particle event stream whenever they occur. In this tutorial your event should fire every time your slip a piece of paper between the photoresistor and the led. You should see messages printed every time this happens.

The publisher stores its identity in files in the directory/store. If you stop the publisher and run it again, you'll need to delete/storefirst.

When you started your node, you should see its subscription id printed at the beginning of the stream, copy this to your clipboard, you'll need it for the next step!

It'll look something like: QmXLZvD9yaD7A5AhwWWggN7dhsAznLGxXGXKWvREgArAFT

3— Subscribing to the data in browser

Once you've copied your node's publisher id from the previous step, open browser/subscribe.js and insert it into the subscriptionId const. This will subscribe this node to the publisher you made before. Afterwards, right-click browser/subscribe.htmland open it in google chrome. You should see your particle event stream printing into the view as events occur.

(() => {
  // ID of the node to subscribing to
  const subscriptionId = 'A_SUBSCRIPTION_ID'

  // Setup
  //////////////////////////////////////////

  // Turn on logging for libp2p
  localStorage.debug = 'libp2p*'
  // // Turn on logging for nomad
  // localStorage.debug = 'nomad*'

  // Config for the publishing node
  // You probably will never need to change this
  const DEFAULT_CONFIG = {
    db: ``,
    repo: `subscriber`, // this is the name o
    ipfs: { bits: 2048, emptyRepo: true }
  }

  // IndexDB is where data for the node is stored in the browser
  const indexedDB = window.indexedDB ||
          window.mozIndexedDB ||
          window.webkitIndexedDB ||
          window.msIndexedDB

  // Clear out the indexDB data if it exists - otherwise IPFS will throw an error
  indexedDB.deleteDatabase(DEFAULT_CONFIG.repo)


  // Creating a subscribe node
  //////////////////////////////////////////

  const node = new Nomad(DEFAULT_CONFIG)

  // Create a node and start publishing every n seconds
  node.start()
    .then(() => {
      const nodeId = node.identity.id

      const pubStr = `Your node ID is:\n ${nodeId}`
      const subStr = `You are subscribing to:\n ${subscriptionId}`

      window.nomadUtils.addElement(pubStr)
      console.log(pubStr)

      window.nomadUtils.addElement(subStr)
      console.log(subStr)

      node.subscribe([ subscriptionId ], (data) => {
        window.nomadUtils.addElement(`Received a new message: ${data.message}`)
        console.log(data)
      })
    })
})()

results matching ""

    No results matching ""