1
+ #include " ManagedTinyGsmClient.h"
2
+
3
+ // Static member definitions
4
+ uint32_t ManagedTinyGsmClient::usedSockets = 0 ;
5
+ bool ManagedTinyGsmClient::socketMutex = false ;
6
+
7
+ void ManagedTinyGsmClient::lockSockets () {
8
+ // Simple spinlock - not ideal but works for basic protection
9
+ while (socketMutex) {
10
+ delay (1 ); // Small delay to prevent busy waiting
11
+ }
12
+ socketMutex = true ;
13
+ }
14
+
15
+ void ManagedTinyGsmClient::unlockSockets () {
16
+ socketMutex = false ;
17
+ }
18
+
19
+ int ManagedTinyGsmClient::allocateSocket () {
20
+ lockSockets ();
21
+
22
+ for (int i = 0 ; i < TINY_GSM_MUX_COUNT; i++) {
23
+ uint32_t mask = 1UL << i;
24
+ if (!(usedSockets & mask)) {
25
+ usedSockets |= mask; // Set bit i
26
+ unlockSockets ();
27
+ return i;
28
+ }
29
+ }
30
+
31
+ unlockSockets ();
32
+ return -1 ; // No available sockets
33
+ }
34
+
35
+ void ManagedTinyGsmClient::releaseSocket (int socketId) {
36
+ if (socketId >= 0 && socketId < TINY_GSM_MUX_COUNT) {
37
+ lockSockets ();
38
+ uint32_t mask = 1UL << socketId;
39
+ usedSockets &= ~mask; // Clear bit socketId
40
+ unlockSockets ();
41
+ }
42
+ }
43
+
44
+ ManagedTinyGsmClient::ManagedTinyGsmClient (TinyGsm& modem)
45
+ : socketId(allocateSocket()), TinyGsmClient(modem, socketId) {
46
+ // Note: If socketId is -1, the client is invalid
47
+ }
48
+
49
+ ManagedTinyGsmClient::ManagedTinyGsmClient (const ManagedTinyGsmClient& other)
50
+ : socketId(allocateSocket()), TinyGsmClient(other) {
51
+ // Copy constructor allocates a new socket
52
+ // Note: If socketId is -1, the client is invalid
53
+ }
54
+
55
+ ManagedTinyGsmClient& ManagedTinyGsmClient::operator =(const ManagedTinyGsmClient& other) {
56
+ if (this != &other) {
57
+ TinyGsmClient::operator =(other);
58
+ // Keep our own socket - don't change it
59
+ }
60
+ return *this ;
61
+ }
62
+
63
+ ManagedTinyGsmClient::ManagedTinyGsmClient (ManagedTinyGsmClient&& other)
64
+ : socketId(other.socketId), TinyGsmClient(other) {
65
+ other.socketId = -1 ; // Mark other as moved-from
66
+ }
67
+
68
+ ManagedTinyGsmClient& ManagedTinyGsmClient::operator =(ManagedTinyGsmClient&& other) {
69
+ if (this != &other) {
70
+ // Release our current socket
71
+ releaseSocket (socketId);
72
+
73
+ TinyGsmClient::operator =(other);
74
+ socketId = other.socketId ;
75
+ other.socketId = -1 ; // Mark other as moved-from
76
+ }
77
+ return *this ;
78
+ }
79
+
80
+ ManagedTinyGsmClient::~ManagedTinyGsmClient () {
81
+ releaseSocket (socketId);
82
+ }
0 commit comments