예제 #1
0
    def __init__(self, address):
        self.requester = GATTRequester(address, False)
        self.response = GATTResponse()

        self.connect()
        self.request_data()
        self.wait_response()
예제 #2
0
    def __init__(self, address):
        self.requester = GATTRequester("40:06:A0:97:74:A9", False)
        self.response = GATTResponse()

        self.connect()
        self.request_data()
        self.wait_response()
예제 #3
0
파일: views.py 프로젝트: dwerb/blindsapi
def sendSteps(address, handle, steps, turnTime=5, timeout=9):
    global received
    delay = 0.25
    try:
        requester = Requester(address)
        t = 0.0
        time.sleep(delay)
        while not requester.is_connected() and t < timeout:
            print(t)
            t += delay
            time.sleep(delay)
        requester.write_by_handle(handle, " " + steps)
    except Exception as ex:
        print(ex)
        return {"steps": -999, "battery": -999}

    response = GATTResponse()
    requester.read_by_handle_async(handle, response)
    while not received:
        time.sleep(0.1)
    while requester.is_connected() and t < timeout:
        t += delay
        time.sleep(delay)
        requester.disconnect()
    print("DataReceived: " + dataReceived)
    battery = dataReceived.split(":")[1].split("\n")[0]
    print("Battery: " + battery)
    received = False
    return {"steps": steps, "battery": int(battery)}
예제 #4
0
    def createResponse(self, responseFunction=None):
        """Create a GATTResponse for the BLEConnectionManager.
        If a responseFunction is supplied, then the GATTResponse
        created will have an overridden on_response function.
        The responseFunction most only accept one parameter,
        which is the data contained in the response. The response
        is assigned an ID and stored in the response list.

        :param responseFunction: Function pointer called
        with a single parameter (data in response) when
        data is received. If not supplied, the GATTResponse
        function .received() can be called to access data (note: this
        function is not available if the responseFunction is specified)
        :type responseFunction: function pointer
        :return: Tuple with the response ID and response object
        :rtype: tuple (int, GATTResponse)
        """
        class BLECustomResponse(GATTResponse):
            def __init__(self, responseFunction):
                super(BLECustomResponse, self).__init__()
                self.responseFunction = responseFunction

            def on_response(self, data):
                if self.responseFunction is not None:
                    self.responseFunction(data)
        if responseFunction is not None:
            response = (self.responseCounter + 1, BLECustomResponse(responseFunction))
        else:
            response = (self.responseCounter + 1, GATTResponse())
        self.responses.append(response)
        self.responseCounter += 1
        return response
예제 #5
0
 def read_async_command(self, handle_id, length=1):
     """
     1バイトリードのときはintで、
     2バイト以上リードするときは配列で返します。
     """
     response = GATTResponse()
     handle = HANDLE[handle_id]
     self.req.read_by_handle_async(handle, response)
     while not response.received():
         time.sleep(0.1)
     ans = response.received()[0]
     ans = map(lambda n: ord(n), ans)
     if length == 1:
         return ans[0]
     else:
         return ans
