aboutsummaryrefslogtreecommitdiff
path: root/vote/vote.ino
blob: caa4fbcbca79c15aa4f8b1606d25ea4a8980cbea (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(
  66. const String& id, unsigned long timestamp, int gape_measure
  67. ) {
  68. int index = findVoterIndex(id);
  69. // If mussel not found, add new
  70. if (index == -1) {
  71. if (voterCount >= VOTER_MAX) {
  72. log_i("Ignored: Max mussel limit reached (%s)",
  73. id.c_str());
  74. return;
  75. }
  76. voters[voterCount].id = id;
  77. voters[voterCount].voteCount = 0;
  78. index = voterCount++;
  79. }
  80. Voter &voter = voters[index];
  81. // Maintain a fixed number of stored votes (FIFO logic)
  82. if (voter.voteCount >= BALLOT_MAX) {
  83. for (int i = 1; i < BALLOT_MAX; i++) {
  84. voter.votes[i - 1] = voter.votes[i];
  85. }
  86. voter.voteCount = BALLOT_MAX - 1;
  87. }
  88. // Store the new vote at the end
  89. voter.votes[voter.voteCount++] = {timestamp, gape_measure};
  90. log_i("Vote stored: Time: %lu, Mussel: %s, Gape: %d",
  91. timestamp, id.c_str(), gape_measure);
  92. }
  93. /// Classify mussel state based on topmost vote
  94. void alignVotes() {
  95. for (int i = 0; i < voterCount; i++) {
  96. Voter &voter = voters[i];
  97. // Skip mussels with no data
  98. if (voter.voteCount == 0) {
  99. log_i("Mussel ID: %s - No data",
  100. voter.id.c_str());
  101. continue;
  102. }
  103. // Use latest vote to determine state
  104. Vote latest = voter.votes[voter.voteCount - 1];
  105. String state = (latest.measure >= 0 && latest.measure < 40)
  106. ? "Closed"
  107. : (latest.measure >= 40 && latest.measure <= 90)
  108. ? "Open"
  109. : "Invalid reading";
  110. log_i("Mussel ID: %s | Latest Gape: %d | State: %s",
  111. voter.id.c_str(), latest.measure, state.c_str());
  112. }
  113. }
  114. /// Decide whether a vote is valid based on gape and age
  115. const char* qualifyMusselVote(
  116. int gape, unsigned long voteTimestamp, unsigned long now
  117. ) {
  118. // Determine state based on gape
  119. MusselGapState gapState = gape >= 40 && gape <= 90 ? Open : Closed;
  120. const char* gapStateStr = (gapState == Open) ? "Open" : "Closed";
  121. unsigned long age = now - voteTimestamp;
  122. // Log the state
  123. log_i("Qualifying vote | Time since vote: %lu ms | Gape: %d (%s)",
  124. age, gape, gapStateStr);
  125. // Invalid if mussel is closed
  126. if (gapState == Closed) {
  127. log_i("→ INVALID: Mussel is Closed");
  128. return "invalid";
  129. }
  130. // Invalid if vote is too old
  131. if (age > VOTE_TIME_BEHIND) {
  132. log_i("→ INVALID: Vote is too old (>2 minutes)");
  133. return "invalid";
  134. }
  135. // Valid if within 1 minute and mussel is open
  136. if (age <= VOTE_TIME_AHEAD) {
  137. log_i("→ VALID: Mussel is Open and vote is recent");
  138. return "valid";
  139. }
  140. // Catch-all for anything in between
  141. log_i("→ INVALID: Vote is in uncertain window time");
  142. return "invalid";
  143. }
  144. /// Output the final vote decision for a mussel
  145. void concludeMusselVote(const String& musselId, const char* validity) {
  146. const char* result = strcmp(validity, "valid") == 0 ? "YES" : "NO";
  147. log_i("Final Vote from Mussel %s %s (Vote was %s)",
  148. musselId.c_str(), result, validity);
  149. }
  150. // Bluetooth beacon discovery callbacks
  151. class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
  152. // decode name and temperature from Eddystone TLM advertisement
  153. void onResult(BLEAdvertisedDevice advertisedDevice) {
  154. if (advertisedDevice.haveName()
  155. && advertisedDevice.getFrameType() == BLE_EDDYSTONE_TLM_FRAME
  156. ) {
  157. BLEEddystoneTLM EddystoneTLM(&advertisedDevice);
  158. // misuse error-only log level for plot-friendly output
  159. #if ARDUHAL_LOG_LEVEL == ARDUHAL_LOG_LEVEL_ERROR
  160. String id_mangled = advertisedDevice.getName();
  161. id_mangled.replace(' ', '_');
  162. id_mangled.replace(':', '=');
  163. Serial.println(id_mangled + ":" + EddystoneTLM.getTemp());
  164. #endif
  165. unsigned long now = millis();
  166. String musselID = advertisedDevice.getName();
  167. int gape = EddystoneTLM.getTemp();
  168. // 1. Store vote
  169. storeVoteForMussel(musselID, now, gape);
  170. // 2. Align
  171. alignVotes();
  172. // 3. Qualify
  173. const char* validity = qualifyMusselVote(gape, now, millis());
  174. // 4. Conclude
  175. concludeMusselVote(musselID, validity);
  176. }
  177. }
  178. };
  179. void setup() {
  180. // enable logging to serial
  181. Serial.begin(115200);
  182. esp_log_level_set("*", ESP_LOG_DEBUG);
  183. // setup Bluetooth
  184. BLEDevice::init("");
  185. pBLEScan = BLEDevice::getScan();
  186. pBLEScan->setAdvertisedDeviceCallbacks(
  187. new MyAdvertisedDeviceCallbacks());
  188. pBLEScan->setActiveScan(true);
  189. pBLEScan->setInterval(SCAN_INTERVAL);
  190. pBLEScan->setWindow(SCAN_WINDOW);
  191. }
  192. void loop() {
  193. pBLEScan->start(SCAN_TIME_SEC, false);
  194. pBLEScan->clearResults();
  195. delay(500);
  196. }