def __init__(self, legacy_port=False, poll_frequency = 1, scan_timeout=4, address_timeout=20, whitelist_path=''):
        self.legacy_port = legacy_port
        self.poll_frequency = poll_frequency #seconds
        self.scan_timeout = scan_timeout #seconds
       	self.address_timeout = address_timeout #seconds; time, after which a detected mac address is considered 'stale'

        full_path = whitelist_path
        if whitelist_path == '':
            package_directory = os.path.dirname(os.path.abspath(__file__))
            full_path = package_directory+"/config/whitelist.yaml"
        try:
            self.mac_whitelist = self._load_yaml(full_path)
        except:
            print("Could not load whitelist yaml file.")
            exit(-1)

        self._setup_args()
        self.run_thread = threading.Thread(target=self._run,)

        self.clients = [] #who we're serving
        self.servers = [] #who we're connected to
        self.serial_clients = dict()
        self.serial_servers = dict()

        self.stale_sockets = dict() #sockets that have not been seen in self.address_timeout seconds
        self.available_devices = dict() #BLE scan results and the last time they were seen
        self.available_devices_lock = threading.Lock()
        self.shutdown = False

        self.my_mac = bluetooth.read_local_bdaddr()[0]
        self.my_nice = self.mac_whitelist[self.my_mac]['nice']
        self.le_devices = []
        self.std_devices = []
Beispiel #2
0
 def __init__(self, server_ble_addr, server_port):
     super().__init__()
     bdaddr = bluetooth.read_local_bdaddr()
     print("Địa chỉ BLE máy khách:", bdaddr[0])
     self.server_ble_addr = server_ble_addr
     self.server_port = server_port
     self.client = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
Beispiel #3
0
def callback(bt_addr, rssi, packet, additional_info):
    print(f"sending RSSI: {rssi}")
    output = json.dumps({
        'tool_id': f"{additional_info['major']}.{additional_info['minor']}",
        'recv_bd_addr': bluetooth.read_local_bdaddr(),
        'rssi': rssi
    })
    asyncio.run(post(output))
Beispiel #4
0
def findHostMAC():
    global hostMACAddress
    name = bluetooth.read_local_bdaddr()
    print("Host: %s" % name[0])
    if name[0] == "B8:27:EB:1A:E0:6F":
        print("Nicke")
        hostMACAddress = "B8:27:EB:1A:E0:6F"
    else:
        print("Jesus")
        hostMACAddress = "B8:27:EB:A6:9E:7E"
Beispiel #5
0
def sync_this_device_Bluetooth():
    server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    binded = False
    try:
        #print(bluetooth.PORT_ANY)
        #server_sock.bind((bluetooth.read_local_bdaddr()[0], bluetooth.PORT_ANY))
        server_sock.bind((bluetooth.read_local_bdaddr()[0], 10))
        binded = True
    except OSError as err:
        print("Une erreur est survenue lors de la phase de bind, OSError: {0}".format(err))
    except SystemError as err:
        print("Une erreur est survenue lors de la phase de bind SystemError: {0}".format(err))

    if binded:

        server_sock.listen(1)

        port = server_sock.getsockname()[1]

        uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

        bluetooth.advertise_service(server_sock, "SampleServer", service_id=uuid,
                                    service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
                                    profiles=[bluetooth.SERIAL_PORT_PROFILE],
                                    # protocols=[bluetooth.OBEX_UUID]
                                    )

        print("En attente du serveur... sur le port Ox10")

        client_sock, client_info = server_sock.accept()
        print("Connexion acceptée de", client_info)

        # Erase the old content in the password file
        #file = open("passwords_chiffres.txt", "wb", errors='ignore')
        #file.close()

        try:
            while True:
                data = client_sock.recv(1024)
                if not data:
                    break
                print("Reçu", data)
                mdp_file = open("passwords_chiffres.txt", "wb")
                mdp_file.write(data)
                mdp_file.close()
        except OSError as err:
            print("Une erreur est survenue lors de la phase de réception, OSError: {0}".format(err))
        except TypeError as err:
            print("Une erreur est survenue lors de la phase de réception, TypeError: {0}".format(err))
        print("Déconnecté.")

        client_sock.close()
        server_sock.close()
        print("Fini.")
