aboutsummaryrefslogtreecommitdiff
path: root/vote/vote.ino
blob: 14b1e99c6f52a9fb55ea19949a3038d50ee58234 (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_TOLERANCE = 1 * 60 * 1000; // 1 minute
  36. // Classify gape state
  37. enum MusselGapState {
  38. Closed,
  39. Open
  40. };
  41. // Data structures
  42. struct Vote {
  43. unsigned long timestamp;
  44. int measure;
  45. };
  46. struct Voter {
  47. String id; // Mussel ID
  48. Vote votes[BALLOT_MAX]; // Last 5 sensor readings
  49. int voteCount = 0; // Number of readings stored
  50. };
  51. // Global array of mussel voters
  52. Voter voters[VOTER_MAX];
  53. int voterCount = 0;
  54. // pointer to control Bluetooth networking
  55. BLEScan *pBLEScan;
  56. /// Find index of mussel ID in the voters array
  57. int findVoterIndex(const String& id) {
  58. for (int i = 0; i < voterCount; i++) {
  59. if (voters[i].id == id) return i;
  60. }
  61. return -1; // Not found
  62. }
  63. /// Add or update vote for a mussel ID
  64. void storeVoteForMussel(
  65. const String& id, unsigned long timestamp, int gape_measure
  66. ) {
  67. int index = findVoterIndex(id);
  68. // If mussel not found, add new
  69. if (index == -1) {
  70. if (voterCount >= VOTER_MAX) {
  71. log_i("Ignored: Max mussel limit reached (%s)",
  72. id.c_str());
  73. return;
  74. }
  75. voters[voterCount].id = id;
  76. voters[voterCount].voteCount = 0;
  77. index = voterCount++;
  78. }
  79. Voter &voter = voters[index];
  80. // Maintain a fixed number of stored votes (FIFO logic)
  81. if (voter.voteCount >= BALLOT_MAX) {
  82. for (int i = 1; i < BALLOT_MAX; i++) {
  83. voter.votes[i - 1] = voter.votes[i];
  84. }
  85. voter.voteCount = BALLOT_MAX - 1;
  86. }
  87. // Store the new vote at the end
  88. voter.votes[voter.voteCount++] = {timestamp, gape_measure};
  89. log_i("Vote stored: Time: %lu, Mussel: %s, Gape: %d",
  90. timestamp, id.c_str(), gape_measure);
  91. }
  92. /// Clean outdated votes and mussels with no valid votes
  93. void cleanOldVotes() {
  94. unsigned long now = millis();
  95. for (int i = 0; i < voterCount; ) {
  96. Voter &voter = voters[i];
  97. int newCount = 0;
  98. // Shift valid votes to the front
  99. for (int j = 0; j < voter.voteCount; j++) {
  100. unsigned long age = now - voter.votes[j].timestamp;
  101. if (age < VOTE_TIME_TOLERANCE) {
  102. voter.votes[newCount++] = voter.votes[j];
  103. } else {
  104. log_i("Dropped old vote for Mussel %s | Age: %lu ms",
  105. voter.id.c_str(), age);
  106. }
  107. }
  108. voter.voteCount = newCount;
  109. // If all votes are dropped, remove the mussel
  110. if (voter.voteCount == 0) {
  111. log_i("Removing Mussel %s - No valid votes left",
  112. voter.id.c_str());
  113. for (int k = i; k < voterCount - 1; k++) {
  114. voters[k] = voters[k + 1];
  115. }
  116. voterCount--;
  117. continue; // Do not increment i since the list shifted
  118. }
  119. i++; // Only increment if we didn't remove current voter
  120. }
  121. }
  122. /// Classify mussel state based on topmost vote
  123. void alignVotes() {
  124. for (int i = 0; i < voterCount; i++) {
  125. Voter &voter = voters[i];
  126. // Skip mussels with no data
  127. if (voter.voteCount == 0) {
  128. log_i("Mussel ID: %s - No data",
  129. voter.id.c_str());
  130. continue;
  131. }
  132. // Use latest vote to determine state
  133. Vote latest = voter.votes[voter.voteCount - 1];
  134. String state = (latest.measure >= 0 && latest.measure < 40)
  135. ? "Closed"
  136. : (latest.measure >= 40 && latest.measure <= 90)
  137. ? "Open"
  138. : "Invalid reading";
  139. log_i("Mussel ID: %s | Latest Gape: %d | State: %s",
  140. voter.id.c_str(), latest.measure, state.c_str());
  141. }
  142. }
  143. /// Decide whether a vote is valid based on age
  144. const char* qualifyMusselVote(
  145. unsigned long voteTimestamp, unsigned long now
  146. ) {
  147. unsigned long age = now - voteTimestamp;
  148. if (age <= VOTE_TIME_TOLERANCE) {
  149. log_i("VALID: Vote is within 1 minute (age: %lums)",
  150. age);
  151. return "valid";
  152. } else {
  153. log_i("INVALID: Vote is older than 1 minute (age: %lums)",
  154. age);
  155. return "invalid";
  156. }
  157. }
  158. /// Output the final vote decision for mussels
  159. void concludeMusselVote() {
  160. int openVotes = 0;
  161. int totalValidVotes = 0;
  162. // First, align votes and qualify them
  163. for (int i = 0; i < voterCount; i++) {
  164. Voter &voter = voters[i];
  165. // Skip mussels with no data
  166. if (voter.voteCount == 0) continue;
  167. // Use latest vote to determine state
  168. Vote latest = voter.votes[voter.voteCount - 1];
  169. unsigned long now = millis();
  170. // Check if the vote is valid using the qualify function
  171. const char* validity = qualifyMusselVote(latest.timestamp, now);
  172. if (strcmp(validity, "valid") == 0) {
  173. totalValidVotes++; // Count valid votes
  174. // Align and classify mussel state
  175. String state = (latest.measure >= 0 && latest.measure < 40)
  176. ? "Closed"
  177. : (latest.measure >= 40 && latest.measure <= 90)
  178. ? "Open"
  179. : "Invalid reading";
  180. // Count valid "Open" votes
  181. if (state == "Open") {
  182. openVotes++;
  183. }
  184. }
  185. }
  186. // Determine the threshold (half of total valid votes, rounded down)
  187. int threshold = totalValidVotes / 2;
  188. // Same or more "Open" votes than the threshold means water is ok
  189. if (openVotes >= threshold) {
  190. log_i("YES, water is drinkable (open: %d, valid: %d)",
  191. openVotes, totalValidVotes);
  192. } else {
  193. log_i("NO, water is not drinkable (open: %d, valid: %d)",
  194. openVotes, totalValidVotes);
  195. }
  196. }
  197. // Bluetooth beacon discovery callbacks
  198. class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
  199. // decode name and temperature from Eddystone TLM advertisement
  200. void onResult(BLEAdvertisedDevice advertisedDevice) {
  201. if (advertisedDevice.haveName()
  202. && advertisedDevice.getFrameType() == BLE_EDDYSTONE_TLM_FRAME
  203. ) {
  204. BLEEddystoneTLM EddystoneTLM(&advertisedDevice);
  205. // misuse error-only log level for plot-friendly output
  206. #if ARDUHAL_LOG_LEVEL == ARDUHAL_LOG_LEVEL_ERROR
  207. String id_mangled = advertisedDevice.getName();
  208. id_mangled.replace(' ', '_');
  209. id_mangled.replace(':', '=');
  210. Serial.println(id_mangled + ":" + EddystoneTLM.getTemp());
  211. #endif
  212. unsigned long now = millis();
  213. String musselID = advertisedDevice.getName();
  214. int gape = EddystoneTLM.getTemp();
  215. // 1. Store vote
  216. storeVoteForMussel(musselID, now, gape);
  217. // 2. Align
  218. alignVotes();
  219. // 3. Qualify
  220. const char* validity = qualifyMusselVote( now, millis());
  221. // 4. Conclude
  222. concludeMusselVote();
  223. }
  224. }
  225. };
  226. void setup() {
  227. // enable logging to serial
  228. Serial.begin(115200);
  229. esp_log_level_set("*", ESP_LOG_DEBUG);
  230. // setup Bluetooth
  231. BLEDevice::init("");
  232. pBLEScan = BLEDevice::getScan();
  233. pBLEScan->setAdvertisedDeviceCallbacks(
  234. new MyAdvertisedDeviceCallbacks());
  235. pBLEScan->setActiveScan(true);
  236. pBLEScan->setInterval(SCAN_INTERVAL);
  237. pBLEScan->setWindow(SCAN_WINDOW);
  238. }
  239. void loop() {
  240. pBLEScan->start(SCAN_TIME_SEC, false);
  241. pBLEScan->clearResults();
  242. cleanOldVotes(); // Keeps the voter stack tidy
  243. delay(500);
  244. }