Upgrade to Pro — share decks privately, control downloads, hide ads and more …

IoT and JS(?!?!) - Grizzhacks 2019

Joe Karlsson
September 28, 2019

IoT and JS(?!?!) - Grizzhacks 2019

My favorite things in life are cats 🐈, computers 🖥 and crappy ideas 💩, so I decided to combine all three and make an IoT (Internet of Things) litter box using a Raspberry Pi and JavaScript! If you have ever wanted to get build your own IoT project, but didn’t know how to start, then this is the talk for you.

Together, we will go through how I setup my IoT Litter Box from start to finish. Including how to setup Node.js on a Raspberry Pi and how to connect sensors to a Raspberry Pi and how to read the sensor inputs with Node.js.

Joe Karlsson

September 28, 2019
Tweet

More Decks by Joe Karlsson

Other Decks in Programming

Transcript

  1. { name: “Joe Karlsson”, company: “MongoDB”, title: [ “Developer Advocate”,

    “Software Engineer” ], twitter: “@JoeKarlsson1”, twitch: “joe_karlsson”, website: “joekarlsson.com”, }
  2. Program faster! Documents map to data structures in most popular

    languages. Update Your Profile @JoeKarlsson1 { first_name: "Paul", surname: "Miller", cell: "447557505611", city: "London", location: [45.123,47.232], profession: ["banking", "finance", "trader"], cars: [ { model: "Bentley", year: 1973 }, { model: "Rolls Royce", year: 1965 } ] }
  3. SQL MongoDB Query faster! Stop doing expensive joins to get

    your data. ID a ... 1 b ... 2 ... ... 3 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... { ...
 a: “b”,
 ... c: {
 d: “e”
 ...
 },
 ... } @JoeKarlsson1
  4. Pivot easier! Easily change the shape of your data as

    your app evolves. SQL MongoDB {
 a: “b”,
 c: “one”,
 e: “f” } {
 a: “b”,
 c: 1,
 new: “no biggee” } ALTER TABLE `mydb`.`letters_table` DROP COLUMN `e`, ADD COLUMN `New` VARCHAR(45) NULL AFTER `C`, CHANGE COLUMN `C` `C` INT NULL DEFAULT NULL ; @JoeKarlsson1
  5. Term mapping summary Row Column Table Database Index Join Join

    Left Outer Join Recursive Common Table Expressions View Transaction Document Field Collection Database Index Embedding Database References $lookup $graphLookup View Transaction @JoeKarlsson1
  6. Did you know that? • MongoDB supports distributed ACID transactions?

    • MongoDB added field level encryption? • MongoDB is now PCI compliant? • MongoDB now has schema validation? @JoeKarlsson1
  7. @JoeKarlsson1 Agenda • Intro to IoT • IoT data cycle

    • Why JS and IoT? • IoT data best practices • IoT Demo • The future of IoT @JoeKarlsson1
  8. @JoeKarlsson1 A network of devices that have an IP address

    and can communicate with each other over the internet @JoeKarlsson1
  9. @JoeKarlsson1 A company is an association or collection of individuals,

    whether natural persons, legal persons, or a mixture of both. Company members share a common purpose and unite in order to focus their various talents and organize their collectively available skills or resources to achieve specific, declared goals. Collect Devices and sensors collect data @JoeKarlsson1
  10. @JoeKarlsson1 A company is an association or collection of individuals,

    whether natural persons, legal persons, or a mixture of both. Company members share a common purpose and unite in order to focus their various talents and organize their collectively available skills or resources to achieve specific, declared goals. Communicate Data and events sent through the network Data Center The Cloud Home Router @JoeKarlsson1
  11. @JoeKarlsson1 A company is an association or collection of individuals,

    whether natural persons, legal persons, or a mixture of both. Company members share a common purpose and unite in order to focus their various talents and organize their collectively available skills or resources to achieve specific, declared goals. Analyze Computers analyzes the incoming data Run Reports Home Router Machine Learning View Reports @JoeKarlsson1
  12. @JoeKarlsson1 A company is an association or collection of individuals,

    whether natural persons, legal persons, or a mixture of both. Company members share a common purpose and unite in order to focus their various talents and organize their collectively available skills or resources to achieve specific, declared goals. Act Taking action based on the data Send a notification Communicate with
 another machine Stream @JoeKarlsson1
  13. @JoeKarlsson1 JS is a great choice for new devs Other

    low level programming languages can be difficult to develop @JoeKarlsson1
  14. @JoeKarlsson1 Why Node? 58 percent of respondents that identified as

    IoT developers use Node Source: https://nodejs.org/en/blog/announcements/nodejs-foundation-survey/ @JoeKarlsson1
  15. @JoeKarlsson1 • Capable of high speed data ingest • An

    event driven DB • Makes it easy to update your schema • Great at handling time series data @JoeKarlsson1 MongoDB is:
  16. @JoeKarlsson1 1 x Raspberry Pi 3 Model B 1 x

    Breadboard 1 x HX711 Module [Load cell amplifier] What Materials Do We Need? 4 x 50 kg load cells [used to measure the weight] 1 x Magnetic door sensor 1 x Kitty Litter Box
  17. @JoeKarlsson1 General Purpose Input/Output Pins [GPIO] Can be used to

    interact in with the real world @JoeKarlsson1
  18. @JoeKarlsson1 Input Pins Switches that you can turn on or

    off from the outside world @JoeKarlsson1
  19. @JoeKarlsson1 Great Overview of the GPIO Pins on Wikipedia @JoeKarlsson1

    Source: https://en.wikipedia.org/wiki/Raspberry_Pi#General_purpose_input-output_(GPIO)_connector
  20. @JoeKarlsson1 var five = require("johnny-five"); var Raspi = require("raspi-io").RaspiIO; var

    board = new five.Board({ io: new Raspi() }); board.on("ready", function() { var led = new five.Led("P1-13"); led.blink(); });
  21. @JoeKarlsson1 • When box is opened, go into maintenance mode.


    • When the box is closed, recalibrate weight.
 • When significant weight is sensed, take weight measurement of cat and send data to MongoDB Atlas. @JoeKarlsson1
  22. @JoeKarlsson1 const { RaspiIO } = require('raspi-io'); const five =

    require(‘johnny-five'); const board = new five.Board({ io: new RaspiIO(), }); let state = { isMaintenenceMode: false, }; board.on('ready', () => { const spdt = new five.Switch('GPIO16'); spdt.on('open', () => { state.isMaintenenceMode = true; }); spdt.on('close', () => { state.isMaintenenceMode = false; }); });
  23. @JoeKarlsson1 import time import sys import RPi.GPIO as GPIO from

    hx711 import HX711 while True: try: except (KeyboardInterrupt, SystemExit): cleanAndExit() hx = HX711(5, 6) hx.set_reading_format("MSB", "MSB") hx.set_reference_unit(1) hx.reset() hx.tare() def cleanAndExit(): print("Cleaning...") GPIO.cleanup() print("Bye!") sys.exit() val = hx.get_weight(5) print(val) hx.power_down() hx.power_up() time.sleep(0.1) loadCell.py
  24. @JoeKarlsson1 const spawn = require('child_process').spawn; const process = spawn('python', ['./hx711py/scale.py'],

    { detached: true }); // Takes stdout data from script which executed // with arguments and send this data to res object process.stdout.on('data', data => { let currWeight = parseFloat(data); let avgWeight = updateAverageWeight(currWeight, recentsWeights); }); process.stderr.on('data', err => { console.error(err); }); process.on('close', (code) => { console.log(`child process exited with code ${code}`); });
  25. @JoeKarlsson1 process.stdout.on('data', data => { let currWeight = parseFloat(data); let

    avgWeight = updateAverageWeight(currWeight, recentsWeights); }); const checkIfCatIsPresent = (avgWeight, baseBoxWeight) => { if (avgWeight - bufferWeight > baseBoxWeight + config.cat.weight) { return true; } return false; }; const updateAverageWeight = (currWeight, recentsWeights) => { if (currWeight) { const maxArrLength = 20; if (recentsWeights.length >= maxArrLength) { recentsWeights.shift(); } recentsWeights.push(currWeight); return getAvg(recentsWeights); } }; const getAvg = arr => { if (arr.length) { const sum = arr.reduce(function(a, b) { return a + b; }, 0); const avg = sum / arr.length; return avg; } return arr[0]; }; const catPresent = checkIfCatIsPresent(avgWeight, baseBoxWeight); if (catPresent) { // Send data to MongoDB }
  26. @JoeKarlsson1 Connect our IoT app with the Node MongoDB Driver

    @JoeKarlsson1 Want $200 in free credits? http://bit.ly/grizzhacks
  27. const MongoClient = require(‘mongodb').MongoClient; const uri = ‘mongodb+srv://kay:[email protected]/iot const client

    = new MongoClient(uri, { useNewUrlParser: true }); client.connect(err => { const collection = client.db(‘IoT’).collection('toilets'); // perform actions on the collection object client.close(); });
  28. @JoeKarlsson1 • Smooth out calibration • Hook up Stitch functions

    to send out weekly email report • Make web app that visualizes my cats bathroom habits/weight with MongoDB Charts @JoeKarlsson1
  29. @JoeKarlsson1 1 x Raspberry Pi 3 Model B 1 x

    Breadboard 1 x 68 Ohms Resistor What Materials Do We Need? 1 x LED 2 x Female to Male Wires
  30. @JoeKarlsson1 General Purpose Input/Output Pins [GPIO] Can be used to

    interact in with the real world @JoeKarlsson1
  31. @JoeKarlsson1 Input Pins Switches that you can turn on or

    off from the outside world @JoeKarlsson1
  32. @JoeKarlsson1 Great Overview of the GPIO Pins on Wikipedia @JoeKarlsson1

    Source: https://en.wikipedia.org/wiki/Raspberry_Pi#General_purpose_input-output_(GPIO)_connector
  33. @JoeKarlsson1 LED Resistors Resistors are used to reduce current, adjust

    signal levels, etc. A diode that emits light when a voltage is applied to it. @JoeKarlsson1
  34. @JoeKarlsson1 Smaller and more powerful devices \ Better Hardware support

    JS with a smaller footprint Batteries will become the bottleneck The Future of JS + IoT? @JoeKarlsson1
  35. @JoeKarlsson1 IoT is exploding Raspberry Pi’s use GPIO to interact

    with the real world JS is a great choice for IoT Easy to update apps Internet already speaks JS Great supporting libraries JS excels at event-driven apps Start with a small project and jump in and learn as you go! MongoDB is a great choice for IoT projects
  36. { name: “Joe Karlsson”, company: “MongoDB”, title: [ “Developer Advocate”,

    “Software Engineer” ], twitter: “@JoeKarlsson1”, twitch: “joe_karlsson”, website: “joekarlsson.com”, }
  37. MongoDB Community • MongoDB University: • university.mongodb.com • MongoDB Community

    Slack Channel: • https://mongo-db.slack.com/ @JoeKarlsson1
  38. @JoeKarlsson1 •$200 in free Atlas credits: http://bit.ly/grizzhacks •Code - https://github.com/JoeKarlsson/IoT-Morse-

    Code-Demo • IoT Reference Architecture - https:// www.mongodb.com/collateral/iot-reference-architecture •Time Series Data and MongoDB: Best Practices Guide - https://www.mongodb.com/collateral/time-series-best- practices
 •A language for the Internet: Why JavaScript and Node.js is right for Internet Applications - Tom Hughes- Croucher Additional Resources