#! /usr/bin/python


#####################################
#                                   #
##################################### 
from bluepy.btle import Scanner, DefaultDelegate
from bluepy.btle import Peripheral, UUID
import sys

#################################
# List of Known UUIDs           #
################################# 
uuid = [ '59c88760-5364-11e7-b114-b2f933d5fe66',  # UUID0
         '59c889e0-5364-11e7-b114-b2f933d5fe66',  # UUID1
         '59c88d6e-5364-11e7-b114-b2f933d5fe66']  # UUID2

###################################
# BLE Target                      #
###################################
ble_module_name = "DRAGONWALLY"
ble_target_uuid = uuid[2]   # UUID2
ble_target_value = [int(str(sys.argv[1]),16)] if (len(sys.argv)==2) else [0x00]

#############################
# convert a Vetor to String #
#############################
def makestring(bytes):
    return "".join(map(chr,bytes))

#################
# Scan Delegate #
#################
class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr

################
# Scan Devices #
################
print("[SCAN DEVICES]")
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(10.0)
mydevice = None

###################
# Analyze Devices #
###################
print("[ANALYZE DEVICES NAMES]")
for dev in devices:
    print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
    for (adtype, desc, value) in dev.getScanData():
        #############################
        # print Complete Local Name #
        #############################
        if (desc == "Complete Local Name"):
        	print "  %s = %s" % (desc, value)
        ##################################
        # find target device by its name #
        ##################################
	if (desc == "Complete Local Name") and (value == ble_module_name) :
		mydevice = dev
		print "[Device %s found as %s]" % (mydevice.addr,value)

###########################
# Target Device was Found #
###########################
if mydevice is not None:
     ##########################
     # Open Peripheral and    #
     # Search Services        #
     ##########################
     p = Peripheral(mydevice.addr,mydevice.addrType)
     print "Get Services ..."
     services = p.getServices()
     print "Done."
     ##########################
     # Analyze Services       #
     ########################## 
     for serv in services:
	print "Peripheral Addr=%s , UUID=%s" % (serv.peripheral.addr,serv.uuid)
	characteristics = serv.getCharacteristics()
	for ch in characteristics:
	   print "   UUID=%s , Properties=%s , Value=%s" % (UUID(ch.uuid).getCommonName(),ch.propertiesToString(),ch.read() if ch.supportsRead() else "-")
           ############################################
           # Write Value of the Target Characteristic #
           ############################################
           if (UUID(ch.uuid).getCommonName() == ble_target_uuid):
	       ch.write(makestring(ble_target_value))
	       print("[Writing Value to Target UUID]") 


