Dynamic Apps with WebSockets and MQTT - IBM Impact 2014


Published on

Learn about how MQTT and WebSockets can drive dynamic, real-time HTML5 applications. The presentation dives into MQTT topic/payload details for 4 demos and gives tips for designing a scalable, location-based topic structure.

Published in: Software, Technology
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Dynamic Apps with WebSockets and MQTT - IBM Impact 2014

  1. 1. © 2014 IBM Corporation Dynamic Mobile Apps with WebSockets and MQTT
  2. 2. The Compelling Experience What makes an application a delight to use? -  Data arrives when you need it, not when you ask for it -  The app provides a collaborative, social experience -  Services are integrated seamlessly together 1
  3. 3. HTML5 WebSocket for Real-time “A conversation on the web” "   WebSocket is bidirectional •  HTTP is request/response, WebSocket is a conversation "   WebSocket is an HTML5 standard •  Cross-domain communication •  Supported by all major browsers 2 http://caniuse.com/websockets
  4. 4. MQTT for Mobile Messaging "   What is it? •  Publish/subscribe messaging protocol designed for mobile and telemetry devices •  Open (royalty-free), simple, lightweight, easy to implement •  Allows for decoupled applications (“Internet of Things”) •  Quality of service for assured message delivery •  MQTT clients connect to an MQTT broker "   Where is it? •  Connected vehicles (ex. Sprint Velocity) •  Connected cities (ex. NYPD ESU) •  Connected people (ex. Facebook Messenger) •  ...and everywhere else 3
  5. 5. Why MQTT? "   Publish/subscribe messaging •  Transmit information one to many •  Subscribe to interesting topics •  Distribute small data packets in huge volumes "   Quality of Service (QoS) for assured messaging •  “At most once”, “At least once”, “Exactly once” "   Simple API •  3 verbs: Connect, Publish, Subscribe (+ Receive) •  Useful features: Last Will and Testament, Retain •  Clients everywhere (40+) –  JavaScript, C, C++, Python, Node.js, Java, Ruby, etc. "   Lightweight •  2-byte header, low latency •  Mobile (LTE) = ~100ms, Browser (Wifi) = ~50ms (RTT) 4
  6. 6. Quick Demo – Whiteboard bit.ly/impactwb 5
  7. 7. Compelling Experience "   Real-time Monitoring (RaceTracker)" "   Scalable Group Chat (Chatterbox)" "   Cross-platform MMOG (Starfighter)! "Agenda (for each demo)" 1.  Problem" 2.  Scenario / Architecture" 3.  Messaging design" 4.  Play time" 5.  "What else is possible?"" 6 Fire up your laptops!
  8. 8. RaceTracker
  9. 9. RaceTracker "   Problem – Marathons are crowded •  Me: “Meet me at mile 17.3 with Gatorade around... 9:00-9:30” •  Wife: “...could you be more specific?” "   Solution – “RaceTracker” 1.  Publish location from iPhone 2.  Calculate speed/stats in real time 3.  Display runner info in a mobile app 4.  Live-tweet the race "   Challenges •  Network congestion (QoS!) •  Wiring applications (pub/sub!) 8
  10. 10. Scenario 9 BlueMix Runner Viewer Analytics Tweeter Broker
  11. 11. 10 OwnTracks (iOS / Android) •  Open-source "location diary" •  Publishes MQTT location data at interval •  http://owntracks.org "   Pubs •  Location Data (retained) –  RaceTracker/<race>/Person/<runner> •  {  "_type":"location","tst":"1392569738",   "lat":"30.3019","lon":"-­‐97.7278",  "batt":"30","acc":"5"}   "   Subs •  [nothing] Runner
  12. 12. 11 Node.js runtime in BlueMix •  Performs speed calculations on runner data, maintains course state, outputs events ("runner X crossed mile 5") "   Pubs •  Course Data (retained) –  RaceTracker/<race>/Marker/<type> •  {  "id":"start",  "lon":30.30214,  "lat":-­‐97.77801  }   –  RaceTracker/<race>/Marker/<type>/text •  {  "text":"Crossed  at  7:38  AM  with  a  split  of  8:28"  }   –  RaceTracker/<race>/Course •  "-­‐97.73911714,30.277803  &  -­‐979780987,30.28985  &  <lon>,<lat>  &"   •  Events (QoS 2) –  RaceTracker/<race>/Person/<runner>/event •  {  "type":"split",  "splitTime":"10:42:13",  "splitMarker":"mile  2",   "splitString":"9:45"  }   •  {  "type":"finish",  "time":"11:43:13",  "totalTime":"4:15:13"  }   Analytics
  13. 13. Analytics 12 "   Pubs (cont.) •  Live Analytics (retained) –  RaceTracker/<race>/Person/<runner>/text •  {  "text":  "Pace:  (about)  9:18  min/mile"  }   "   Subs •  Location Data –  RaceTracker/<race>/Person/+ •  {  "_type":"location","tst":"1392569738",   "lat":"30.3019","lon":"-­‐97.7278",  "batt":"30","acc":"5"}   Analytics
  14. 14. 13 HTML5 Map UI •  Course data, analytics, and runners are displayed on a map and updated in real-time through MQTT over WebSockets •  Uses OpenLayers JavaScript library with ESRI imagery "   Pubs   •  [Nothing] "   Subs •  Location Data –  RaceTracker/<race>/Person/+ •  Live Analytics –  RaceTracker/<race>/Person/+/text –  RaceTracker/<race>/Marker/+/text •  Course Data –  RaceTracker/<race>/Marker/+ RaceTracker/<race>/Course Viewer
  15. 15. Play time bit.ly/IBMRaceTracker 14
  16. 16. What else is possible? "   This is a simple messaging model (flows 1 direction) •  “But WebSocket is bidirectional!” "   Future Ideas: •  Voice chat to runner –  Audio encouragement •  Augment runner app with live leaderboard –  Google Glass = augmented reality race –  “Arnaud Mathieu is 0.23 miles ahead of you!” "   A decoupled application with MQTT allows for easy extension and integration of new features "   What else is possible? 15
  17. 17. Chatterbox

  18. 18. Chatterbox "   Problem •  Need scalable chat that works anywhere you are. –  2G in the country, LTE in the city, Wifi at Impact! –  Reliability is key •  Need scalable chat that works on any device –  Think desktop, mobile... wearable, etc. "   Solution – “Chatterbox” •  MQTT HTML5 ßà MQTT native iOS •  Assured messaging with QoS •  Text, picture, audio, video chat "   Challenges •  Cross-platform messaging (MQTT Paho clients!) •  Constrained networks (MQTT durable subscriber!) 17
  19. 19. Scenario 18 Broker Chatterbox HTML5 - Desktop Chatterbox HTML5 - Mobile Chatterbox iOS
  20. 20. 19 Web App / Native App (iOS) •  All clients use same "Chatterbox" JSON API "   Pubs •  Room Data (retained) –  chatterbox/Room/<room_id> •  {  "id":"IBMIMP5116",  "name":"IBM  Impact",  "password":""  }   •  Presence (retained) –  chatterbox/Room/<room_id>/User/<uuid> •  {  "displayName":"Bryan  Boyd",  "color":"green",  "uuid":<uuid>  } •  Chat Data –  chatterbox/Room/<room_id>/Chat •  {  "name":"Bryan  Boyd",  "uuid":<uuid>,  "format":"text",   "data":"Hello  world!",  "index":0,  "max":1,  "id":"b4ps8fjqgg",   "timestamp":1398875852255  } Chatterbox
  21. 21. 20 "   Subs •  Room Data (retained) –  chatterbox/Room/+ •  Presence (retained) –  chatterbox/Room/<room_id>/User/+ •  Chat Data –  chatterbox/Room/<room_id>/Chat Image / Audio / Video •  Split, send as QoS 1, reconstruct message at subscribers      {  "name":"Bryan  Boyd",  "uuid":<uuid>,  "id":"b4ps8fjqgg",  "timestamp":  ...            "format":"data:audio/wav;base64",  "index":1,"max":6,  "data":"UklGriDAAQZa...          "format":"data:image/png;base64",  "index":7,"max":17,  "data":"whW+fd+JsGg...          "format":"data:video/mp4;base64",  "index":9,"max":31,  "data":"8F/yzUBAQY...   Chatterbox
  22. 22. Play time [see Arnaud for free tablets] or bit.ly/ibmchatterbox (use Chrome, accept camera/microphone prompts) 21
  23. 23. What else is possible? "   Even more collaboration •  Broadcast streaming audio, video •  Screen share, drawing •  Record MQTT messages to “archive” a collaboration and play back in real time "   Integrate social media •  Link twitter account •  Type “:tweet: <chat>” to publish a tweet "   What else is possible? 22
  24. 24. Starfighter
  25. 25. Starfighter "   Problem •  Quickly build a massively multiplayer game •  Need low latency from client to client •  To scale, we need to intelligently deliver the right data to the right place at the right time "   Solution – “Starfighter” •  MMOG, IoT-style... •  Every ship is a MQTT client –  Humans: HTML5, Bots: Node.js •  Every action is a message –  Shoot / Move / Hit •  Client-to-Broker-to-Client for low latency "   Challenges •  Data management (dynamic subscriptions!) 24
  26. 26. Scenario 25 Broker Player AI Bot Viewer BlueMix BlueMix Scoring
  27. 27. Mobile-ready App (HTML5) 26 "   Pubs •  "Telemetry" – 16 msg/sec –  starfighter/players/ship/<z>/<x>/<y>/<uuid> {  "uuid":"gqds2na46a","time":1398962284414,      "name":"@bryanboyd","type":"ship",      "worldPos":  {"x":"10022.6","y":"2698.2"},      "velocity":  {"x":"0.1","y":"185.8"},  "angle":"8.9",      "shield":"1.0000",  "status":"NORMAL",  "score":0      "lastHitTime":1398962247380,  "lastUpdate":1398962261510  }   •  Gunfire –  starfighter/players/bullet/<z>/<x>/<y>/<uuid> •  {  "uuid":"gqds2na46a",  "action":"shoot",  "bullets":3  } •  Events –  starfighter/players/event/<z>/<x>/<y>/<uuid> •  {  "uuid":"gqds2na46a",  "name":"@bryanboyd",  action:"hit",   "damage":0.03,  "by":"u6xnd"  }   •  {  "uuid":"gqds2na46a",  "name":"@bryanboyd",  action:"destroyed",   "bonus":500,  "by":"u6xnd"  }
  28. 28. Mobile-ready App (HTML5) 27 "   Subs •  "Telemetry" –  starfighter/players/ship/<z>/<x>/<y>/+ •  Gunfire –  starfighter/players/bullet/<z>/<x>/<y>/+ •  Events –  starfighter/players/event/<z>/<x>/<y>/+ How does this scale? Not well. -  10 players x 16 msgs/sec telemetry is okay -  100 players x 16 msgs/sec telemetry is not -  10000 players x 16 msgs/sec...
  29. 29. 28 "   Idea: •  Map ship x,y coord to a map region •  Include region in the topic •  Publish multiple feeds at different rates: –  z = 0, 1 msg/sec –  z = N, 2n msg/sec ... –  z = 4, 16 msg/sec –  Total = (2z_max – 1) •  As your ship changes regions, change the publishing topic Location Topics 3210 1 2 3 0 1 0 1 0 0 z = 0 z = 1 z = 2
  30. 30. 29 "   Idea •  Which feeds do I need? (find z) –  smallest map region that encompasses viewport •  Where am I? (find x, y) •  Subscribe to z/x/y and the neighboring regions •  As your ship changes regions, subscribe to the new topics and unsubscribe from the old "   Benefits •  Viewer just subscribes to z = 0, gets N msgs/sec •  Player gets fine-grained data about neighboring players to draw smoothly... no more "lag kills" Dynamic Subscriptions
  31. 31. Hackathon-ready "   To build an AI... •  Pick a random position and vector •  Publish telemetry, update position over time, and fire away •  Subscribe to topics for local region •  If a player gets within X dist, update vector to intercept " Node.js bots in BlueMix 30 BlueMix
  32. 32. Play time 31 [see Arnaud for free tablets] or bit.ly/playstarfighter optimized for Google Chrome
  33. 33. What else is possible? "   Other scenarios: •  Fleet management –  Track vehicle movements and inventory in real time –  Provide feeds of different granularity based on map region •  Online gaming – poker, horse betting –  Pub/sub is good for a gaming table, real-time race tracking, assured messaging for placing bets •  Collaboration –  Many users can control and affect the same virtual space "   What else is possible? 32
  34. 34. Takeaways
  35. 35. Takeaways "   WebSockets – extending real-time communication to browsers "   MQTT – scalable, reliable, fast messaging everywhere •  Scalable – pub/sub, tiny headers •  Reliable – quality of service for assured messaging •  Fast – with the right broker, low latency at scale •  Everywhere – Eclipse Paho clients A great protocol needs a great broker... 34
  36. 36. IBM MessageSight "   Secure messaging for Mobile and Internet of Things •  MQTT Broker (TCP + WebSocket), JMS "   Mobile engineered – very fast, reliable messaging "   Massive scale – a million connections, millions of msgs/sec "   Simple configuration – secure messaging topics and endpoints with policies 35
  37. 37. Scaling with IBM MessageSight "   1 million concurrent connections, millions of msgs/sec "   What we can do: •  RaceTracker –  Track the Boston, NYC, and Chicago marathons at the same time •  Chatterbox –  Run low-latency, secure, on-premise chat for your entire enterprise •  Starfighter –  Thousands of players can collaborate simultaneously –  Monitor and control tens of thousands of sensors 36
  38. 38. In conclusion... 37 "   WebSocket for bidirectional communication "   MQTT for efficient mobile-to-mobile publish/subscribe "   IBM MessageSight for scalability, security, and simplicity With real-time, scalable mobile messaging... what kind of compelling experiences can you create?
  39. 39. m2m.demos.ibm.com Bryan Boyd bboyd@us.ibm.com @bryanboyd Resources – m2m / IoT demos
  40. 40. References     "   Demo site: http://m2m.demos.ibm.com/ "   M2M Community https://www.ibm.com/developerworks/community/blogs/c565c720- fe84-4f63-873f-607d87787327/entry/mobile_messaging?lang=en "   Download free virtual image for Development: https://www.ibmdw.net/messaging/messagesight/ " MQTT.org: http://mqtt.org/ "   Eclipse Paho project: http://www.eclipse.org/paho/ "   IBM Messaging community: http://www.ibm.com/developerworks/connect/IBMmessaging "   IBM Messaging media: http://www.youtube.com/user/IBMmessagingMedia?feature=watch "   IBM MessageSight: http://www.ibm.com/messagesight "   IBM and Sprint Velocity Drive Connected Car Into The Future: http://www.ibm.com/press/us/en/pressrelease/41441.wss
  41. 41. Questions?
  42. 42. We Value Your Feedback "   Don’t forget to submit your Impact session and speaker feedback! Your feedback is very important to us – we use it to continually improve the conference. "   Use the Conference Mobile App or the online Agenda Builder to quickly submit your survey •  Navigate to “Surveys” to see a view of surveys for sessions you’ve attended 41
  43. 43. Thank You
  44. 44. Legal Disclaimer •  © IBM Corporation 2014. All Rights Reserved. •  The information contained in this publication is provided for informational purposes only. While efforts were made to verify the completeness and accuracy of the information contained in this publication, it is provided AS IS without warranty of any kind, express or implied. In addition, this information is based on IBM’s current product plans and strategy, which are subject to change by IBM without notice. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, this publication or any other materials. Nothing contained in this publication is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software. •  References in this presentation to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates. Product release dates and/or capabilities referenced in this presentation may change at any time at IBM’s sole discretion based on market opportunities or other factors, and are not intended to be a commitment to future product or feature availability in any way. Nothing contained in these materials is intended to, nor shall have the effect of, stating or implying that any activities undertaken by you will result in any specific sales, revenue growth or other results. •  If the text contains performance statistics or references to benchmarks, insert the following language; otherwise delete: Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any user will experience will vary depending upon many factors, including considerations such as the amount of multiprogramming in the user's job stream, the I/O configuration, the storage configuration, and the workload processed. Therefore, no assurance can be given that an individual user will achieve results similar to those stated here. •  If the text includes any customer examples, please confirm we have prior written approval from such customer and insert the following language; otherwise delete: All customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer. •  Please review text for proper trademark attribution of IBM products. At first use, each product name must be the full name and include appropriate trademark symbols (e.g., IBM Lotus® Sametime® Unyte™). Subsequent references can drop “IBM” but should include the proper branding (e.g., Lotus Sametime Gateway, or WebSphere Application Server). Please refer to http://www.ibm.com/legal/copytrade.shtml for guidance on which trademarks require the ® or ™ symbol. Do not use abbreviations for IBM product names in your presentation. All product names must be used as adjectives rather than nouns. Please list all of the trademarks that you use in your presentation as follows; delete any not included in your presentation. IBM, the IBM logo, Lotus, Lotus Notes, Notes, Domino, Quickr, Sametime, WebSphere, UC2, PartnerWorld and Lotusphere are trademarks of International Business Machines Corporation in the United States, other countries, or both. Unyte is a trademark of WebDialogs, Inc., in the United States, other countries, or both. •  If you reference Adobe® in the text, please mark the first use and include the following; otherwise delete: Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States, and/or other countries. •  If you reference Java™ in the text, please mark the first use and include the following; otherwise delete: Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. •  If you reference Microsoft® and/or Windows® in the text, please mark the first use and include the following, as applicable; otherwise delete: Microsoft and Windows are trademarks of Microsoft Corporation in the United States, other countries, or both. •  If you reference Intel® and/or any of the following Intel products in the text, please mark the first use and include those that you use as follows; otherwise delete: Intel, Intel Centrino, Celeron, Intel Xeon, Intel SpeedStep, Itanium, and Pentium are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries. •  If you reference UNIX® in the text, please mark the first use and include the following; otherwise delete: UNIX is a registered trademark of The Open Group in the United States and other countries. •  If you reference Linux® in your presentation, please mark the first use and include the following; otherwise delete: Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both. Other company, product, or service names may be trademarks or service marks of others. •  If the text/graphics include screenshots, no actual IBM employee names may be used (even your own), if your screenshots include fictitious company names (e.g., Renovations, Zeta Bank, Acme) please update and insert the following; otherwise delete: All references to [insert fictitious company name] refer to a fictitious company and are used for illustration purposes only.