import sys
from bluepy import btle
import time
import binascii

class MyDelegate(btle.DefaultDelegate):
    def __init__(self, p):
        btle.DefaultDelegate.__init__(self)
        self.p = p

    def handleNotification(self, cHandle, data):
        print("A notification %d was received: %s from mac %s" %(cHandle, binascii.b2a_hex(data), self.p.addr))

p = btle.Peripheral("A4:C1:38:43:13:2F")
p.withDelegate( MyDelegate(p) )


dev_name_uuid = btle.UUID(0x2A00)

ch = p.getCharacteristics(uuid=dev_name_uuid)[0]
if (ch.supportsRead()):
    print(ch.read())


services=p.getServices()
#displays all services
for service in services:
    print(service)


chList = p.getCharacteristics()
print("Handle   UUID                                Properties")
print("-------------------------------------------------------")
for ch in chList:
    print("  0x"+ format(ch.getHandle(),'02X')  +"   "+str(ch.uuid) +" " + ch.propertiesToString())

time.sleep(3)

ch = p.getCharacteristics(uuid="FFF2")[0]
print(ch.valHandle)

if sys.version_info < (3, 0):
    a = binascii.a2b_hex("CC80020301010001")
else:
    data_list = [0xCC, 0x80, 0x02, 0x03, 0x01, 0x01, 0x00, 0x01]
    a = bytes(data_list)

ch.write(a)
time.sleep(1)

data_list = [0xCC, 0x80, 0x02, 0x03, 0x01, 0x02, 0x00, 0x02]
ch.write("CC80020301020002")

if sys.version_info < (3, 0):
    a = binascii.a2b_hex("CC80020301020002")
else:
    data_list = [0xCC, 0x80, 0x02, 0x03, 0x01, 0x02, 0x00, 0x02]
    a = bytes(data_list)

ch.write(a)
time.sleep(1)

while True:
    try:
        if p.waitForNotifications(5.0):
            # handleNotification() was called
            continue
    except btle.BTLEDisconnectError:
        print("reconnect")
        flag = 0
    except Exception,err:
        print(err)

    if flag == 0:
        try:
            p.connect("A4:C1:38:43:13:2F")
        except btle.BTLEDisconnectError:
            print("connect failed")
        else:
            print("connect successfully", p.getState())
            flag = 1
    print("Waiting...")
    # Perhaps do something else here
