#!/usr/bin/env python

# smartPlug AWOX control scanner
#
# Search AWOX smartPlug (BLE electrical plug with relay) from command line
#
# sample:
#     lefebvre@debian:~$ sudo smartplugscan
#     98:7b:f3:34:78:52, -82 dBm, SMP-B16-FR
#
# needs: bluez and python bluepy module
#
# license: MIT

from __future__ import print_function
import os
import sys
from bluepy.btle import Scanner, DefaultDelegate


class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            for (ad_type, desc, value) in dev.getScanData():
                if ad_type == 9 and value.startswith("SMP-B16-"):
                    print("%s, %d dBm, %s" % (dev.addr, dev.rssi, value))


# root is need for doing a BLE scan
if os.geteuid() != 0:
    sys.exit('BLE scan need to be run by root')

# start a BLE scan for 2s
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(2.0)

# exit with no error
sys.exit(0)
