import os
import time
import sys

temp = os.open('/home/root/bt_test.log',os.O_RDWR|os.O_CREAT)
os.dup2(temp,sys.stderr.fileno())
os.dup2(temp,sys.stdout.fileno())


os.popen('echo 102 > /sys/class/gpio/export').readline()
os.popen('echo out > /sys/class/gpio/gpio102/direction').readline()

result={'succeed':0,'failed':0}
os.popen('killall hciattach').readline()
while True:
    time.sleep(0.2)
    os.popen('echo 0 > /sys/class/gpio/gpio102/value').readline()
    time.sleep(0.2)
    os.popen('echo 1 > /sys/class/gpio/gpio102/value').readline()
    time.sleep(0.2)
    res = os.popen('hciattach /dev/ttyS1 texas').readline()
    if len(res)==22:
        result['succeed'] = result['succeed']+1
        time.sleep(0.2)
        os.popen('killall hciattach').readline()
        print(res)
    else:
        result['failed'] = result['failed']+1
        print(res)
        print('retry')
        res = os.popen('hciattach /dev/ttyS1 texas').readline()
        print(res)
    print(result)