Skip to content

Commit 31ddb45

Browse files
committed
feat: on timeout bridge.client has appropriate error code
fix: RpcResult overloaded bool using a generic return type, not setting a timeout, can potentially execute result method multiple times
1 parent 7932a81 commit 31ddb45

File tree

1 file changed

+27
-13
lines changed

1 file changed

+27
-13
lines changed

src/bridge.h

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,21 @@
2929
void updateEntryPoint(void *, void *, void *);
3030

3131
class RpcResult {
32+
33+
const int FALLBACK_TIMEOUT = 10;
34+
3235
public:
33-
RpcResult(uint32_t id, RPCClient* c, struct k_mutex* m) : msg_id_wait(id), client(c), read_mutex(m) {}
36+
RpcResult(uint32_t id, RPCClient* c, struct k_mutex* m, int timeout) : msg_id_wait(id), client(c), read_mutex(m), _timeout(timeout) {}
37+
38+
template<typename RType> bool result(RType& result) {
3439

35-
template<typename RType> bool result(RType& result, int timeout_ms = -1) {
36-
// Lock read mutex
37-
if (_timeout < 0) _timeout = timeout_ms;
3840
int start = millis();
39-
while(true && (_timeout < 0 || (millis() - start) < _timeout)) {
41+
while(true) {
42+
if (_timeout > 0 && (millis() - start) > _timeout){
43+
client->lastError.code = GENERIC_ERR;
44+
client->lastError.message = "Timed out";
45+
break;
46+
}
4047
if (k_mutex_lock(read_mutex, K_MSEC(10)) == 0 ) {
4148
if (client->get_response(msg_id_wait, result)) {
4249
k_mutex_unlock(read_mutex);
@@ -48,19 +55,20 @@ class RpcResult {
4855
k_yield();
4956
}
5057
}
51-
return (client->lastError.code == NO_ERR) && (_timeout < 0 || (millis() - start) < _timeout);
58+
_executed = true;
59+
return client->lastError.code == NO_ERR;
5260
}
61+
5362
operator bool() {
54-
char c;
55-
return result(c);
56-
}
57-
RpcResult& timeout(int ms) {
58-
_timeout = ms;
59-
return *this;
63+
if (_executed) return client->lastError.code == NO_ERR;
64+
MsgPack::object::nil_t nil;
65+
return result(nil, FALLBACK_TIMEOUT);
6066
}
67+
6168
private:
6269
uint32_t msg_id_wait;
6370
RPCClient* client;
71+
bool _executed = false;
6472
struct k_mutex* read_mutex;
6573
int _timeout = -1;
6674
};
@@ -81,6 +89,8 @@ class BridgeClass {
8189

8290
bool started = false;
8391

92+
int _timeout = -1;
93+
8494
public:
8595

8696
explicit BridgeClass(HardwareSerial& serial) {
@@ -91,6 +101,10 @@ class BridgeClass {
91101
return started;
92102
}
93103

104+
void setTimeout(int t) {
105+
_timeout = t;
106+
}
107+
94108
// Initialize the bridge
95109
bool begin(unsigned long baud=DEFAULT_SERIAL_BAUD) {
96110
serial_ptr->begin(baud);
@@ -183,7 +197,7 @@ class BridgeClass {
183197
k_yield();
184198
}
185199
}
186-
return RpcResult{msg_id_wait, client, &read_mutex};
200+
return RpcResult{msg_id_wait, client, &read_mutex, _timeout};
187201
}
188202

189203

0 commit comments

Comments
 (0)