Small subset of IoT device types and applications |
---|
activity trackers—Apple Watch, FitBit, … |
personal assistants—Amazon Echo (Alexa), Apple HomePod (Siri), Google Home (Google Assistant) |
appliances—ovens, coffee makers, refrigerators, … |
driverless cars |
earthquake sensors |
healthcare—blood glucose monitors for diabetics, blood pressure monitors, electrocardiograms (EKG/ECG), electroencephalograms (EEG), heart monitors, ingestible sensors, pacemakers, sleep trackers, … |
sensors—chemical, gas, GPS, humidity, light, motion, pressure, temperature, … |
smart home—lights, garage openers, video cameras, doorbells, irrigation controllers, security devices, smart locks, smart plugs, smoke detectors, thermostats, air vents |
tracking devices |
wireless network devices |
Sensor Dashboard
in the enter a name field, then click the Create New button to create a dashboard.Humidity
for the TITLE, then click SAVE. %
, then click SAVE.Math.round
to round the humidity value to the closest integer."Math.round("
before the text in the VALUE field and ")"
after the text, then click SAVE
.+
button, then selecting Sparkline from the TYPE drop-down list.Millirads/Hour
for the UNITS and 400
for the MAXIMUM.Celsius
for the UNITS and 50
for the MAXIMUM. dweet.io
to publish periodic JSON messages—called dweets (like a tweet from a device)freeboard.io
to create a dashboardpip install dweepy
simulator.py
Script¶simulator.py
simulates our thermostat
ipython simulator.py 1000 1
dweet.io
site at dweet.io
is a public service, so any app can publish or subscribe to messages'temperature-simulator-deitel-python'
dweepy
’s dweet_for
function to send a dweet, dweet.io
creates the device name# simulator.py
"""A connected thermostat simulator that publishes JSON
messages to dweet.io"""
import dweepy
import sys
import time
import random
MIN_CELSIUS_TEMP = -25
MAX_CELSIUS_TEMP = 45
MAX_TEMP_CHANGE = 2
# get the number of messages to simulate and delay between them
NUMBER_OF_MESSAGES = int(sys.argv[1])
MESSAGE_DELAY = int(sys.argv[2])
dweeter = 'temperature-simulator-deitel-python' # provide a unique name
thermostat = {'Location': 'Boston, MA, USA',
'Temperature': 20,
'LowTempWarning': False,
'HighTempWarning': False}
print('Temperature simulator starting')
for message in range(NUMBER_OF_MESSAGES):
# generate a random number in the range -MAX_TEMP_CHANGE
# through MAX_TEMP_CHANGE and add it to the current temperature
thermostat['Temperature'] += random.randrange(
-MAX_TEMP_CHANGE, MAX_TEMP_CHANGE + 1)
# ensure that the temperature stays within range
if thermostat['Temperature'] < MIN_CELSIUS_TEMP:
thermostat['Temperature'] = MIN_CELSIUS_TEMP
if thermostat['Temperature'] > MAX_CELSIUS_TEMP:
thermostat['Temperature'] = MAX_CELSIUS_TEMP
# check for low temperature warning
if thermostat['Temperature'] < 3:
thermostat['LowTempWarning'] = True
else:
thermostat['LowTempWarning'] = False
# check for high temperature warning
if thermostat['Temperature'] > 35:
thermostat['HighTempWarning'] = True
else:
thermostat['HighTempWarning'] = False
# send the dweet to dweet.io via dweepy
print(f'Messages sent: {message + 1}\r', end='')
dweepy.dweet_for(dweeter, thermostat)
time.sleep(MESSAGE_DELAY)
print('Temperature simulator finished')
Dashboard contains:
pubnub
module for performing pub/sub operationspip install "pubnub>=4.1.2"
stocklistener.py
subscribes to the stream and visualizes the stock prices'bid_price'
, 'order_quantity'
, 'symbol'
, 'timestamp'
and 'trade_type'
'bid_price'
and 'symbol'
# stocklistener.py
"""Visualizing a PubNub live stream."""
from matplotlib import animation
import matplotlib.pyplot as plt
import pandas as pd
import random
import seaborn as sns
import sys
from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
DataFrame
companies_df
stores each company’s last pricecompanies = ['Apple', 'Bespin Gas', 'Elerium', 'Google', 'Linen Cloth']
# DataFrame to store last stock prices
companies_df = pd.DataFrame(
{'company': companies, 'price' : [0, 0, 0, 0, 0]})
SensorSubscriberCallback
¶SubscribeCallback
(module pubnub.callbacks
)status
— called by PubNub client each time a status notification arrivesmessage
— called when a message arrives from the channelclass SensorSubscriberCallback(SubscribeCallback):
"""SensorSubscriberCallback receives messages from PubNub."""
def __init__(self, df, limit=1000):
"""Create instance variables for tracking number of tweets."""
self.df = df # DataFrame to store last stock prices
self.order_count = 0
self.MAX_ORDERS = limit # 1000 by default
super().__init__() # call superclass's init
def status(self, pubnub, status):
if status.category == PNStatusCategory.PNConnectedCategory:
print('Connected to PubNub')
elif status.category == PNStatusCategory.PNAcknowledgmentCategory:
print('Disconnected from PubNub')
def message(self, pubnub, message):
symbol = message.message['symbol']
bid_price = message.message['bid_price']
print(symbol, bid_price)
self.df.at[companies.index(symbol), 'price'] = bid_price
self.order_count += 1
# if MAX_ORDERS is reached, unsubscribe from PubNub channel
if self.order_count == self.MAX_ORDERS:
pubnub.unsubscribe_all()
update
Visualizes the Stock Prices¶def update(frame_number):
"""Configures bar plot contents for each animation frame."""
plt.cla() # clear old barplot
axes = sns.barplot(
data=companies_df, x='company', y='price', palette='cool')
axes.set(xlabel='Company', ylabel='Price')
plt.tight_layout()
if __name__ == '__main__':
sns.set_style('whitegrid') # white background with gray grid lines
figure = plt.figure('Stock Prices') # Figure for animation
show
method normally blocks a script from continuing until you close the Figure
block=False
allows execution to continue FuncAnimation
, see my Python Fundamentals LiveLessons videos (two videos) and in Python for Programmers, Section 6.4# configure and start animation that calls function update
stock_animation = animation.FuncAnimation(
figure, update, repeat=False, interval=33)
plt.show(block=False) # display window
SensorSubscriberCallback
object is passed to the PubNub
client’s add_listener
method to register it to receive messages from the channel# set up pubnub-market-orders sensor stream key
config = PNConfiguration()
config.subscribe_key = 'sub-c-4377ab04-f100-11e3-bffd-02ee2ddab7fe'
# create PubNub client and register a SubscribeCallback
pubnub = PubNub(config)
pubnub.add_listener(
SensorSubscriberCallback(df=companies_df,
limit=int(sys.argv[1] if len(sys.argv) > 1 else 1000))
'pubnub-market-orders'
execute()
tells client to begin listening for messages# subscribe to pubnub-sensor-network channel and begin streaming
pubnub.subscribe().channels('pubnub-market-orders').execute()
plt.show() # keeps graph on screen until you dismiss its window
©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.