-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
190 lines (162 loc) · 8.03 KB
/
test.py
File metadata and controls
190 lines (162 loc) · 8.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import asyncio
import logging
import struct
import csv
from bleak import discover
from bleak import BleakClient
import bleak
import time
UART_SERVICE_UUID = "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
UART_RX_CHAR_UUID = "49535343-8841-43F4-A8D4-ECBE34729BB3"
UART_TX_CHAR_UUID = "49535343-1E4D-4BD9-BA61-23C647249616"
TEST_CHAR = "49535343-4c8a-39b3-2f49-511cff073b7e"
new_address = "40:84:32:58:FB:05"
sam_address = "44:B7:D0:2D:66:FD"
#address = "B900376F-4577-CA3A-EC9E-E3836929A78A"
devices_dict = {}
devices_list = []
receive_data = []
csv_filename = "received_data" + time.ctime() + ".csv"
fmt = '<d'
received = False
#To discover BLE devices nearby
async def scan():
dev = await discover()
for i in range(0,len(dev)):
#Print the devices discovered
print("[" + str(i) + "]" + dev[i].address,dev[i].name,dev[i].metadata["uuids"])
#Put devices information into list
devices_dict[dev[i].address] = []
devices_dict[dev[i].address].append(dev[i].name)
devices_dict[dev[i].address].append(dev[i].metadata["uuids"])
devices_list.append(dev[i].address)
def split_into_chunks(byte_array, chunk_size):
return [byte_array[i:i+chunk_size] for i in range(0, len(byte_array), chunk_size)]
#An easy notify function, just print the recieve data
def notification_handler(sender, data):
received = True
#print(data)
print(', '.join('{:02x}'.format(x) for x in data))
#csv_writer.writerow((', '.join('{:02x}'.format(x) for x in data)))
with open(csv_filename, mode='a', newline='') as csv_file:
csv_writer = csv.writer(csv_file)
for x in split_into_chunks(data, 4):
original_values = [str(y) for y in x]
# print(original_values)
hex_string = ''.join('{:02x}'.format(y) for y in x)
# print(hex_string)
hex_bytes = bytes.fromhex(hex_string)
decimal_value = struct.unpack('f', hex_bytes)[0]
# print(decimal_value)
csv_writer.writerow([decimal_value, hex_bytes])
# print("x: " + str(x))
# print(struct.unpack('f', x))
# print(type(data))
# print("receving")
# st_bytes = data.decode('ascii')
# print(int.from_bytes(data, byteorder="little", signed=True))
# print(data)
# print(st_bytes)
async def run(address, debug=False):
log = logging.getLogger(__name__)
if debug:
import sys
log.setLevel(logging.DEBUG)
h = logging.StreamHandler(sys.stdout)
h.setLevel(logging.DEBUG)
log.addHandler(h)
async with BleakClient(address) as client:
x = await client.is_connected()
log.info("Connected: {0}".format(x))
for service in client.services:
log.info("[Service] {0}: {1}".format(service.uuid, service.description))
for char in service.characteristics:
if "read" in char.properties:
try:
value = bytes(await client.read_gatt_char(char.uuid))
except Exception as e:
value = str(e).encode()
else:
value = None
log.info(
"\t[Characteristic] {0}: (Handle: {1}) ({2}) | Name: {3}, Value: {4} ".format(
char.uuid,
char.handle,
",".join(char.properties),
char.description,
value,
)
)
# for descriptor in char.descriptors:
# value = await client.read_gatt_descriptor(descriptor.handle)
# log.info(
# "\t\t[Descriptor] {0}: (Handle: {1}) | Value: {2} ".format(
# descriptor.uuid, descriptor.handle, bytes(value)
# )
# )
#Characteristic uuid
CHARACTERISTIC_UUID = UART_TX_CHAR_UUID
try:
print("awakening . . .")
# while True:
while (received == False):
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
# await client.write_gatt_char(UART_RX_CHAR_UUID, data="iiiiiiiiii".encode(), response=None)
# await client.write_gatt_char(UART_RX_CHAR_UUID, data="iiiiiiiiii".encode(), response=None)
# await client.write_gatt_char(UART_RX_CHAR_UUID, data="iiiiiiiiii".encode(), response=None)
# await client.write_gatt_char(UART_RX_CHAR_UUID, data="iiiiiiiiii".encode(), response=None)
await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
# await client.write_gatt_char(CHARACTERISTIC_UUID, input().encode(), response=True)
await asyncio.sleep(0.5) # Sleeping just to make sure the response is not missed...
await client.stop_notify(CHARACTERISTIC_UUID)
while True:
try:
# await client.write_gatt_char(UART_RX_CHAR_UUID, data="iiiiiiiiii".encode(), response=None)
print("receiving . . .")
# Notify the data from the device
# await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
# await asyncio.sleep(5.0)
# await client.stop_notify(CHARACTERISTIC_UUID)
# print("send")
# await client.write_gatt_char(UART_RX_CHAR_UUID, data="aa55332211".encode(), response=None)
await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
# await client.write_gatt_char(CHARACTERISTIC_UUID, input().encode(), response=True)
await asyncio.sleep(0.5) # Sleeping just to make sure the response is not missed...
await client.stop_notify(CHARACTERISTIC_UUID)
except KeyboardInterrupt:
print("sleeping ... ")
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
except KeyboardInterrupt:
print("Exiting...")
# ... ")
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
await client.write_gatt_char(UART_RX_CHAR_UUID, data="cccccccccc".encode(), response=None)
if __name__ == "__main__":
print("Connecting to Bluetooth module...")
# # Build an event loop
# loop = asyncio.get_event_loop()
# # Run the discover event
# loop.run_until_complete(scan())
# # let user chose the device
# index = input('please select device from 0 to ' + str(len(devices_list)) + ":")
# index = int(index)
# address = devices_list[index]
# print("Address is " + address)
# # Run notify event
# loop = asyncio.get_event_loop()
# loop.set_debug(True)
# loop.run_until_complete(run(address, True))
try:
asyncio.run(run(sam_address, True))
except(bleak.exc.BleakDeviceNotFoundError):
print("Device not found. Are you sure it's on?")
csv_file.close()