#! /usr/bin/python
from __future__ import print_function # import print from python3: end=""
import time
import re
import subprocess
import pexpect # sudo apt-get install python-pexpect
import random
import binascii
import struct
import sys, os, time
import bluepy.btle as btle
'''
42 0x2A READ Im advertising the flag
MD5OFLOL
'''
deviceMAC = open('ctf_mac.txt').read()
p = btle.Peripheral(deviceMAC)
svc=p.getServiceByUUID(0x00FF)
print ("Attached to peripheral")
print("Loading level 09")
hex1 = binascii.unhexlify(str('%0*x' % (4,9)))
p.writeCharacteristic(0x30, hex1, withResponse=False)
p.disconnect()
print("Starting advertisement listner")
ps = subprocess.Popen(["btmon"], shell=False, stdout=subprocess.PIPE)
gp = subprocess.Popen(["grep", "Name"], shell=False, stdin=ps.stdout)
ps.stdout.close()
#output = gp.communicate()[0]
#ps.wait()
print("Please wait 5s...")
time.sleep(5)
print("Starting hcitool")
ps2 = subprocess.Popen(['hcitool', 'lescan'], shell=False)
print("Please wait 5s...")
time.sleep(5)
ps2.terminate()
ps.terminate()