Examples

The following examples are available to download from here

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.
"""
from smartgadget import connect, milliseconds_to_datetime

# The MAC address of the Smart Gadget you want to download the data from
mac_address = 'ef:ce:43:b4:83:f8'

# 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.
rpi.connect_gadget(mac_address)

# 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...')
temperatures, humidities = rpi.fetch_logged_data(mac_address, enable_humidity=False)
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', mode='wt') 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
from smartgadget import SHT3XService

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

# The MAC address of the Smart Gadget you want to download the data from
mac_address = 'ef:ce:43:b4:83:f8'

# 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
s.disconnect_gadgets()

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

with open('humidity.csv', mode='wt') 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
from smartgadget import connect

# 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
mac_addresses = rpi.scan()

# 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
# previously-configured Smart Gadget.
rpi.connect_gadgets(mac_addresses)
print('Connected to: {}'.format(rpi.connected_gadgets()))

# Set the logger interval to be 10 seconds (10000 milliseconds)
t0 = perf_counter()
for address in mac_addresses:
    print('Setting the logger interval for {!r}'.format(address))
    rpi.set_logger_interval(address, 10000)
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
available Smart Gadgets to separate CSV files. The MAC address of a Smart Gadget
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

from smartgadget import connect, kill_manager

# 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)
rpi_password = '<PASSWORD>'

# 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
mac_addresses = []

# 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...')
            rpi = connect(host=host, rpi_password=rpi_password, assert_hostname=False)
            print('Scanning for Smart Gadgets...')
            mac_addresses = rpi.scan()
            print('Found {} Smart Gadgets'.format(len(mac_addresses)))
            if not mac_addresses:
                break
            print('Connecting to {} Smart Gadgets...'.format(len(mac_addresses)))
            rpi.connect_gadgets(mac_addresses)
            for address in mac_addresses:
                files[address] = os.path.join(save_dir, address.replace(':', '-') + '.csv')
                if not os.path.isfile(files[address]):
                    print('Create logging file {!r}'.format(files[address]))
                    with open(files[address], mode='wt') as f:
                        f.write('Timestamp,Battery[%],Temperature[C],Humidity[%RH],Dewpoint[C]\n')

        for address in mac_addresses:
            # Fetch the data and append to the appropriate file
            battery = rpi.battery(address)
            values = rpi.temperature_humidity_dewpoint(address)
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print('{} [{}] {:3d} {:.3f} {:.3f} {:.3f}'.format(now, address, battery, *values))
            with open(files[address], mode='at') as fp:
                fp.write('{},{},{},{},{}\n'.format(now, battery, *values))

        time.sleep(sleep)

    except KeyboardInterrupt:
        print('CTRL+C received...')
        break

    except Exception as e:
        rpi = None
        msg = str(e).splitlines()[-1]
        print(msg)
        if msg.endswith('address already in use'):
            print('Killing the Network Manager...')
            kill_manager(host=host, rpi_password=rpi_password)

# 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')