@@ -50,6 +50,19 @@ func handleEvent() {
5050 currentConnection .Reg = gapEvent .conn_handle
5151 DefaultAdapter .connectHandler (Address {}, true )
5252 case C .BLE_GAP_EVT_DISCONNECTED :
53+ if debug {
54+ println ("evt: disconnected" )
55+ }
56+ // Store system attributes data
57+ dataLen := uint16 (0 )
58+ C .sd_ble_gatts_sys_attr_get (gapEvent .conn_handle , nil , & dataLen , 0 ) // get data length
59+ if int (dataLen ) <= cap (DefaultAdapter .systemAttributes ) { // we can not allocate here, so ensure at least data fits the buffer
60+ DefaultAdapter .systemAttributes = DefaultAdapter .systemAttributes [:dataLen ]
61+ C .sd_ble_gatts_sys_attr_get (gapEvent .conn_handle , & DefaultAdapter .systemAttributes [0 ], & dataLen , 0 )
62+ }
63+ // Clean up state for this connection.
64+ currentConnection .Reg = C .BLE_CONN_HANDLE_INVALID
65+ // Auto-restart advertisement if needed.
5366 if defaultAdvertisement .isAdvertising .Get () != 0 {
5467 // The advertisement was running but was automatically stopped
5568 // by the connection event.
@@ -59,7 +72,6 @@ func handleEvent() {
5972 // necessary.
6073 defaultAdvertisement .start ()
6174 }
62- currentConnection .Reg = C .BLE_CONN_HANDLE_INVALID
6375 DefaultAdapter .connectHandler (Address {}, false )
6476 case C .BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST :
6577 // Respond with the default PPCP connection parameters by passing
@@ -87,15 +99,16 @@ func handleEvent() {
8799 handler .callback (Connection (gattsEvent .conn_handle ), int (writeEvent .offset ), data )
88100 }
89101 case C .BLE_GATTS_EVT_SYS_ATTR_MISSING :
90- // This event is generated when reading the Generic Attribute
91- // service. It appears to be necessary for bonded devices.
92- // From the docs:
93- // > If the pointer is NULL, the system attribute info is
94- // > initialized, assuming that the application does not have any
95- // > previously saved system attribute data for this device.
96- // Maybe we should look at the error, but as there's not really a
97- // way to handle it, ignore it.
98- C .sd_ble_gatts_sys_attr_set (gattsEvent .conn_handle , nil , 0 , 0 )
102+ if debug {
103+ println ("evt: sys attr missing" )
104+ }
105+ // Try and restore system attributes data if we have any (from previous connections)
106+ // Fallback to initialize them from scratch otherwise
107+ if len (DefaultAdapter .systemAttributes ) > 0 {
108+ C .sd_ble_gatts_sys_attr_set (gattsEvent .conn_handle , & DefaultAdapter .systemAttributes [0 ], uint16 (len (DefaultAdapter .systemAttributes )), 0 )
109+ } else {
110+ C .sd_ble_gatts_sys_attr_set (gattsEvent .conn_handle , nil , 0 , 0 )
111+ }
99112 default :
100113 if debug {
101114 println ("unknown GATTS event:" , id , id - C .BLE_GATTS_EVT_BASE )
0 commit comments