예제 #6
0
    def __init__(self, address, **kwargs):
        """
        Creates a MetaWear object
        @params:
            address     - Required  : MAC address of the board to connect to e.g. E8:C9:8F:52:7B:07
            cache_path  - Optional  : Path the SDK uses for cached data, defaults to '.metawear' in the local directory
            device      - Optional  : hci device to use, defaults to 'hci0'
            deserialize - Optional  : Deserialize the cached C++ SDK state if available, defaults to true
        """
        self.info = {}

        self.address = address
        self.cache = kwargs['cache_path'] if ('cache_path'
                                              in kwargs) else ".metawear"
        self.gatt = _PyBlueZGatt(
            address, "hci0" if 'device' not in kwargs else kwargs['device'])
        self.response = GATTResponse()
        self.on_notification = self.gatt.on_notification

        self._write_fn = FnVoid_VoidP_GattCharWriteType_GattCharP_UByteP_UByte(
            self._write_gatt_char)
        self._read_fn = FnVoid_VoidP_GattCharP_FnIntVoidPtrArray(
            self._read_gatt_char)
        self._notify_fn = FnVoid_VoidP_GattCharP_FnIntVoidPtrArray_FnVoidVoidPtrInt(
            self._enable_notifications)
        self._disconnect_fn = FnVoid_VoidP_FnVoidVoidPtrInt(
            self._on_disconnect)
        self._btle_connection = BtleConnection(
            write_gatt_char=self._write_fn,
            read_gatt_char=self._read_fn,
            enable_notifications=self._notify_fn,
            on_disconnect=self._disconnect_fn)

        self.board = libmetawear.mbl_mw_metawearboard_create(
            byref(self._btle_connection))

        if 'deserialize' not in kwargs or kwargs['deserialize']:
            self.deserialize()

        try:
            os.makedirs(self.cache)
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise
예제 #7
0
    def send_data(self):
        status = True
        profile = self.requester.read_by_handle(0x61)
        time.sleep(2)
        print(profile)
        #Checks the profile loaded by the FPGA, if it's 12, then stop loop
        while ("\x0c" not in profile):
            #Attempt to set profile to 12
            try:
                self.requester.write_by_handle(0x61, str(bytearray([12])))
            except RuntimeError:
                status = False
                break
            #Delay time to allow for successful transfer
            time.sleep(2)
            print("Currently in profile loop")
            try:
                profile = self.requester.read_by_handle(0x61)
            except RuntimeError:
                status = False
                break
            time.sleep(2)
        #time.sleep(3)
        while status:
            #Write the button press to reset data
            try:
                writeResponse = GATTResponse()
                self.requester.write_by_handle_async(0x72, str(bytearray([1])),
                                                     writeResponse)
                counter = 0
                time.sleep(0.4)

                information_taken = self.requester.read_by_handle(0xa2)[0]

                counter = 0
                time.sleep(0.5)
                print("bytes received:", end=' ')
                print(int(ord(information_taken[0])))
                #first array containing value
                data = {}
                data[fields[0]] = 0
                #send to bpressure array
                data[fields[1]] = int(ord(information_taken[0]))
                params = urllib.urlencode(data)
                data = urllib.urlencode(data)
                headers = {}
                headers["Content-Type"] = 'application/x-www-form-urlencoded'
                headers["Connection"] = "close"
                headers["Content-Length"] = len(params)
                headers["Phant-Private-Key"] = private_hash

                c = httplib.HTTPConnection(base_url)
                c.request("POST", "/input/" + public_hash + ".txt", params,
                          headers)
                #send to website https://data.sparkfun.com/streams/7JYarO9dElfVn7vnlG5q
                r = c.getresponse()
                #print (r.status,r.reason)
                #time.sleep(2)
            except:
                break
        try:
            self.requester.disconnect()
        except:
            print("disconnect failed")
예제 #8
0
 def __init__(self, link):
     self.link = link
     self.resp = GATTResponse()
