aboutsummaryrefslogtreecommitdiff
path: root/vote/vote.ino
blob: a805ea6e347d32744435e9c8071c5934d7c0851b (plain)
  1. // SPDX-FileCopyrightText: 2025 Amal Mazrah <mazrah@ruc.dk>
  2. // SPDX-FileCopyrightText: 2025 Jonas Smedegaard <dr@jones.dk>
  3. // SPDX-FileCopyrightText: 2025 Mennatullah Hatim Kassim <stud-mennatulla@ruc.dk>
  4. // SPDX-FileCopyrightText: 2025 Noor Ahmad <noora@ruc.dk>
  5. // SPDX-FileCopyrightText: 2025 Tanishka Suwalka <tanishkas@ruc.dk>
  6. // SPDX-License-Identifier: GPL-3.0-or-later
  7. /// Mussel vote - an Arduino sketch to monitor mussel biosensors
  8. ///
  9. /// @version 0.0.3
  10. /// @see <https://app.radicle.xyz/nodes/seed.radicle.garden/rad:z2tFBF4gN7ziG9oXtUytVQNYe3VhQ>
  11. /// @see <https://moodle.ruc.dk/course/view.php?id=23504>
  12. // arduino-esp32 Logging system
  13. // activate in Arduino IDE: Tools -> Core Debug Level
  14. // special: set Core Debug Level to Error for plot-friendly output
  15. #define CONFIG_ARDUHAL_ESP_LOG 1
  16. #define LOG_LOCAL_LEVEL CORE_DEBUG_LEVEL
  17. #include <esp32-hal-log.h>
  18. #undef ARDUHAL_LOG_FORMAT
  19. #define ARDUHAL_LOG_FORMAT(letter, format) \
  20. ARDUHAL_LOG_COLOR_##letter "[" #letter "] %s(): " format \
  21. ARDUHAL_LOG_RESET_COLOR "\r\n", __FUNCTION__
  22. // arduino-esp32 Bluetooth Low Energy (BLE) networking stack
  23. #include <BLEDevice.h>
  24. #include <BLEScan.h>
  25. #include <BLEAdvertisedDevice.h>
  26. #include <BLEEddystoneTLM.h>
  27. #include <BLEBeacon.h>
  28. #define SCAN_INTERVAL 100
  29. #define SCAN_WINDOW 99
  30. #define SCAN_TIME_SEC 1
  31. // stack sizes for voters and ballots-per-voter
  32. #define VOTER_MAX 10
  33. #define BALLOT_MAX 5
  34. // Validity timing thresholds
  35. const unsigned long VOTE_TIME_AHEAD = 1 * 60 * 1000; // 1 minute
  36. const unsigned long VOTE_TIME_BEHIND = 2 * 60 * 1000; // 2 minutes
  37. // Classify gape state
  38. enum MusselGapState {
  39. Closed,
  40. Open
  41. };
  42. // Data structures
  43. struct Vote {
  44. unsigned long timestamp;
  45. int measure;
  46. };
  47. struct Voter {
  48. String id; // Mussel ID
  49. Vote votes[BALLOT_MAX]; // Last 5 sensor readings
  50. int voteCount = 0; // Number of readings stored
  51. };
  52. // Global array of mussel voters
  53. Voter voters[VOTER_MAX];
  54. int voterCount = 0;
  55. // pointer to control Bluetooth networking
  56. BLEScan *pBLEScan;
  57. /// Find index of mussel ID in the voters array
  58. int findVoterIndex(const String& id) {
  59. for (int i = 0; i < voterCount; i++) {
  60. if (voters[i].id == id) return i;
  61. }
  62. return -1; // Not found
  63. }
  64. /// Add or update vote for a mussel ID
  65. void storeVoteForMussel(const String& id, unsigned long timestamp, int gape_measure) {
  66. int index = findVoterIndex(id);
  67. // If mussel not found, add new
  68. if (index == -1) {
  69. if (voterCount >= VOTER_MAX) {
  70. log_i("Ignored: Max mussel limit reached (%s)",
  71. id.c_str());
  72. return;
  73. }
  74. voters[voterCount].id = id;
  75. voters[voterCount].voteCount = 0;
  76. index = voterCount++;
  77. }
  78. Voter &voter = voters[index];
  79. // Maintain a fixed number of stored votes (FIFO logic)
  80. if (voter.voteCount >= BALLOT_MAX) {
  81. for (int i = 1; i < BALLOT_MAX; i++) {
  82. voter.votes[i - 1] = voter.votes[i];
  83. }
  84. voter.voteCount = BALLOT_MAX - 1;
  85. }
  86. // Store the new vote at the end
  87. voter.votes[voter.voteCount++] = {timestamp, gape_measure};
  88. log_i("Vote stored: Time: %lu, Mussel: %s, Gape: %d",
  89. timestamp, id.c_str(), gape_measure);
  90. }
  91. /// Classify mussel state based on topmost vote
  92. void alignVotes() {
  93. for (int i = 0; i < voterCount; i++) {
  94. Voter &voter = voters[i];
  95. // Skip mussels with no data
  96. if (voter.voteCount == 0) {
  97. log_i("Mussel ID: %s - No data",
  98. voter.id.c_str());
  99. continue;
  100. }
  101. // Use latest vote to determine state
  102. Vote latest = voter.votes[voter.voteCount - 1];
  103. String state = (latest.measure >= 0 && latest.measure < 40) ? "Closed" :
  104. (latest.measure >= 40 && latest.measure <= 90) ? "Open" :
  105. "Invalid reading";
  106. log_i("Mussel ID: %s | Latest Gape: %d | State: %s",
  107. voter.id.c_str(), latest.measure, state.c_str());
  108. }
  109. }
  110. /// Decide whether a vote is valid based on gape and age
  111. const char* qualifyMusselVote(int gape, unsigned long voteTimestamp, unsigned long now) {
  112. // Determine state based on gape
  113. MusselGapState gapState = gape >= 40 && gape <= 90 ? Open : Closed;
  114. const char* gapStateStr = (gapState == Open) ? "Open" : "Closed";
  115. unsigned long age = now - voteTimestamp;
  116. // Log the state
  117. log_i("Qualifying vote | Time since vote: %lu ms | Gape: %d (%s)",
  118. age, gape, gapStateStr);
  119. // Invalid if mussel is closed
  120. if (gapState == Closed) {
  121. log_i("→ INVALID: Mussel is Closed");
  122. return "invalid";
  123. }
  124. // Invalid if vote is too old
  125. if (age > VOTE_TIME_BEHIND) {
  126. log_i("→ INVALID: Vote is too old (>2 minutes)");
  127. return "invalid";
  128. }
  129. // Valid if within 1 minute and mussel is open
  130. if (age <= VOTE_TIME_AHEAD) {
  131. log_i("→ VALID: Mussel is Open and vote is recent");
  132. return "valid";
  133. }
  134. // Catch-all for anything in between
  135. log_i("→ INVALID: Vote is in uncertain window time");
  136. return "invalid";
  137. }
  138. /// Output the final vote decision for a mussel
  139. void concludeMusselVote(const String& musselId, const char* validity) {
  140. const char* result = strcmp(validity, "valid") == 0 ? "YES" : "NO";
  141. log_i("Final Vote from Mussel %s %s (Vote was %s)",
  142. musselId.c_str(), result, validity);
  143. }
  144. // Bluetooth beacon discovery callbacks
  145. class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
  146. // decode name and temperature from Eddystone TLM advertisement
  147. void onResult(BLEAdvertisedDevice advertisedDevice) {
  148. if (advertisedDevice.haveName()
  149. && advertisedDevice.getFrameType() == BLE_EDDYSTONE_TLM_FRAME
  150. ) {
  151. BLEEddystoneTLM EddystoneTLM(&advertisedDevice);
  152. // misuse error-only log level for plot-friendly output
  153. #if ARDUHAL_LOG_LEVEL == ARDUHAL_LOG_LEVEL_ERROR
  154. String id_mangled = advertisedDevice.getName();
  155. id_mangled.replace(' ', '_');
  156. id_mangled.replace(':', '=');
  157. Serial.println(id_mangled + ":" + EddystoneTLM.getTemp());
  158. #endif
  159. unsigned long now = millis();
  160. String musselID = advertisedDevice.getName();
  161. int gape = EddystoneTLM.getTemp(); // Referring to gape_measure
  162. // 1. Store vote
  163. storeVoteForMussel(musselID, now, gape);
  164. // 2. Align
  165. alignVotes();
  166. // 3. Qualify
  167. const char* validity = qualifyMusselVote(gape, now, millis());
  168. // 4. Conclude
  169. concludeMusselVote(musselID, validity);
  170. }
  171. }
  172. };
  173. void setup() {
  174. // enable logging to serial
  175. Serial.begin(115200);
  176. esp_log_level_set("*", ESP_LOG_DEBUG);
  177. // setup Bluetooth
  178. BLEDevice::init("");
  179. pBLEScan = BLEDevice::getScan();
  180. pBLEScan->setAdvertisedDeviceCallbacks(
  181. new MyAdvertisedDeviceCallbacks());
  182. pBLEScan->setActiveScan(true);
  183. pBLEScan->setInterval(SCAN_INTERVAL);
  184. pBLEScan->setWindow(SCAN_WINDOW);
  185. }
  186. void loop() {
  187. pBLEScan->start(SCAN_TIME_SEC, false);
  188. pBLEScan->clearResults();
  189. delay(500);
  190. }