# -*- coding:utf-8 -*-
import subprocess
import fcntl, os
import time
import select
import re
import sys

pipe = subprocess.Popen("btmgmt", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

flags = fcntl.fcntl(pipe.stdout, fcntl.F_GETFL)
fcntl.fcntl(pipe.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)

# pipe.stdin.write("")
# pipe.stdin.flush()
last_check = int(time.time())
last_clear = last_check
poll = select.epoll()
poll.register(pipe.stdout.fileno())
while True:
    epoll_list = poll.poll(30000)
    now_check = int(time.time())
    if now_check < last_check:
        last_check = now_check
        last_clear = now_check
    elif (now_check - last_check) >= 60:
        last_check = now_check
        if (now_check - last_clear) >= 21600:
            last_clear = now_check
            os.system("cd / ; exec lua /app/bluetooth/hci_monitor.lua clear")
        else:
            os.system("cd / ; exec lua /app/bluetooth/hci_monitor.lua")
    for fd, events in epoll_list:
        if fd == pipe.stdout.fileno() and select.EPOLLIN & events:
            if sys.version_info < (3, 4):
                out = pipe.stdout.read()
            else:
                out = pipe.stdout.read().decode()
            print(out)
            if "connect failed (status 0x0a, Busy)" in out:
                hci_dev = re.search(r"(hci[0-9])",out).group()
                cmd = "hciconfig " + hci_dev + " down; " + "hciconfig " + hci_dev + " up"
                os.system(cmd)
                cmd = "logger -t BLE-SUP reset the " + hci_dev + out
                os.system(cmd)
            elif "status 0x03" in out:
                hci_dev = re.search(r"(hci[0-9])",out).group()
                cmd = "hciconfig " + hci_dev + " down; " + "hciconfig " + hci_dev + " up"
                os.system(cmd)
                cmd = "logger -t BLE-SUP reset the " + hci_dev + out
                os.system(cmd)
