Examples¶

fetch_logged_data_remotely.py¶

"""
This example assumes that you are connecting to a Raspberry Pi from
another computer on the network to fetch the logged data.
"""

# Connect to the Raspberry Pi (update the IP address of the Raspberry Pi)
rpi = connect(host='192.168.1.100', assert_hostname=False)

# We will be picky and only allow 1 attempt to perform a Smart Gadget request.
# Increasing this value will decrease the occurrence of getting a
# BTLEDisconnectError or a BrokenPipeError when sending requests.
rpi.set_max_attempts(1)

# Connect to the Smart Gadget. This is optional, you could call
# rpi.fetch_logged_data() without first connecting to the Smart Gadget.

# Fetch all temperature logger data.
# The humidity data is also returned but it will be an emtpy list.
#
# This step can take a very long time (minutes) if there is a lot of data
# to fetch or if the Bluetooth connection is slow/keeps dropping out.
# There is no option to display the current status of the request
# -- see fetch_logged_data_rpi.py which will display status updates.
print('Fetching data...')
print('Fetched {} temperature values'.format(len(temperatures)))

# Disconnect from the Raspberry Pi when finished communicating with it
rpi.disconnect()

# Save the temperature results (the returned timestamps are in milliseconds)
with open('temperature.csv', 'w') as fp:
fp.write('timestamp,temperature[C]\n')
for timestamp, value in temperatures:
fp.write('{},{}\n'.format(milliseconds_to_datetime(timestamp), value))

fetch_logged_data_rpi.py¶

#!/home/pi/shtenv/bin/python
"""
This example assumes that you are directly running the script on a Raspberry Pi.

You must execute this script as the root user in order to have access to
the Bluetooth drivers.

First, make this script executable

$chmod +x fetch_logged_data_rpi.py Next, execute the script$ sudo ./fetch_logged_data_rpi.py

"""
import logging

# This allows you to see some status messages displayed to the terminal
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)-7s] %(message)s')

# Create an instance of the Smart Gadget Service
s = SHT3XService()

# Fetch all available temperature and humidity logger data.
# Perform this 2 times to reduce missing data packets during the Bluetooth download.
# This step can take a very long time (minutes) if there is a lot of data
# to fetch or if the Bluetooth connection is slow/keeps dropping out.
temperatures, humidities = s.fetch_logged_data(mac_address, num_iterations=2, as_datetime=True)

# Disconnect from the Smart Gadget when finished communicating with it

# Save the results
with open('temperature.csv', 'w') as fp:
fp.write('timestamp,temperature[C]\n')
for row in temperatures:
fp.write('{},{}\n'.format(*row))

with open('humidity.csv', 'w') as fp:
fp.write('timestamp,humidity[%RH]\n')
for row in humidities:
fp.write('{},{}\n'.format(*row))

set_logger_interval.py¶

"""
This script will set the logger interval for all available Smart Gadgets.

This will delete all values from the memory of each Smart Gadget so that the
timestamps for all Smart Gadgets are in sync.
"""
from time import perf_counter

# Connect to the Raspberry Pi (update the IP address of the Raspberry Pi)
rpi = connect(host='192.168.1.100', assert_hostname=False)

# Get all available Smart Gadgets

# We connect to all Smart Gadgets now so that the start time of each Smart
# Gadget logger is as close as possible to all other Smart Gadgets. Without
# first connecting to all Smart Gadgets the start time for each Smart Gadget
# would accumulate approximately a 7-second delay (the time it takes to
# connect to a Smart Gadget) compared to the start time of the

# Set the logger interval to be 10 seconds (10000 milliseconds)
t0 = perf_counter()
print('Setting the logger interval for {!r}'.format(address))
dt = perf_counter() - t0
print('All Smart Gadgets should be in sync to within {:.3f} seconds'.format(dt))

# Disconnect from the Raspberry Pi when finished communicating with it
rpi.disconnect()

custom_logging.py¶

"""
Sample script to log the battery, temperature, humidity and dew point from all
is used as the name of the file.

Sometimes the number of Smart Gadgets discovered during a Bluetooth scan is
less than the number expected. This example script does not rescan until the
expected number are found. Alternatively, if you know the MAC addresses of the
Smart Gadgets that you want to log then you could specify the MAC addresses
in a list and not perform the Bluetooth scan.
"""
import os
import time
from datetime import datetime

# The IP address of the Raspberry Pi
host = '192.168.1.100'

# The password of the Raspberry Pi (this should be read from a file or from the terminal)

# The folder to save the data to (default value is the current working directory)
save_dir = ''

# You could also specify the MAC addresses rather than performing the scan below

# The number of seconds to wait after fetching the data from all Smart Gadgets
sleep = 10

# Initialize these parameters (they don't need to be changed)
files = {}
rpi = None

while True:
try:
if rpi is None:
# Connect to the Raspberry Pi and scan for Smart Gadgets
print('Connecting to the Raspberry Pi...')
break
f.write('Timestamp,Battery[%],Temperature[C],Humidity[%RH],Dewpoint[C]\n')

# Fetch the data and append to the appropriate file
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print('{} [{}] {:3d} {:.3f} {:.3f} {:.3f}'.format(now, address, battery, *values))
fp.write('{},{},{},{},{}\n'.format(now, battery, *values))

time.sleep(sleep)

except KeyboardInterrupt:
break

except Exception as e:
rpi = None
msg = str(e).splitlines()[-1]
print(msg)
print('Killing the Network Manager...')

# Must wait for the previous request to finish before sending the disconnect request
try:
rpi.wait()
except:
pass

# Disconnect from the Raspberry Pi
try:
rpi.disconnect()
except:
pass

print('Disconnected from the Raspberry Pi')