@@ -8,10 +8,12 @@ import (
88
99const maxConnections = 1
1010
11- // Adapter represents the UART connection to the HCI controller.
11+ // Adapter represents a "plain" UART connection to the HCI controller.
1212type Adapter struct {
1313 hciAdapter
1414
15+ uart * machine.UART
16+
1517 // used for software flow control
1618 cts , rts machine.Pin
1719}
@@ -20,11 +22,13 @@ type Adapter struct {
2022//
2123// Make sure to call Enable() before using it to initialize the adapter.
2224var DefaultAdapter = & Adapter {
23- isDefault : true ,
24- connectHandler : func (device Device , connected bool ) {
25- return
25+ hciAdapter : hciAdapter {
26+ isDefault : true ,
27+ connectHandler : func (device Device , connected bool ) {
28+ return
29+ },
30+ connectedDevices : make ([]Device , 0 , maxConnections ),
2631 },
27- connectedDevices : make ([]Device , 0 , maxConnections ),
2832}
2933
3034// SetUART sets the UART to use for the HCI connection.
@@ -49,16 +53,66 @@ func (a *Adapter) SetSoftwareFlowControl(cts, rts machine.Pin) error {
4953// Enable configures the BLE stack. It must be called before any
5054// Bluetooth-related calls (unless otherwise indicated).
5155func (a * Adapter ) Enable () error {
52- a .hci , a .att = newBLEStack (a .uart )
53-
56+ transport := & hciUART {uart : a .uart }
5457 if a .cts != 0 && a .rts != 0 {
55- a . hci . softRTS = a .rts
56- a .hci . softRTS .Configure (machine.PinConfig {Mode : machine .PinOutput })
57- a .hci . softRTS .High ()
58+ transport . rts = a .rts
59+ a .rts .Configure (machine.PinConfig {Mode : machine .PinOutput })
60+ a .rts .High ()
5861
59- a . hci . softCTS = a .cts
62+ transport . cts = a .cts
6063 a .cts .Configure (machine.PinConfig {Mode : machine .PinInput })
6164 }
6265
66+ a .hci , a .att = newBLEStack (transport )
6367 a .enable ()
68+
69+ return nil
70+ }
71+
72+ type hciUART struct {
73+ uart * machine.UART
74+
75+ // used for software flow control
76+ cts , rts machine.Pin
77+ }
78+
79+ func (h * hciUART ) startRead () {
80+ if h .rts != machine .NoPin {
81+ h .rts .Low ()
82+ }
83+ }
84+
85+ func (h * hciUART ) endRead () {
86+ if h .rts != machine .NoPin {
87+ h .rts .High ()
88+ }
89+ }
90+
91+ func (h * hciUART ) Buffered () int {
92+ return h .uart .Buffered ()
93+ }
94+
95+ func (h * hciUART ) ReadByte () (byte , error ) {
96+ return h .uart .ReadByte ()
97+ }
98+
99+ const writeAttempts = 200
100+
101+ func (h * hciUART ) Write (buf []byte ) (int , error ) {
102+ if h .cts != machine .NoPin {
103+ retries := writeAttempts
104+ for h .cts .Get () {
105+ retries --
106+ if retries == 0 {
107+ return 0 , ErrHCITimeout
108+ }
109+ }
110+ }
111+
112+ n , err := h .uart .Write (buf )
113+ if err != nil {
114+ return 0 , err
115+ }
116+
117+ return n , nil
64118}
0 commit comments