| 93 | return pack_adv_service(_UART_UUID) |
| 94 | |
| 95 | class BLEUART: |
| 96 | def __init__(self, ble, name="mpy-uart", rxbuf=100): |
| 97 | name = name[:16] |
| 98 | self._ble = ble |
| 99 | if not self._ble.active(): self._ble.active(True) |
| 100 | self._ble.irq(self.irq_handler) |
| 101 | ((self._tx_handle, self._rx_handle),) = self._ble.gatts_register_services((_UART_SERVICE,)) |
| 102 | # Increase the size of the rx buffer and enable append mode. |
| 103 | self._ble.gatts_set_buffer(self._rx_handle, rxbuf, True) |
| 104 | self._connections = set() |
| 105 | self._rx_buffer = bytearray() |
| 106 | self._handler = None |
| 107 | self._payload = gen_advertising_payload(name=name) |
| 108 | self._resp = gen_resp_payload() |
| 109 | self._advertise() |
| 110 | |
| 111 | def set_callback(self, handler): |
| 112 | self._handler = handler |
| 113 | |
| 114 | def irq_handler(self, event, data): |
| 115 | # Track connections so we can send notifications. |
| 116 | if event == _IRQ_CENTRAL_CONNECT: |
| 117 | conn_handle, _, _ = data |
| 118 | self._connections.add(conn_handle) |
| 119 | elif event == _IRQ_CENTRAL_DISCONNECT: |
| 120 | conn_handle, _, _ = data |
| 121 | if conn_handle in self._connections: |
| 122 | self._connections.remove(conn_handle) |
| 123 | # Start advertising again to allow a new connection. |
| 124 | self._advertise() |
| 125 | elif event == _IRQ_GATTS_WRITE: |
| 126 | conn_handle, value_handle = data |
| 127 | if conn_handle in self._connections and value_handle == self._rx_handle: |
| 128 | self._rx_buffer += self._ble.gatts_read(self._rx_handle) |
| 129 | if self._handler: |
| 130 | self._handler() |
| 131 | |
| 132 | def any(self): |
| 133 | return len(self._rx_buffer) |
| 134 | |
| 135 | def read(self, sz=None): |
| 136 | if not sz: |
| 137 | sz = len(self._rx_buffer) |
| 138 | result = self._rx_buffer[0:sz] |
| 139 | self._rx_buffer = self._rx_buffer[sz:] |
| 140 | return result |
| 141 | |
| 142 | def write(self, data): |
| 143 | for conn_handle in self._connections: |
| 144 | self._ble.gatts_notify(conn_handle, self._tx_handle, data) |
| 145 | |
| 146 | # Like write() but adds a newline at the end. |
| 147 | def print(self, value): |
| 148 | self.write(str(value)+"\n") |
| 149 | |
| 150 | def close(self): |
| 151 | for conn_handle in self._connections: |
| 152 | self._ble.gap_disconnect(conn_handle) |