Beispiel #6
0
    def worker(self):
        '''
        Worker method for bluetooth socket

        No Return Value
        '''
        if 'socketproto' in self.config.keys():
            socketproto = eval('bluetooth.' + self.config['socketproto'])
        else:
            socketproto = bluetooth.RFCOMM


        if 'localaddr' in self.config.keys():
            localaddr = self.config['localaddr']
        else:
            localaddr = bluetooth.read_local_bdaddr()[0]

        if 'port' in self.config.keys():
            port = eval('bluetooth.' + self.config['port'])
        else:
            port = bluetooth.PORT_ANY

        if 'servicename' in self.config.keys():
            servicename = self.config['servicename']
        else:
            servicename = self.config['name']

        btsocket = bluetooth.BluetoothSocket(proto=socketproto)
        btsocket.bind((localaddr, port))

        btsocket.listen(1)

        bluetooth.advertise_service(btsocket, servicename,
                service_classes=[bluetooth.SERIAL_PORT_CLASS],
                profiles=[bluetooth.SERIAL_PORT_PROFILE])

        while True:
            clientsocket, clientaddress = btsocket.accept()

            data = bytes()
            while True:
                try:
                    data += clientsocket.recv(131072)
                except:
                    break

            clientsocket.close()

            self.queue.put(data)
Beispiel #7
0
    def __init__(self, config, control_service, logger):
        self.logger = logger
        self.config = config
        self.is_monitoring = False
        self.control_service = control_service

        if self.config.debug:
            self.logger.log(self.TAG, "BluetoothService instantiated")
            self.logger.log(
                self.TAG, "This device: " + str(bluetooth.read_local_bdaddr()))
        self.gamepad = InputDevice(self.config.input_device)
        if self.config.debug:
            self.logger.log(self.TAG, "Gamepad: " + str(self.gamepad))

        self.thread = threading.Thread(target=self.start_monitoring)
        self.thread.start()
Beispiel #8
0
def WaitForClient():
    hostMACAddress = "B8:27:EB:A6:9E:7E"  #Jesus
    #hostMACAddress = "B8:27:EB:AB:1C:2B" #Josh
    #hostMACAddress = "B8:27:EB:1A:E0:6F" #Nicke
    #hostMACAddress = ""
    subprocess.call(['sudo', 'hciconfig', 'hci0', 'piscan'])
    port = 4
    backlog = 10
    size = 1024
    s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    name = bluetooth.read_local_bdaddr()
    print("Host: %s" % name[0])
    if name[0] == "B8:27:EB:1A:E0:6F":
        print("Nicke")
        hostMACAddress = "B8:27:EB:1A:E0:6F"
    else:
        print("Jesus")
        hostMACAddress = "B8:27:EB:A6:9E:7E"
    s.bind((hostMACAddress, port))
    print("Listening")
    s.listen(backlog)
    try:
        client, clientInfo = s.accept()
        while 1:
            print("Connected", clientInfo)
            #threading.Thread(target=recv, daemon=True).start()
            #
            client.send("You are connected")
            data = client.recv(size)
            if not data:
                print("Wrong Data %s" % data)
            print("received: %s" % data)
    except:
        print("Closing socket")
        #client.close()
        s.close()
Beispiel #9
0
#http://people.csail.mit.edu/albert/bluez-intro/c212.html#findmyphone.py
import bluetooth

target_name = "lwy2010"
target_address = None

local_addr = bluetooth.read_local_bdaddr()
print(f"local_addr{local_addr}")

nearby_devices = bluetooth.discover_devices()  # scan time about 10s

#services= bluetooth.find_service()
#print(services)

for bdaddr in nearby_devices:
    name = bluetooth.lookup_name(
        bdaddr
    )  # and lookup_name() will sometimes return None to indicate that it couldn't determine the user-friendly name of the detected device
    print(f"{bdaddr} : {name}")
    if target_name == name:
        target_address = bdaddr
        break

if target_address is not None:
    print(
        f"found target bluetooth device name {target_name} with address {target_address}"
    )
else:
    print(f"could not find target bluetooth device nearby")
Beispiel #10
0
 def setup(self):
     """Check if Bluetooth Adapter is available"""
     try:
         bluetooth.read_local_bdaddr()
     except bluetooth.BluetoothError:
         raise BackendError("No Bluetooth Receiver available")