예제 #9
0
    def draw(canvas):
        global hit_1, hit_2
        global paddle1_pos, paddle2_pos, ball_pos, ball_vel, l_score, r_score
        global finish_flag
        global req, req1, response, response1
        global l_score_extra, r_score_extra

        canvas.fill((255, 255, 0))
        pygame.draw.line(canvas, WHITE, [WIDTH / 2, 0], [WIDTH / 2, HEIGHT], 1)
        pygame.draw.line(canvas, WHITE, [PAD_WIDTH, 0], [PAD_WIDTH, HEIGHT], 1)
        pygame.draw.line(canvas, WHITE, [WIDTH - PAD_WIDTH, 0],
                         [WIDTH - PAD_WIDTH, HEIGHT], 1)
        pygame.draw.circle(canvas, WHITE, [WIDTH // 2, HEIGHT // 2], 70, 1)

        #update ball
        ball_pos[0] += int(ball_vel[0])
        ball_pos[1] += int(ball_vel[1])

        #draw paddles and ball
        pygame.draw.circle(canvas, BLACK, ball_pos, 20, 0)

        if int(ball_pos[0]) < WIDTH / 2:
            if not req.is_connected():
                try:
                    req1.disconnect()
                except:
                    pass
                req.connect(True)
                response = GATTResponse()
                l_score_extra = 0

            req.read_by_handle_async(0x000e, response)
            if response.received():
                # print "1 works"
                print "Reading data from 1 : " + str(
                    ord(response.received()[-1]))
                hit_1 = ord(response.received()[-1])
                if hit_1 == 1:
                    l_score_extra += (ball_pos[0] * 400) / WIDTH / float(WIDTH)
                    pygame.draw.polygon(window, RED,
                                        [[
                                            paddle1_pos[0] - HALF_PAD_WIDTH,
                                            paddle1_pos[1] - HALF_PAD_HEIGHT
                                        ],
                                         [
                                             paddle1_pos[0] - HALF_PAD_WIDTH,
                                             paddle1_pos[1] + HALF_PAD_HEIGHT
                                         ],
                                         [
                                             paddle1_pos[0] + HALF_PAD_WIDTH,
                                             paddle1_pos[1] + HALF_PAD_HEIGHT
                                         ],
                                         [
                                             paddle1_pos[0] + HALF_PAD_WIDTH,
                                             paddle1_pos[1] - HALF_PAD_HEIGHT
                                         ]], 0)
# top.update_idletasks()
        else:
            if not req1.is_connected():
                try:
                    req.disconnect()
                except:
                    pass
                req1.connect(True)
                response1 = GATTResponse()
                r_score_extra = 0

            req1.read_by_handle_async(0x000e, response1)
            if response1.received():
                # print "2 works"
                print "Reading data from 2 :" + str(
                    ord(response1.received()[-1]))
                hit_2 = ord(response1.received()[-1])
                if hit_2 == 1:
                    r_score_extra += (
                        (WIDTH - ball_pos[0]) * 400) / WIDTH / float(WIDTH)
                    pygame.draw.polygon(window, RED,
                                        [[
                                            paddle2_pos[0] - HALF_PAD_WIDTH,
                                            paddle2_pos[1] - HALF_PAD_HEIGHT
                                        ],
                                         [
                                             paddle2_pos[0] - HALF_PAD_WIDTH,
                                             paddle2_pos[1] + HALF_PAD_HEIGHT
                                         ],
                                         [
                                             paddle2_pos[0] + HALF_PAD_WIDTH,
                                             paddle2_pos[1] + HALF_PAD_HEIGHT
                                         ],
                                         [
                                             paddle2_pos[0] + HALF_PAD_WIDTH,
                                             paddle2_pos[1] - HALF_PAD_HEIGHT
                                         ]], 0)
            # draw(canvas)
        #ball collision check on top and bottom walls
        if int(ball_pos[1]) <= BALL_RADIUS:
            ball_vel[1] = -ball_vel[1]
            sounds["da-ding"].play()
            # draw(canvas)
        if int(ball_pos[1]) >= HEIGHT + 1 - BALL_RADIUS:
            ball_vel[1] = -ball_vel[1]
            sounds["da-ding"].play()
            # draw(canvas)

#ball collison check on gutters or paddles
        if int(ball_pos[0]) <= 200 and hit_1 == 0:
            sounds["warn"].play()
            # draw(canvas)
        if int(ball_pos[0]) >= 1400 and hit_2 == 0:
            sounds["warn"].play()
            # draw(canvas)
        if int(ball_pos[0]) <= BALL_RADIUS + PAD_WIDTH and int(
                ball_pos[1]) in range(paddle1_pos[1] - HALF_PAD_HEIGHT,
                                      paddle1_pos[1] + HALF_PAD_HEIGHT,
                                      1) and hit_1 == 1:
            ball_vel[0] = -ball_vel[0]
            sounds["click"].play()
            l_score -= int(l_score_extra)
            l_score_extra = 0
            # draw(canvas)
        # sounds["ping"].play()
        elif int(ball_pos[0]) <= BALL_RADIUS + PAD_WIDTH:
            if not finish_flag:
                l_score -= 10
                l_score -= int(l_score_extra)
                l_score_extra = 0
            sounds["ping"].play()
            time.sleep(2)
            ball_init(True)
            # draw(canvas)
        if int(ball_pos[0]) >= WIDTH + 1 - BALL_RADIUS - PAD_WIDTH and int(
                ball_pos[1]) in range(paddle2_pos[1] - HALF_PAD_HEIGHT,
                                      paddle2_pos[1] + HALF_PAD_HEIGHT,
                                      1) and hit_2 == 1:
            ball_vel[0] = -ball_vel[0]
            sounds["click"].play()
            r_score -= int(r_score_extra)
            r_score_extra = 0
            # draw(canvas)
        elif int(ball_pos[0]) >= WIDTH + 1 - BALL_RADIUS - PAD_WIDTH:
            if not finish_flag:
                r_score -= 10
                r_score -= int(r_score_extra)
                r_score_extra = 0
            sounds["ping"].play()
            time.sleep(2)
            ball_init(False)
            # draw(canvas)
        #update scores
        myfont1 = pygame.font.SysFont(None, 48)
        myfont2 = pygame.font.SysFont(None, 48)
        if l_score > 0 and r_score > 0:
            myfont1.set_underline(1)
            label1 = myfont1.render("PLAYER1", 1, (0, 0, 0))
            myfont1.set_underline(0)
            label5 = myfont1.render(str(l_score), 1, (0, 0, 0))
            myfont2.set_underline(1)
            label2 = myfont2.render("PLAYER2", 1, (0, 0, 0))
            myfont2.set_underline(0)
            label6 = myfont2.render(str(r_score), 1, (0, 0, 0))
            canvas.blit(label1, (250, 20))
            canvas.blit(label2, (1050, 20))
            canvas.blit(label5, (290, 65))
            canvas.blit(label6, (1090, 65))
            # top.update_idletasks()
        else:
            finish_flag = 1
            if l_score > r_score:
                label1 = myfont1.render("WIN", 1, (0, 255, 0))
                label2 = myfont2.render("LOST", 1, (255, 0, 0))
                canvas.blit(label1, (250, 20))
                canvas.blit(label2, (1050, 20))
            elif r_score > l_score:
                label1 = myfont1.render("LOST", 1, (255, 0, 0))
                label2 = myfont2.render("WIN", 1, (0, 255, 0))
                canvas.blit(label1, (250, 20))
                canvas.blit(label2, (1050, 20))
            else:
                label3 = myfont1.render("MATCH DRAW", 1, (0, 0, 255))
                canvas.blit(label3, (850, 20))
예제 #10
0
파일: test.py 프로젝트: smihir/smartshoes
from __future__ import division
from gattlib import DiscoveryService
from gattlib import GATTRequester, GATTResponse
import time
import os

service = DiscoveryService("hci1")
devices = service.discover(2)
tag_address = "B0:B4:48:BF:C3:83"

for address, name in devices.items():
    print("name: {}, address: {}".format(name, address))
    if address == tag_address:
        print "cilia found"
        req = GATTRequester(tag_address, False, "hci1")
        response = GATTResponse()
        req.connect()
        req.read_by_handle_async(0x3A, response)
        while not response.received():
            time.sleep(0.1)

        steps = response.received()[0]
        #print "steps..."
        #print type(steps)
        #print steps
        #for b in steps:
        #	print hex(ord(b)),' '

        req.write_by_handle(0x3C, str(bytearray([0xff, 0xff])))
        req.write_by_handle(0x3E, str(bytearray([0x64])))
        data = req.read_by_handle(0x3C)[0]