class BTKbDevice():
    # change these constants
    MY_ADDRESS = bluetooth.read_local_bdaddr()[0]
    MY_DEV_NAME = "ThanhLe_Keyboard_Mouse"

    # define some constants
    P_CTRL = 17  # Service port - must match port configured in SDP record
    P_INTR = 19  # Interrupt port - must match port configured in SDP record
    # dbus path of the bluez profile we will create
    # file path of the sdp record to load
    SDP_RECORD_PATH = sys.path[0] + "/sdp_record.xml"
    UUID = "00001124-0000-1000-8000-00805f9b34fb"

    def __init__(self):
        print("2. Setting up BT device")
        self.init_bt_device()
        self.init_bluez_profile()

    # configure the bluetooth hardware device
    def init_bt_device(self):
        print("3. Configuring Device name " + BTKbDevice.MY_DEV_NAME)
        # set the device class to a keybord and set the name
        os.system("hciconfig hci0 up")
        os.system("hciconfig hci0 name " + BTKbDevice.MY_DEV_NAME)
        # make the device discoverable
        os.system("hciconfig hci0 piscan")

    # set up a bluez profile to advertise device capabilities from a loaded service record
    def init_bluez_profile(self):
        print("4. Configuring Bluez Profile")
        # setup profile options
        service_record = self.read_sdp_service_record()
        opts = {"AutoConnect": True, "ServiceRecord": service_record}
        # retrieve a proxy for the bluez profile interface
        bus = dbus.SystemBus()
        manager = dbus.Interface(bus.get_object("org.bluez", "/org/bluez"),
                                 "org.bluez.ProfileManager1")
        manager.RegisterProfile("/org/bluez/hci0", BTKbDevice.UUID, opts)
        print("6. Profile registered ")
        os.system("hciconfig hci0 class 0x0025C0")

    # read and return an sdp record from a file
    def read_sdp_service_record(self):
        print("5. Reading service record")
        try:
            fh = open(BTKbDevice.SDP_RECORD_PATH, "r")
        except:
            sys.exit("Could not open the sdp record. Exiting...")
        return fh.read()

    # listen for incoming client connections
    def listen(self):
        print("\033[0;33m7. Waiting for connections\033[0m")
        self.scontrol = socket.socket(
            socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET,
            socket.BTPROTO_L2CAP)  # BluetoothSocket(L2CAP)
        self.sinterrupt = socket.socket(
            socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET,
            socket.BTPROTO_L2CAP)  # BluetoothSocket(L2CAP)
        self.scontrol.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sinterrupt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # bind these sockets to a port - port zero to select next available
        self.scontrol.bind((socket.BDADDR_ANY, self.P_CTRL))
        self.sinterrupt.bind((socket.BDADDR_ANY, self.P_INTR))

        # Start listening on the server sockets
        self.scontrol.listen(5)
        self.sinterrupt.listen(5)

        self.ccontrol, cinfo = self.scontrol.accept()
        print(
            "\033[0;32mGot a connection on the control channel from %s \033[0m"
            % cinfo[0])

        self.cinterrupt, cinfo = self.sinterrupt.accept()
        print(
            "\033[0;32mGot a connection on the interrupt channel from %s \033[0m"
            % cinfo[0])

    # send a string to the bluetooth host machine
    def send_string(self, message):
        try:
            self.cinterrupt.send(bytes(message))
        except OSError as err:
            error(err)
Beispiel #12
0
try:
    camera = PiCamera()
    CAMERA_ENABLED = True
except:
    CAMERA_ENABLED = False

HOSTNAME = socket.gethostname()

LOG_FILENAME = HOSTNAME + ".log"
logging.basicConfig(
    filename=LOG_FILENAME,
    level=logging.INFO,
)

# read local bluetooth addr
LOCAL_BLUETOOTH_ADDR = bluetooth.read_local_bdaddr()[0]
print("Local Bluetooth addr: ", LOCAL_BLUETOOTH_ADDR)

def remove_time_lapse_info():
    if os.path.isfile("time_lapse_info.txt"):
        os.remove("time_lapse_info.txt")
        log("time_lapse_info.txt deleted")


def date_iso():
    return datetime.datetime.now().isoformat().split(".")[0].replace("T", "_")


def log(msg):
    """
    write message to log
Beispiel #13
0
    def __init__(self, parent, *args):
        self.page = Frame(parent)
        parent.add(self.page, text="Scouting")

        # all of our output that would normally go on console will go here
        outputScrollBar = Scrollbar(self.page)
        outputScrollBar.grid(row=0, column=1, rowspan=999, sticky=NS)

        self.output = Text(self.page,
                           background="black",
                           foreground="white",
                           yscrollcommand=outputScrollBar.set)
        self.output.grid(row=0, column=0, rowspan=999)
        outputScrollBar.config(command=self.output.yview)

        global textOutput
        textOutput = self.output

        #####

        try:
            adrr = bluetooth.read_local_bdaddr()[0]
        except OSError:
            adrr = "No bluetooth address found. Maybe bluetooth isn't turned on?"

        # create qr code from address
        self.qr = createQR(adrr)

        # setup tkinter image with the qr code
        self.qrBm = BitmapImage(data=self.qr.xbm(scale=5))
        self.qrBm.config(background="white")
        Label(self.page, image=self.qrBm).grid(row=2, column=2)
        Label(self.page, text=adrr).grid(row=3, column=2)

        #####

        # start button
        global clicked
        clicked = False

        self.startButtonText = StringVar()
        self.startButtonText.set("Start")

        self.startButton = Button(self.page,
                                  textvariable=self.startButtonText,
                                  command=self.startBtnClick)

        self.startButton.grid(row=1, column=2, columnspan=2, sticky=EW)

        #####

        # verification textbox label
        Label(self.page, text="Verification:").grid(row=4, column=2)

        # textbox to set verification

        self.verificationText = StringVar()
        self.verificationText.set(verification)
        self.verificationText.trace("w", self.setVerification)
        verificationTextBox = Entry(self.page,
                                    textvariable=self.verificationText)
        verificationTextBox.grid(row=5, column=2)

        # generate excel button
        generateExcelButton = Button(self.page,
                                     text="Generate Excel",
                                     command=generateExcel)
        generateExcelButton.grid(row=6, column=2)
import bluetooth

ADDRESS = bluetooth.read_local_bdaddr()[0]
print(ADDRESS)
PORT = 3

#The backlog argument must be at least 1
#it specifies the number of unaccepted connections
#that the system will allow before refusing new connections.
BACKLOG = 1

#Receive up to buffersize bytes from the socket
SIZE = 1024

sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.bind((ADDRESS, PORT))
sock.listen(BACKLOG)
try:
    client, address = sock.accept()
    while True:
        data = client.recv(SIZE)
        print("CALLER SAYS: {}".format(data))
        client.send("TX from {} ACK".format(address[0]))
except:
    print("Closing Socket")
    client.send("GOODBYE!")
    client.close()
    sock.shutdown(2)
    sock.close()
Beispiel #15
0
    return subprocess.Popen(["display", filename])


program_files_dir = sys.argv[1]
key_size = int(sys.argv[2])

if os.path.exists(program_files_dir + 'cert') == False:
    os.mkdir(program_files_dir + 'cert')  #,745)

exchanged = False
while exchanged == False:
    print("Making the first connection")
    integrity_key = Random.new().read(key_size / 8)
    encoded_key = base64.b64encode(integrity_key)
    random_uuid = str(uuid.uuid1())
    mac = add_left_zeros(bluetooth.read_local_bdaddr()[0])
    qrcode_content = mac + random_uuid + encoded_key

    filename = "qrcode"
    p = create_qrcode(qrcode_content, filename)

    android_info = create_pc_service(random_uuid)

    h = HMAC.new(integrity_key,
                 android_info[2] + android_info[3] + android_info[4],
                 SHA512).digest()
    if android_info[1] == h:
        integrity_preserved(android_info[0])
        exchanged = True
    else:
        integrity_changed(android_info[0])
Beispiel #16
0
def bt_adr():
    try:
        adr = bluetooth.read_local_bdaddr()
        return adr[0]
    except:
        return "off"
Beispiel #17
0
 def __init__(self, server_port):
     super().__init__()
     self.server_port = server_port
     self.server = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
     self.bltaddr = bluetooth.read_local_bdaddr()
     print("Địa chỉ BLE máy chủ: ", str(self.bltaddr[0]))
Beispiel #18
0
 def get_local_address(self):
     return str(bluetooth.read_local_bdaddr())
Beispiel #19
0
#!/usr/bin/env python3
#ifdef _WIN32
#include <Winsock2.h>
#endif

import bluetooth

print("local Bluetooth device address - {}".format(
    bluetooth.read_local_bdaddr()))

print("Performing inquiry...")

nearby_devices = bluetooth.discover_devices(duration=8,
                                            lookup_names=True,
                                            flush_cache=True,
                                            lookup_class=False)

print("Found {} devices".format(len(nearby_devices)))

for addr, name in nearby_devices:
    try:
        print("   {} - {}".format(addr, name))
    except UnicodeEncodeError:
        print("   {} - {}".format(addr, name.encode("utf-8", "replace")))

print(nearby_devices)

Engineer_devices = ['9C:B6:D0:FA:B0:54', 'others']
print(Engineer_devices)

for addr, name in nearby_devices:
Beispiel #20
0
import os
import sys
import struct
import bluetooth


if __name__ == "__main__":
    bdaddr = bluetooth.read_local_bdaddr()
    print(bdaddr)