27 Commits
Author SHA1 Message Date
Kostas Drakontidis 80ff81b1e0 room occupancy impl & race cond fix & local user roomID and psuedoID storage for cleanup and indexing 2026-05-25 05:57:35 +03:00
Kostas Drakontidis 46016d966d ngsi-ld public api code 2026-05-25 05:55:43 +03:00
Kostas Drakontidis c2b947a197 flush redis on startup and init subredis 2026-05-25 05:55:04 +03:00
Kostas Drakontidis 66ab3fa6ca added debug prefix 2026-05-25 05:54:37 +03:00
Kostas Drakontidis c8da529ce3 whitespace 2026-05-25 05:54:25 +03:00
Kostas Drakontidis 93c65a948b added routes 2026-05-25 05:54:17 +03:00
Kostas Drakontidis 124ef542b0 moved redis & added subredis for expire notifications 2026-05-25 05:53:53 +03:00
Kostas DrakontidisandGitHub 31f8dc2f98 Update progress.md with Week 4 details 2026-05-24 00:25:38 +03:00
Kostas DrakontidisandGitHub 77f53435fe Merge pull request #14 from dkwstas/core_dev
Core dev
2026-05-24 00:21:14 +03:00
Kostas Drakontidis 565900c9d4 init fully working core code 2026-05-24 00:19:09 +03:00
Kostas Drakontidis a3d28e8cd5 prisma migrations 2026-05-24 00:18:31 +03:00
Kostas Drakontidis 9d024de5a6 get data from tag table instead of user 2026-05-24 00:04:43 +03:00
Kostas Drakontidis 18932a3f4d add room entity 2026-05-24 00:03:59 +03:00
Kostas Drakontidis e4868f6fdc install mqtt & redis packages 2026-05-24 00:03:51 +03:00
Kostas Drakontidis d4cf7f5b48 mqtt topic and msg small change 2026-05-23 23:43:28 +03:00
Kostas Drakontidis c8f07e22d9 Add reset command scanner 2026-05-22 13:03:47 +03:00
Kostas DrakontidisandGitHub 22f4d777a4 Merge pull request #13 from dkwstas/persistent_config
Closes #11
2026-05-20 17:46:57 +03:00
admin 3977e8d17b Tag config management code 2026-05-20 17:44:46 +03:00
Kostas DrakontidisandGitHub a50c48a92d Merge pull request #12 from dkwstas/main
Change tag name & remove mfg data
2026-05-19 23:29:19 +03:00
admin 96233d2ae5 Scanner config management code 2026-05-19 23:02:09 +03:00
Kostas Drakontidis 86cc46ea9b Change tag name & remove mfg data 2026-05-15 17:32:45 +03:00
Kostas DrakontidisandGitHub d5738d460c Add equipment functionality testing to completed section 2026-05-15 14:34:07 +03:00
Kostas DrakontidisandGitHub 80f7c89852 Update weekly progress log with new entries 2026-05-14 23:48:10 +03:00
Kostas DrakontidisandGitHub 744d145ec2 Enhance architecture documentation for OfficeSense system
Expanded the architecture document to include detailed descriptions of the OfficeSense system, its components, data flow, design decisions, and validation plan.
2026-05-14 23:34:14 +03:00
Kostas DrakontidisandGitHub a775109b36 Merge pull request #7 from dkwstas/pi_code_init
Initial Pi code for public lookup api
2026-05-13 23:28:48 +03:00
Kostas DrakontidisandGitHub e349ef92b7 Merge pull request #5 from dkwstas/ble_scanner_init
Initial scanner code
2026-05-13 18:18:31 +03:00
Kostas DrakontidisandGitHub 095da18f73 Merge pull request #2 from dkwstas/ble_tag_init
Initial tag code
2026-05-07 00:08:13 +03:00
23 changed files with 1959 additions and 83 deletions
+50 -9
View File
@@ -1,21 +1,62 @@
# System Architecture # System Architecture
## Overview ## Overview
Describe the project at a high level. OfficeSense is a Smart Office Presence system that detects user presence and identifies the room where each user is located using Bluetooth Low Energy (BLE) technology. Users carry BLE tags that periodically broadcast pseudonymized identifiers, while BLE scanners installed in different rooms detect these signals and forward the data to a Raspberry Pi for processing.
The system follows a privacy-by-design approach by using identifiers instead of personal data during communication. In addition to BLE-based presence detection, a camera connected to the Raspberry Pi performs face-recognition-based authentication to verify that the detected BLE tag belongs to the actual user.
The architecture combines edge computing, real-time processing, and lightweight storage technologies to provide low-latency monitoring, room occupancy tracking, and secure user authentication through real-time dashboards.
## Components ## Components
- sensors / input devices - BLE Tags (Seeed Studio XIAO ESP32-C6)
- processing node - BLE Scanners (Waveshare ESP32-S3 Zero)
- communication - USB Camera
- storage - Processing Node (Raspberry Pi)
- dashboard / app - Communication (BLE, WiFi, MQTT, HTTP, NGSI-LD)
- actuators / notifications - Storage (SQLite, Redis, Optional InfluxDB)
- Dashboard (Node-RED, AdminJS, Optional Grafana)
## Data Flow ## Data Flow
Describe how data moves through the system. 1. A BLE tag periodically broadcasts a pseudonymized UUID.
2. Nearby BLE scanners receive the signal and measure RSSI values.
3. The scanners:
- validate UUIDs,
- apply EMA filtering to RSSI values,
- cache validation responses,
- package the data and publish to the MQTT broker over WiFi.
4. The Raspberry Pi receives MQTT messages and processes them.
5. The system estimates the users room based on strongest RSSI values.
6. When a new presence event occurs:
- the camera is triggered,
- image frames are captured,
- the face recognition service verifies the user identity.
7. The system compares:
- BLE tag identity
- face recognition identity
8. The authentication result and room location are stored in Redis.
9. Persistent information is stored in SQLite.
10. Backend APIs provide data to dashboards for real-time visualization.
11. If no BLE signal is received for a predefined timeout period, the user is automatically marked as absent.
## Decisions and Tradeoffs ## Decisions and Tradeoffs
Explain key design choices. - Edge Computing with Raspberry Pi
- Reduces latency
- Minimizes cloud dependency
- Improves privacy and reliability
- Hybrid Storage Architecture
- SQLite for reliable persistent storage
- Redis for fast real-time operations
- Event-Driven Processing
- BLE detections trigger processing only when needed
- Reduces unnecessary computation
- Privacy-by-Design
- Uses pseudonymized UUIDs instead of direct user identities
- MQTT Communication
- Lightweight and suitable for IoT environments
- Supports asynchronous communication
- RSSI-based localization is less accurate than more advanced positioning systems
- Face recognition increases security but also adds computational overhead
## Validation Plan ## Validation Plan
Describe how you will test the system. Describe how you will test the system.
+32 -9
View File
@@ -1,7 +1,5 @@
# Weekly Progress Log # Weekly Progress Log
Update this file every week.
## Week 1 ## Week 1
### Completed ### Completed
- Repository created - Repository created
@@ -18,19 +16,44 @@ Update this file every week.
- Finalize architecture - Finalize architecture
- Create first Issues - Create first Issues
### Team Contribution
- Student 1:
- Student 2:
## Week 2 ## Week 2
### Completed ### Completed
- Full BLE Tag code
### In Progress ### In Progress
### Problems / Risks ### Problems / Risks
### Next Steps ### Next Steps
- UUID modification during Runtime
### Team Contribution ## Week 3
- Student 1: ### Completed
- Student 2: - Full BLE Scanner code
- SQLite schema with Prisma ORM
- UUID lookup for public API
- Connected and tested functionality of all equipment
### In Progress
- Core script to receive MQTT data, process and store in Redis
- NGSI-LD data for public API
- Admin API with CRUD functions
### Problems / Risks
- WiFi won't reconnect
- no auth to use public API
### Next Steps
- WiFi self-healing and MQTT reconnection & testing
## Week 4
### Completed
- Tag & Scanner CLI for configuration & persistent config
- Core script (MQTT, location estimation, Store in Redis)
### In Progress
- NGSI-LD data for public API
- Admin API with CRUD functions
### Next Steps
- Add verification with camera in core script
+519 -3
View File
@@ -12,7 +12,9 @@
"@prisma/adapter-better-sqlite3": "^7.8.0", "@prisma/adapter-better-sqlite3": "^7.8.0",
"@prisma/client": "^7.8.0", "@prisma/client": "^7.8.0",
"dotenv": "^17.4.2", "dotenv": "^17.4.2",
"express": "^5.2.1" "express": "^5.2.1",
"mqtt": "^5.15.1",
"redis": "^5.12.1"
}, },
"devDependencies": { "devDependencies": {
"@types/better-sqlite3": "^7.6.13", "@types/better-sqlite3": "^7.6.13",
@@ -23,6 +25,15 @@
"typescript": "^6.0.3" "typescript": "^6.0.3"
} }
}, },
"node_modules/@babel/runtime": {
"version": "7.29.2",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",
"integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@electric-sql/pglite": { "node_modules/@electric-sql/pglite": {
"version": "0.4.1", "version": "0.4.1",
"resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.4.1.tgz", "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.4.1.tgz",
@@ -870,6 +881,78 @@
} }
} }
}, },
"node_modules/@redis/bloom": {
"version": "5.12.1",
"resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-5.12.1.tgz",
"integrity": "sha512-PUUfv+ms7jgPSBVoo/DN4AkPHj4D5TZSd6SbJX7egzBplkYUcKmHRE8RKia7UtZ8bSQbLguLvxVO+asKtQfZWA==",
"license": "MIT",
"engines": {
"node": ">= 18.19.0"
},
"peerDependencies": {
"@redis/client": "^5.12.1"
}
},
"node_modules/@redis/client": {
"version": "5.12.1",
"resolved": "https://registry.npmjs.org/@redis/client/-/client-5.12.1.tgz",
"integrity": "sha512-7aPGWeqA3uFm43o19umzdl16CEjK/JQGtSXVPevplTaOU3VJA/rseBC1QvYUz9lLDIMBimc4SW/zrW4S89BaCA==",
"license": "MIT",
"dependencies": {
"cluster-key-slot": "1.1.2"
},
"engines": {
"node": ">= 18.19.0"
},
"peerDependencies": {
"@node-rs/xxhash": "^1.1.0",
"@opentelemetry/api": ">=1 <2"
},
"peerDependenciesMeta": {
"@node-rs/xxhash": {
"optional": true
},
"@opentelemetry/api": {
"optional": true
}
}
},
"node_modules/@redis/json": {
"version": "5.12.1",
"resolved": "https://registry.npmjs.org/@redis/json/-/json-5.12.1.tgz",
"integrity": "sha512-eOze75esLve4vfqDel7aMX08CNaiLLQS2fV8mpRN9NxPe1rVR4vQyYiW/OgtGUysF6QOr9ANhfxABKNOJfXdKg==",
"license": "MIT",
"engines": {
"node": ">= 18.19.0"
},
"peerDependencies": {
"@redis/client": "^5.12.1"
}
},
"node_modules/@redis/search": {
"version": "5.12.1",
"resolved": "https://registry.npmjs.org/@redis/search/-/search-5.12.1.tgz",
"integrity": "sha512-ItlxbxC9cKI6IU1TLWoczwJCRb6TdmkEpWv05UrPawqaAnWGRu3rcIqsc5vN483T2fSociuyV1UkWIL5I4//2w==",
"license": "MIT",
"engines": {
"node": ">= 18.19.0"
},
"peerDependencies": {
"@redis/client": "^5.12.1"
}
},
"node_modules/@redis/time-series": {
"version": "5.12.1",
"resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-5.12.1.tgz",
"integrity": "sha512-c6JL6E3EcZJuNqKFz+KM+l9l5mpcQiKvTwgA3blt5glWJ8hjDk0yeHN3beE/MpqYIQ8UEX44ItQzgkE/gCBELQ==",
"license": "MIT",
"engines": {
"node": ">= 18.19.0"
},
"peerDependencies": {
"@redis/client": "^5.12.1"
}
},
"node_modules/@standard-schema/spec": { "node_modules/@standard-schema/spec": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
@@ -944,7 +1027,6 @@
"version": "25.7.0", "version": "25.7.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.7.0.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-25.7.0.tgz",
"integrity": "sha512-z+pdZyxE+RTQE9AcboAZCb4otwcrvgHD+GlBpPgn0emDVt0ohrTMhAwlr2Wd9nZ+nihhYFxO2pThz3C5qSu2Eg==", "integrity": "sha512-z+pdZyxE+RTQE9AcboAZCb4otwcrvgHD+GlBpPgn0emDVt0ohrTMhAwlr2Wd9nZ+nihhYFxO2pThz3C5qSu2Eg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"undici-types": "~7.21.0" "undici-types": "~7.21.0"
@@ -975,6 +1057,15 @@
"csstype": "^3.2.2" "csstype": "^3.2.2"
} }
}, },
"node_modules/@types/readable-stream": {
"version": "4.0.23",
"resolved": "https://registry.npmjs.org/@types/readable-stream/-/readable-stream-4.0.23.tgz",
"integrity": "sha512-wwXrtQvbMHxCbBgjHaMGEmImFTQxxpfMOR/ZoQnXxB1woqkUbdLGFDgauo00Py9IudiaqSeiBiulSV9i6XIPig==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/send": { "node_modules/@types/send": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
@@ -996,6 +1087,27 @@
"@types/node": "*" "@types/node": "*"
} }
}, },
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/abort-controller": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
"integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
"license": "MIT",
"dependencies": {
"event-target-shim": "^5.0.0"
},
"engines": {
"node": ">=6.5"
}
},
"node_modules/accepts": { "node_modules/accepts": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
@@ -1121,6 +1233,18 @@
"url": "https://opencollective.com/express" "url": "https://opencollective.com/express"
} }
}, },
"node_modules/broker-factory": {
"version": "3.1.14",
"resolved": "https://registry.npmjs.org/broker-factory/-/broker-factory-3.1.14.tgz",
"integrity": "sha512-L45k5HMbPIrMid0nTOZ/UPXG/c0aRuQKVrSDFIb1zOkvfiyHgYmIjc3cSiN1KwQIvRDOtKE0tfb3I9EZ3CmpQQ==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.2",
"fast-unique-numbers": "^9.0.27",
"tslib": "^2.8.1",
"worker-factory": "^7.0.49"
}
},
"node_modules/buffer": { "node_modules/buffer": {
"version": "5.7.1", "version": "5.7.1",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
@@ -1145,6 +1269,12 @@
"ieee754": "^1.1.13" "ieee754": "^1.1.13"
} }
}, },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/bytes": { "node_modules/bytes": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -1247,6 +1377,36 @@
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/cluster-key-slot": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
"integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/commist": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/commist/-/commist-3.2.0.tgz",
"integrity": "sha512-4PIMoPniho+LqXmpS5d3NuGYncG6XWlkBSVGiWycL22dd42OYdUGil2CWuzklaJoNxyxUSpO4MKIBU94viWNAw==",
"license": "MIT"
},
"node_modules/concat-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"engines": [
"node >= 6.0"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
},
"node_modules/confbox": { "node_modules/confbox": {
"version": "0.2.4", "version": "0.2.4",
"resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz",
@@ -1581,6 +1741,24 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/events": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
"integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
"license": "MIT",
"engines": {
"node": ">=0.8.x"
}
},
"node_modules/expand-template": { "node_modules/expand-template": {
"version": "2.0.3", "version": "2.0.3",
"resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
@@ -1670,6 +1848,19 @@
"devOptional": true, "devOptional": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/fast-unique-numbers": {
"version": "9.0.27",
"resolved": "https://registry.npmjs.org/fast-unique-numbers/-/fast-unique-numbers-9.0.27.tgz",
"integrity": "sha512-nDA9ADeINN8SA2u2wCtU+siWFTTDqQR37XvgPIDDmboWQeExz7X0mImxuaN+kJddliIqy2FpVRmnvRZ+j8i1/A==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.2",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=18.2.0"
}
},
"node_modules/fast-uri": { "node_modules/fast-uri": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
@@ -1919,6 +2110,12 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/help-me": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz",
"integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==",
"license": "MIT"
},
"node_modules/hono": { "node_modules/hono": {
"version": "4.12.18", "version": "4.12.18",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.18.tgz", "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.18.tgz",
@@ -2004,6 +2201,15 @@
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/ip-address": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
"license": "MIT",
"engines": {
"node": ">= 12"
}
},
"node_modules/ipaddr.js": { "node_modules/ipaddr.js": {
"version": "1.9.1", "version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
@@ -2043,6 +2249,16 @@
"jiti": "lib/jiti-cli.mjs" "jiti": "lib/jiti-cli.mjs"
} }
}, },
"node_modules/js-sdsl": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.3.0.tgz",
"integrity": "sha512-mifzlm2+5nZ+lEcLJMoBK0/IH/bDg8XnJfd/Wq6IP+xoCjLZsTOnV2QpxlVbX9bMnkl5PdEjNtBJ9Cj1NjifhQ==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/js-sdsl"
}
},
"node_modules/json-schema-traverse": { "node_modules/json-schema-traverse": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
@@ -2057,6 +2273,12 @@
"devOptional": true, "devOptional": true,
"license": "Apache-2.0" "license": "Apache-2.0"
}, },
"node_modules/lru-cache": {
"version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
"license": "ISC"
},
"node_modules/lru.min": { "node_modules/lru.min": {
"version": "1.1.4", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz", "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz",
@@ -2155,6 +2377,141 @@
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/mqtt": {
"version": "5.15.1",
"resolved": "https://registry.npmjs.org/mqtt/-/mqtt-5.15.1.tgz",
"integrity": "sha512-V1WnkGuJh3ec9QXzy5Iylw8OOBK+Xu1WhxcQ9mMpLThG+/JZIMV1PgLNRgIiqXhZnvnVLsuyxHl5A/3bHHbcAA==",
"license": "MIT",
"dependencies": {
"@types/readable-stream": "^4.0.21",
"@types/ws": "^8.18.1",
"commist": "^3.2.0",
"concat-stream": "^2.0.0",
"debug": "^4.4.1",
"help-me": "^5.0.0",
"lru-cache": "^10.4.3",
"minimist": "^1.2.8",
"mqtt-packet": "^9.0.2",
"number-allocator": "^1.0.14",
"readable-stream": "^4.7.0",
"rfdc": "^1.4.1",
"socks": "^2.8.6",
"split2": "^4.2.0",
"worker-timers": "^8.0.23",
"ws": "^8.18.3"
},
"bin": {
"mqtt": "build/bin/mqtt.js",
"mqtt_pub": "build/bin/pub.js",
"mqtt_sub": "build/bin/sub.js"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/mqtt-packet": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/mqtt-packet/-/mqtt-packet-9.0.2.tgz",
"integrity": "sha512-MvIY0B8/qjq7bKxdN1eD+nrljoeaai+qjLJgfRn3TiMuz0pamsIWY2bFODPZMSNmabsLANXsLl4EMoWvlaTZWA==",
"license": "MIT",
"dependencies": {
"bl": "^6.0.8",
"debug": "^4.3.4",
"process-nextick-args": "^2.0.1"
}
},
"node_modules/mqtt-packet/node_modules/bl": {
"version": "6.1.6",
"resolved": "https://registry.npmjs.org/bl/-/bl-6.1.6.tgz",
"integrity": "sha512-jLsPgN/YSvPUg9UX0Kd73CXpm2Psg9FxMeCSXnk3WBO3CMT10JMwijubhGfHCnFu6TPn1ei3b975dxv7K2pWVg==",
"license": "MIT",
"dependencies": {
"@types/readable-stream": "^4.0.0",
"buffer": "^6.0.3",
"inherits": "^2.0.4",
"readable-stream": "^4.2.0"
}
},
"node_modules/mqtt-packet/node_modules/buffer": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.2.1"
}
},
"node_modules/mqtt-packet/node_modules/readable-stream": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
"integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
"license": "MIT",
"dependencies": {
"abort-controller": "^3.0.0",
"buffer": "^6.0.3",
"events": "^3.3.0",
"process": "^0.11.10",
"string_decoder": "^1.3.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
},
"node_modules/mqtt/node_modules/buffer": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.2.1"
}
},
"node_modules/mqtt/node_modules/readable-stream": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
"integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
"license": "MIT",
"dependencies": {
"abort-controller": "^3.0.0",
"buffer": "^6.0.3",
"events": "^3.3.0",
"process": "^0.11.10",
"string_decoder": "^1.3.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.3", "version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -2222,6 +2579,16 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/number-allocator": {
"version": "1.0.14",
"resolved": "https://registry.npmjs.org/number-allocator/-/number-allocator-1.0.14.tgz",
"integrity": "sha512-OrL44UTVAvkKdOdRQZIJpLkAdjXGTRda052sN4sO77bKEzYYqWKMBjQvrJFzqygI99gL6Z4u2xctPW1tB8ErvA==",
"license": "MIT",
"dependencies": {
"debug": "^4.3.1",
"js-sdsl": "4.3.0"
}
},
"node_modules/object-inspect": { "node_modules/object-inspect": {
"version": "1.13.4", "version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
@@ -2392,6 +2759,21 @@
} }
} }
}, },
"node_modules/process": {
"version": "0.11.10",
"resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
"integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
"license": "MIT",
"engines": {
"node": ">= 0.6.0"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
"license": "MIT"
},
"node_modules/proper-lockfile": { "node_modules/proper-lockfile": {
"version": "4.1.2", "version": "4.1.2",
"resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
@@ -2569,6 +2951,22 @@
"url": "https://paulmillr.com/funding/" "url": "https://paulmillr.com/funding/"
} }
}, },
"node_modules/redis": {
"version": "5.12.1",
"resolved": "https://registry.npmjs.org/redis/-/redis-5.12.1.tgz",
"integrity": "sha512-LDsoVvb/CpoV9EN3FXvgvSHNJWuCIzl9MiO3ppOevuGLpSGJhwfQjpEwfFJcQvNSddHADDdZaWx0HnmMxRXG7g==",
"license": "MIT",
"dependencies": {
"@redis/bloom": "5.12.1",
"@redis/client": "5.12.1",
"@redis/json": "5.12.1",
"@redis/search": "5.12.1",
"@redis/time-series": "5.12.1"
},
"engines": {
"node": ">= 18.19.0"
}
},
"node_modules/remeda": { "node_modules/remeda": {
"version": "2.33.4", "version": "2.33.4",
"resolved": "https://registry.npmjs.org/remeda/-/remeda-2.33.4.tgz", "resolved": "https://registry.npmjs.org/remeda/-/remeda-2.33.4.tgz",
@@ -2609,6 +3007,12 @@
"node": ">= 4" "node": ">= 4"
} }
}, },
"node_modules/rfdc": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
"integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
"license": "MIT"
},
"node_modules/router": { "node_modules/router": {
"version": "2.2.0", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
@@ -2881,6 +3285,39 @@
"simple-concat": "^1.0.0" "simple-concat": "^1.0.0"
} }
}, },
"node_modules/smart-buffer": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
"integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
"license": "MIT",
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
}
},
"node_modules/socks": {
"version": "2.8.9",
"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz",
"integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==",
"license": "MIT",
"dependencies": {
"ip-address": "^10.1.1",
"smart-buffer": "^4.2.0"
},
"engines": {
"node": ">= 10.0.0",
"npm": ">= 3.0.0"
}
},
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"engines": {
"node": ">= 10.x"
}
},
"node_modules/sqlstring": { "node_modules/sqlstring": {
"version": "2.3.3", "version": "2.3.3",
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz", "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz",
@@ -2962,6 +3399,12 @@
"node": ">=0.6" "node": ">=0.6"
} }
}, },
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tsx": { "node_modules/tsx": {
"version": "4.21.0", "version": "4.21.0",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
@@ -3025,6 +3468,12 @@
"url": "https://opencollective.com/express" "url": "https://opencollective.com/express"
} }
}, },
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/typescript": { "node_modules/typescript": {
"version": "6.0.3", "version": "6.0.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
@@ -3043,7 +3492,6 @@
"version": "7.21.0", "version": "7.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.21.0.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.21.0.tgz",
"integrity": "sha512-w9IMgQrz4O0YN1LtB7K5P63vhlIOvC7opSmouCJ+ZywlPAlO9gIkJ+otk6LvGpAs2wg4econaCz3TvQ9xPoyuQ==", "integrity": "sha512-w9IMgQrz4O0YN1LtB7K5P63vhlIOvC7opSmouCJ+ZywlPAlO9gIkJ+otk6LvGpAs2wg4econaCz3TvQ9xPoyuQ==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/unpipe": { "node_modules/unpipe": {
@@ -3101,12 +3549,80 @@
"node": ">= 8" "node": ">= 8"
} }
}, },
"node_modules/worker-factory": {
"version": "7.0.49",
"resolved": "https://registry.npmjs.org/worker-factory/-/worker-factory-7.0.49.tgz",
"integrity": "sha512-lW7tpgy6aUv2dFsQhv1yv+XFzdkCf/leoKRTGMPVK5/die6RrUjqgJHJf556qO+ZfytNG6wPXc17E8zzsOLUDw==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.2",
"fast-unique-numbers": "^9.0.27",
"tslib": "^2.8.1"
}
},
"node_modules/worker-timers": {
"version": "8.0.31",
"resolved": "https://registry.npmjs.org/worker-timers/-/worker-timers-8.0.31.tgz",
"integrity": "sha512-ngkq5S6JuZyztom8tDgBzorLo9byhBMko/sXfgiUD945AuzKGg1GCgDMCC3NaYkicLpGKXutONM36wEX8UbBCA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.2",
"tslib": "^2.8.1",
"worker-timers-broker": "^8.0.16",
"worker-timers-worker": "^9.0.14"
}
},
"node_modules/worker-timers-broker": {
"version": "8.0.16",
"resolved": "https://registry.npmjs.org/worker-timers-broker/-/worker-timers-broker-8.0.16.tgz",
"integrity": "sha512-JyP3AvUGyPGbBGW7XiUewm2+0pN/aYo1QpVf5kdXAfkDZcN3p7NbWrG6XnyDEpDIvfHk/+LCnOW/NsuiU9riYA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.2",
"broker-factory": "^3.1.14",
"fast-unique-numbers": "^9.0.27",
"tslib": "^2.8.1",
"worker-timers-worker": "^9.0.14"
}
},
"node_modules/worker-timers-worker": {
"version": "9.0.14",
"resolved": "https://registry.npmjs.org/worker-timers-worker/-/worker-timers-worker-9.0.14.tgz",
"integrity": "sha512-/qF06C60sXmSLfUl7WglvrDIbspmPOM8UrG63Dnn4bi2x4/DfqHS/+dxF5B+MdHnYO5tVuZYLHdAodrKdabTIg==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.2",
"tslib": "^2.8.1",
"worker-factory": "^7.0.49"
}
},
"node_modules/wrappy": { "node_modules/wrappy": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/ws": {
"version": "8.21.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/zeptomatch": { "node_modules/zeptomatch": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/zeptomatch/-/zeptomatch-2.1.0.tgz", "resolved": "https://registry.npmjs.org/zeptomatch/-/zeptomatch-2.1.0.tgz",
+3 -1
View File
@@ -23,6 +23,8 @@
"@prisma/adapter-better-sqlite3": "^7.8.0", "@prisma/adapter-better-sqlite3": "^7.8.0",
"@prisma/client": "^7.8.0", "@prisma/client": "^7.8.0",
"dotenv": "^17.4.2", "dotenv": "^17.4.2",
"express": "^5.2.1" "express": "^5.2.1",
"mqtt": "^5.15.1",
"redis": "^5.12.1"
} }
} }
@@ -0,0 +1,20 @@
-- CreateTable
CREATE TABLE "Room" (
"id" TEXT NOT NULL PRIMARY KEY,
"nameame" TEXT NOT NULL
);
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_User" (
"id" TEXT NOT NULL PRIMARY KEY,
"firstName" TEXT NOT NULL,
"lastName" TEXT NOT NULL,
"faceEmbedding" BLOB
);
INSERT INTO "new_User" ("faceEmbedding", "firstName", "id", "lastName") SELECT "faceEmbedding", "firstName", "id", "lastName" FROM "User";
DROP TABLE "User";
ALTER TABLE "new_User" RENAME TO "User";
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;
@@ -0,0 +1,19 @@
/*
Warnings:
- You are about to drop the column `nameame` on the `Room` table. All the data in the column will be lost.
- Added the required column `name` to the `Room` table without a default value. This is not possible if the table is not empty.
*/
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_Room" (
"id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT NOT NULL
);
INSERT INTO "new_Room" ("id") SELECT "id" FROM "Room";
DROP TABLE "Room";
ALTER TABLE "new_Room" RENAME TO "Room";
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;
+5
View File
@@ -20,3 +20,8 @@ model Tag {
userId String @unique userId String @unique
user User @relation(fields: [userId], references: [id]) user User @relation(fields: [userId], references: [id])
} }
model Room {
id String @id @default(uuid())
name String
}
@@ -0,0 +1,10 @@
import express from "express";
import { getEntities, getEntitiesOfType, getEntity } from "./livedata.controller.js";
const router = express.Router();
router.get("/entities", getEntities);
router.get("/entities", getEntitiesOfType);
router.get("/entities/:urn", getEntity);
export default router;
@@ -0,0 +1,172 @@
import type { Request, Response, NextFunction } from "express";
import { getActiveUserData, getRedisRoomData, type RedisRoomData, type RedisUserData } from "./livedata.repository.js";
import { prisma } from "../../lib/prisma.js";
interface Params {
urn: string;
}
type Relationship = {
type: "Relationship";
object: string;
};
type Property<T = any> = {
type: "Property";
value: T;
};
interface Entity {
id: string;
type: string;
name: {
type: "Property";
value: string;
};
}
interface User extends Entity {
type: "User";
locatedIn: Relationship;
rssi: Property<number>;
authenticationStatus: Property<string>;
observedAt: Property<string>;
}
interface Room extends Entity {
type: "Room";
occupancy: Property<number>;
}
function convertToNGSIUser(user: RedisUserData): User {
return {
id: `urn:ngsi-ld:User:${user.userID}`,
type: "User",
name: {
type: "Property",
value: user.name
},
locatedIn: {
type: "Relationship",
object: user.room
},
rssi: {
type: "Property",
value: user.rssi,
},
authenticationStatus: {
type: "Property",
value: user.verified ? "verified" : "unverified"
},
observedAt: {
type: "Property",
value: (new Date(user.timestamp)).toISOString()
}
}
}
async function convertToNGSIRoom(room: RedisRoomData): Promise<Room | null> {
const roomName = await prisma.room.findUnique({
where: { id: room.roomID },
select: { name: true }
})
if (!roomName?.name) return null;
return {
id: `urn:ngsi-ld:Room:${room.roomID}`,
type: "Room",
name: {
type: "Property",
value: roomName.name
},
occupancy: {
type: "Property",
value: room.occupancy
}
}
}
async function getNGSIUsers(): Promise<User[]> {
let users: User[] = [];
const result: RedisUserData[] = await getActiveUserData();
for (const r of result) {
const user = convertToNGSIUser(r);
users.push(user);
}
return users;
}
async function getNGSIRooms(): Promise<Room[]> {
let rooms: Room[] = [];
const result: RedisRoomData[] = await getRedisRoomData();
for (const r of result) {
const room = await convertToNGSIRoom(r);
if (room == null) continue;
rooms.push(room);
}
return rooms;
}
export async function getEntities(req: Request, res: Response, next: NextFunction) {
if (Object.keys(req.query).length > 0) return next();
let entities: Entity[] = [];
entities.push(...await getNGSIUsers());
entities.push(...await getNGSIRooms());
return res.status(200).send(entities);
}
export async function getEntitiesOfType(req: Request, res: Response) {
const { type } = req.query;
switch (type) {
case "user": return res.status(200).send(await getNGSIUsers());
case "room": return res.status(200).send(await getNGSIRooms());
default:
return res.sendStatus(400);
}
}
export async function getEntity(req: Request<Params>, res: Response) {
const { urn } = req.params;
if (!urn || !urn.startsWith("urn:ngsi-ld:")) return res.sendStatus(400);
const entity = urn.slice(12);
if (!entity) return res.sendStatus(400);
if (entity.toLowerCase().startsWith("room:")) {
const roomID = entity.slice(5);
if (!roomID) return res.sendStatus(400);
const data = await getRedisRoomData(roomID);
if (!data.length) return res.sendStatus(404);
return res.status(200).send(await convertToNGSIRoom(data[0]!));
} else if (entity.toLowerCase().startsWith("user:")) {
const userID = entity.slice(5);
if (!userID) return res.sendStatus(400);
const data = await getActiveUserData(userID);
if (!data.length) return res.sendStatus(404);
return res.status(200).send(convertToNGSIUser(data[0]!));
} else
return res.sendStatus(400);
}
@@ -0,0 +1,106 @@
import { prisma } from "../../lib/prisma.js";
import { getRedis } from "../../redis/redis.js";
export interface RedisUserData {
userID: string;
name: string;
rssi: number;
room: string;
verified: boolean;
timestamp: number;
}
export interface RedisRoomData {
roomID: string;
occupancy: number;
}
export async function getActiveUserData(userID?: string): Promise<RedisUserData[]> {
const redis = getRedis();
if (!userID) {
let cursor = "0";
let result: RedisUserData[] = [];
do {
const res = await redis.scan(cursor, {
MATCH: "user:*",
COUNT: 100,
});
cursor = res.cursor;
const values = await Promise.all(
res.keys.map((key) => redis.get(key))
);
result.push(...values
.filter((v): v is string => v !== null)
.map((v) => JSON.parse(v))
);
} while (cursor !== "0");
return result;
}
const _userID = await redis.get(`_user:${userID}`);
if (!_userID) return [];
const res = await redis.get(`user:${_userID}`);
if (!res) return [];
const resObj: RedisUserData = JSON.parse(res);
return [resObj];
}
export async function getRedisRoomData(roomID?: string): Promise<RedisRoomData[]> {
const redis = getRedis();
if (!roomID) {
let cursor = "0";
let result: RedisRoomData[] = [];
do {
const res = await redis.scan(cursor, {
MATCH: "room:*",
COUNT: 100,
});
cursor = res.cursor;
const values = await Promise.all(
res.keys.map(async (key) => ({
roomID: key,
occupancy: await redis.get(key),
}))
);
result.push(...values
.filter((v) => v.occupancy !== null)
.map((v) => ({
roomID: v.roomID.slice(5),
occupancy: Number(v.occupancy),
}))
);
} while (cursor !== "0");
return result;
}
const res = await redis.get(`room:${roomID}`);
if (!res) return [];
return [{ roomID: roomID, occupancy: Number(res) }];
}
export async function getRoomIDs(): Promise<{ id: string; }[]> {
return await prisma.room.findMany({
select: { id: true }
});
}
@@ -1,9 +1,9 @@
import { prisma } from "../../lib/prisma.js"; import { prisma } from "../../lib/prisma.js";
export async function existsByUUID(uuid: string): Promise<boolean> { export async function existsByUUID(uuid: string): Promise<boolean> {
const user = await prisma.user.findUnique({ const tag = await prisma.tag.findUnique({
where: { id: uuid } where: { id: uuid }
}); });
return !!user; return !!tag;
} }
+57
View File
@@ -0,0 +1,57 @@
interface Config {
api: {
address: string;
port: number;
};
mqtt: {
host: string;
port: number;
username: string;
password: string;
topic: string;
};
redis: {
host: string;
port: number;
};
core: {
hysteresis: number;
candidateHysteresis: number;
debounceMS: number;
minSamples: number;
transitionTTL: number;
transitionCleanupInterval: number;
lossThreshold: number;
userTTL: number;
};
}
const config: Config = {
api: {
address: "0.0.0.0",
port: 80,
},
mqtt: {
host: "192.168.1.2",
port: 1883,
username: "user",
password: "pass",
topic: "scanners/+",
},
redis: {
host: "192.168.1.2",
port: 6379,
},
core: {
hysteresis: 6,
candidateHysteresis: 3,
debounceMS: 3000,
minSamples: 4,
transitionTTL: 5 * 60 * 1000,
transitionCleanupInterval: 60 * 1000,
lossThreshold: 5000,
userTTL: 3 * 60 * 1000
},
}
export default config;
+173
View File
@@ -0,0 +1,173 @@
import { getRedis } from "../redis/redis.js";
import { prisma } from "../lib/prisma.js";
import { RoomTransition, transitions } from "./transition.js";
import config from "../config/config.js";
import { type RedisUserData } from "../api/livedata/livedata.repository.js";
const adjectives = [
"Crazy",
"Silent",
"Dark",
"Fast",
"Lucky",
"Wild",
"Epic"
];
const nouns = [
"Tiger",
"Wolf",
"Falcon",
"Shadow",
"Ninja",
"Dragon",
"Phoenix"
];
const running = new Set<string>();
const userRooms = new Map<string, string>();
const userPseudo = new Map<string, string>();
export async function updateRoomOccupancyListener(message: string, channel: string) {
console.log(`[Redis] Key ${message} expired.`);
const id = message.startsWith("user:") ? message.slice(5) : message;
const lastRoomID = userRooms.get(id);
const userPseudoID = userPseudo.get(id);
const redis = getRedis();
if (!lastRoomID) {
console.log("[!] Key not found in local mapι")
} else {
await redis.decr(`room:${lastRoomID}`);
}
await redis.del(`_user:${userPseudoID}`);
userRooms.delete(id);
userPseudo.delete(id);
}
function generateNickname() {
const adjective =
adjectives[Math.floor(Math.random() * adjectives.length)];
const noun =
nouns[Math.floor(Math.random() * nouns.length)];
const number = Math.floor(Math.random() * 1000);
return `${adjective}${noun}${number}`;
}
function newUser(): { pseudoID: string, psuedoName: string } {
return {
pseudoID: crypto.randomUUID(),
psuedoName: generateNickname()
};
}
export async function analyzeData(roomID: string, metrics: {
tagID: string,
rssi: number
}) {
if (running.has(metrics.tagID)) {
console.log(`[!] Skipping TAG_ID: ${metrics.tagID} already in process.`);
return;
}
running.add(metrics.tagID);
try {
console.log(`\n=======================================================\n` +
`ROOM_ID: ${roomID}\nTAG_ID: ${metrics.tagID}\nRSSI: ${metrics.rssi}\n` +
`=======================================================\n`);
const userID = (
await prisma.tag.findUnique({
where: { id: metrics.tagID },
select: { userId: true },
})
)?.userId;
console.log(`[SQLite] Resolved USER_ID: ${userID}`);
if (!userID)
return;
const redis = getRedis();
const res = await redis.get(`user:${userID}`);
if (!res) {
const user = newUser();
console.log(`[Redis] Created USER: ${user.psuedoName} USER_ID: ${user.pseudoID}`);
// trigger camera
await redis.set(`user:${userID}`, JSON.stringify({
userID: user.pseudoID,
name: user.psuedoName,
rssi: metrics.rssi,
room: roomID,
verified: false,
timestamp: Date.now()
}), { PX: config.core.userTTL });
await redis.set(`_user:${user.pseudoID}`, userID);
await redis.incr(`room:${roomID}`);
userRooms.set(userID, roomID);
userPseudo.set(userID, user.pseudoID);
console.log("[Redis] Stored new user in redis.");
return;
}
let resObj: RedisUserData = JSON.parse(res);
console.log(`[Redis] User exists in redis in ROOM_ID: ${resObj["room"]}`);
if (roomID == resObj["room"]) {
console.log("[Redis] Same room, updating redis...");
resObj["rssi"] = metrics.rssi;
resObj["timestamp"] = Date.now()
await redis.set(`user:${userID}`, JSON.stringify(resObj), { PX: config.core.userTTL });
return;
}
let transition = transitions.get(userID);
// update room occupancy
if (!transition) {
console.log("[!] Starting new transition");
transition = new RoomTransition();
transitions.set(userID, transition);
}
if (transition.shouldTransitionTo(roomID, metrics.rssi, resObj["rssi"], resObj["timestamp"])) {
// trigger camera
console.log(`[!] Transition done ${resObj["room"]} -> ${roomID}`);
await redis.decr(`room:${resObj["room"]}`);
await redis.incr(`room:${roomID}`);
userRooms.set(userID, roomID);
resObj["rssi"] = metrics.rssi;
resObj["room"] = roomID;
resObj["timestamp"] = Date.now()
await redis.set(`user:${userID}`, JSON.stringify(resObj), { PX: config.core.userTTL });
} else
console.log("[!] Transition declined");
} finally {
running.delete(metrics.tagID);
}
}
+27
View File
@@ -0,0 +1,27 @@
import { getRoomIDs } from "../api/livedata/livedata.repository.js";
import { initRedis, initSubRedis } from "../redis/redis.js";
import * as mqtt from "./mqtt.js";
import { cleanupWorker } from "./transition.js";
export async function bootstrap() {
try {
const redis = await initRedis();
await redis.flushDb();
console.log(`[!] Flushed Redis.`);
const rooms = await getRoomIDs();
for (const { id } of rooms)
await redis.set(`room:${id}`, 0);
await initSubRedis();
await mqtt.start();
cleanupWorker();
console.log("[!] Core started.");
} catch (err: any) {
console.log("[!] Bootstrap failed:", err.message);
process.exit(1);
}
}
+48
View File
@@ -0,0 +1,48 @@
import mqtt, { MqttClient } from "mqtt";
import config from "../config/config.js";
import { analyzeData } from "./analyze.js";
function initMqtt(): Promise<MqttClient> {
return new Promise((resolve, reject) => {
const client = mqtt.connect(
`mqtt://${config.mqtt.host}:${config.mqtt.port}`,
{
username: config.mqtt.username,
password: config.mqtt.password
}
);
client.once("connect", () => {
console.log("[MQTT] MQTT connected.");
client.subscribe(config.mqtt.topic, (err) => {
if (err) {
reject(err);
} else {
console.log("[MQTT] MQTT subscribed.");
resolve(client);
}
});
});
client.once("error", (err) => {
reject(err);
});
});
}
export async function start() {
try {
const mqttClient = await initMqtt();
mqttClient.on("message", (topic, message) => {
analyzeData(topic.split("/").pop()!, JSON.parse(message.toString()));
});
mqttClient.on("error", (err) => {
console.log(err.message);
})
} catch (err: any) {
console.log("[MQTT] MQTT connection failed:", err.message);
}
}
+94
View File
@@ -0,0 +1,94 @@
import config from "../config/config.js";
export const transitions = new Map<string, RoomTransition>();
export function cleanupWorker() {
setInterval(() => {
const now = Date.now();
for (const [userID, transition] of transitions) {
const inactiveFor = now - transition.lastSeen;
if (inactiveFor > 5 * config.core.transitionTTL)
transitions.delete(userID);
}
}, config.core.transitionCleanupInterval);
}
type Candidate = {
roomID: string | null;
since: number | null;
samples: number;
rssi: number | null;
};
export class RoomTransition {
candidate: Candidate;
lastSeen: number;
constructor() {
this.lastSeen = Date.now();
this.candidate = { roomID: null, since: null, samples: 0, rssi: null };
}
shouldTransitionTo(roomID: string, candidateRSSI: number, currRSSI: number, lastCurrentSeen: number) {
const now = Date.now();
this.lastSeen = now;
const stronger = candidateRSSI > currRSSI + config.core.hysteresis;
const signalLost = now - lastCurrentSeen > config.core.lossThreshold;
console.log(`[TRANSITION] stronger = ${stronger}`);
console.log(`[TRANSITION] signalLost = ${signalLost}`);
if (!stronger && !signalLost) {
this.reset();
return false;
}
const noCandidate = this.candidate.roomID == null;
const betterCandidate = this.candidate.roomID != roomID &&
this.candidate.rssi !== null &&
candidateRSSI > this.candidate.rssi + config.core.candidateHysteresis;
console.log(`[TRANSITION] noCandidate = ${noCandidate}`);
console.log(`[TRANSITION] betterCandidate = ${betterCandidate}`);
if (noCandidate || betterCandidate) {
this.candidate.roomID = roomID;
this.candidate.since = now;
this.candidate.samples = 1;
this.candidate.rssi = candidateRSSI;
return false;
}
this.candidate.samples++;
this.candidate.rssi = candidateRSSI;
console.log(`[TRANSITION] samples = ${this.candidate.samples}`);
console.log(`[TRANSITION] candidateRSSI = ${this.candidate.rssi}`);
const enoughTime = now - (this.candidate.since ?? now) >= config.core.debounceMS;
const enoughConfirmations = this.candidate.samples >= config.core.minSamples;
console.log(`[TRANSITION] enoughTime = ${enoughTime}`);
console.log(`[TRANSITION] enoughConfirmations = ${enoughConfirmations}`);
console.log(`[TRANSITION] signalLost = ${signalLost}`);
if ((enoughTime && enoughConfirmations) || signalLost) {
this.reset();
return true;
}
return false;
}
reset() {
this.candidate.roomID = null;
this.candidate.since = null;
this.candidate.samples = 0;
this.candidate.rssi = null;
}
}
+14 -7
View File
@@ -1,12 +1,19 @@
import express from "express"; import express from "express";
import lookupRoutes from "./api/lookup/lookup.routes.js"; import lookupRoutes from "./api/lookup/lookup.routes.js";
import livedataRoutes from "./api/livedata/livadata.routes.js"
import config from "./config/config.js";
import { bootstrap } from "./core/bootstrap.js";
const app = express(); (async () => {
const PORT = 80; const app = express();
const ADDRESS = "0.0.0.0";
app.use("/", lookupRoutes); app.use("/lookup", lookupRoutes);
app.use("/livedata", livedataRoutes);
app.listen(PORT, ADDRESS, () => { app.listen(config.api.port, config.api.address, () => {
console.log(`Server listening on ${ADDRESS}:${PORT}`); console.log(`Server listening on ${config.api.address}:${config.api.port}`);
}); });
bootstrap();
})()
+48
View File
@@ -0,0 +1,48 @@
import { createClient, type RedisClientType } from "redis";
import config from "../config/config.js";
import { updateRoomOccupancyListener } from "../core/analyze.js";
let redisClient: RedisClientType;
let subRedisClient: RedisClientType;
export async function initSubRedis(): Promise<void> {
subRedisClient = createClient({
url: `redis://${config.redis.host}:${config.redis.port}`
});
subRedisClient.on("error", (err) => {
console.log("[Redis] SubRedis error:", err.message);
});
await subRedisClient.connect();
console.log("[Redis] SubRedis connected.");
subRedisClient.pSubscribe("__keyevent@0__:expired", updateRoomOccupancyListener);
console.log("[Redis] SubRedis listener set.");
}
export async function initRedis(): Promise<RedisClientType> {
redisClient = createClient({
url: `redis://${config.redis.host}:${config.redis.port}`
});
redisClient.on("error", (err) => {
console.log("[Redis] Redis error:", err.message);
});
await redisClient.connect();
console.log("[Redis] Redis connected.");
return redisClient;
}
export function getRedis(): RedisClientType {
if (!redisClient) {
throw new Error("[Redis] Redis not initialized");
}
return redisClient;
}
+1
View File
@@ -18,6 +18,7 @@ board_build.partitions = default.csv
build_flags = build_flags =
-DARDUINO_USB_CDC_ON_BOOT=1 -DARDUINO_USB_CDC_ON_BOOT=1
-DBOARD_HAS_PSRAM -DBOARD_HAS_PSRAM
-DCORE_DEBUG_LEVEL=0
lib_deps = lib_deps =
h2zero/NimBLE-Arduino h2zero/NimBLE-Arduino
+233 -24
View File
@@ -5,9 +5,14 @@
#include "freertos/queue.h" #include "freertos/queue.h"
#include <HTTPClient.h> #include <HTTPClient.h>
#include <PubSubClient.h> #include <PubSubClient.h>
#include <Preferences.h>
#include "esp_system.h"
Preferences prefs;
Config config;
CB cb; CB cb;
char MQTT_PUB_TOPIC[sizeof(MQTT_TOPIC) + sizeof(DEV_NAME) - 1]; String MQTT_PUB_TOPIC;
String serial_buffer = "";
std::unordered_map<std::string, Tag> tags; std::unordered_map<std::string, Tag> tags;
std::unordered_map<std::string, UUIDCacheEntry> uuid_cache; std::unordered_map<std::string, UUIDCacheEntry> uuid_cache;
SemaphoreHandle_t uuid_mtx; SemaphoreHandle_t uuid_mtx;
@@ -27,7 +32,7 @@ void cleanupCache()
{ {
uint32_t age = now - it->second.last_check; uint32_t age = now - it->second.last_check;
if (age > UUID_CACHE_CLEAN_TIMEOUT) if (age > config.interval.uuid_cache_clean_timeout)
{ {
Serial.printf("Erasing %s from cache after being inactive for %dms.\n", Serial.printf("Erasing %s from cache after being inactive for %dms.\n",
it->first.c_str(), it->first.c_str(),
@@ -47,7 +52,7 @@ void cleanupTags()
for (auto it = tags.begin(); it != tags.end();) for (auto it = tags.begin(); it != tags.end();)
{ {
if ((now - it->second.getLastSeen()) >= TAG_TIMEOUT) if ((now - it->second.getLastSeen()) >= config.interval.tag_timeout)
{ {
Serial.printf("Erasing %s from memory after being inactive for %dms.\n", Serial.printf("Erasing %s from memory after being inactive for %dms.\n",
it->first.c_str(), it->first.c_str(),
@@ -69,7 +74,7 @@ void httpTask(void *)
{ {
HTTPClient http; HTTPClient http;
String url = UUID_CHECK_ENDPOINT + String(ev.uuid); String url = config.api.url + config.api.uuid_check_endpoint + String("/") + String(ev.uuid);
http.setTimeout(3000); http.setTimeout(3000);
http.setReuse(false); http.setReuse(false);
@@ -82,6 +87,19 @@ void httpTask(void *)
int code = http.GET(); int code = http.GET();
if (code < 0)
{
xSemaphoreTake(uuid_mtx, portMAX_DELAY);
uuid_cache[ev.uuid] = {
UUIDState::RETRY,
millis()};
xSemaphoreGive(uuid_mtx);
http.end();
continue;
}
bool valid = (code == 200); bool valid = (code == 200);
http.end(); http.end();
@@ -110,8 +128,8 @@ void mqttTask(void *)
{ {
while (!mqtt.connected()) while (!mqtt.connected())
{ {
Serial.printf("MQTT Disconnected. Connecting to %s:%d\n", MQTT_HOST, MQTT_PORT); // Serial.printf("MQTT Disconnected. Connecting to %s:%d\n", config.mqtt.host.c_str(), config.mqtt.port);
if (mqtt.connect(DEV_NAME, MQTT_USER, MQTT_PASS)) if (mqtt.connect(config.dev_name.c_str(), config.mqtt.username.c_str(), config.mqtt.password.c_str()))
Serial.println("MQTT connected."); Serial.println("MQTT connected.");
vTaskDelay(pdMS_TO_TICKS(1000)); vTaskDelay(pdMS_TO_TICKS(1000));
} }
@@ -121,11 +139,11 @@ void mqttTask(void *)
char payload[128]; char payload[128];
snprintf(payload, sizeof(payload), snprintf(payload, sizeof(payload),
"{\"uuid\":\"%s\",\"rssi\":%.2f}", "{\"tagID\":\"%s\",\"rssi\":%.2f}",
ev.uuid, ev.uuid,
ev.ema); ev.ema);
bool ok = mqtt.publish(MQTT_PUB_TOPIC, payload); bool ok = mqtt.publish(MQTT_PUB_TOPIC.c_str(), payload);
if (!ok) if (!ok)
Serial.println("Failed to publish on MQTT."); Serial.println("Failed to publish on MQTT.");
@@ -143,7 +161,7 @@ void processEvent(const BleEvent &event)
uint32_t now = millis(); uint32_t now = millis();
if (it == uuid_cache.end()) if (it == uuid_cache.end() || (it->second.state == UUIDState::RETRY))
{ {
uuid_cache[event.uuid] = {UUIDState::PENDING, now}; uuid_cache[event.uuid] = {UUIDState::PENDING, now};
@@ -158,7 +176,7 @@ void processEvent(const BleEvent &event)
} }
if (it->second.state == UUIDState::INVALID && if (it->second.state == UUIDState::INVALID &&
now - it->second.last_check > UUID_CACHE_RETRY_TIMEOUT) now - it->second.last_check > config.interval.uuid_cache_retry_timeout)
{ {
it->second.state = UUIDState::PENDING; it->second.state = UUIDState::PENDING;
it->second.last_check = now; it->second.last_check = now;
@@ -202,9 +220,9 @@ void CB::onResult(const NimBLEAdvertisedDevice *d)
return; return;
NimBLEUUID uuid = d->getServiceUUID(0); NimBLEUUID uuid = d->getServiceUUID(0);
const std::string &name = d->getName(); const String name(d->getName().c_str());
if ((uuid.bitSize() != 128) || (name != TAG_NAME)) if ((uuid.bitSize() != 128) || (name != config.tag_name))
return; return;
BleEvent event; BleEvent event;
@@ -215,23 +233,179 @@ void CB::onResult(const NimBLEAdvertisedDevice *d)
xQueueSend(ble_queue, &event, pdMS_TO_TICKS(5)); xQueueSend(ble_queue, &event, pdMS_TO_TICKS(5));
} }
void saveConfig()
{
prefs.begin("config", false);
prefs.putUInt(CLEANUP_INTERVAL_CONFIG_KEY, config.interval.cleanup);
prefs.putUInt(TAG_TIMEOUT_CONFIG_KEY, config.interval.tag_timeout);
prefs.putUInt(UUID_CACHE_RETRY_TIMEOUT_CONFIG_KEY, config.interval.uuid_cache_retry_timeout);
prefs.putUInt(UUID_CACHE_CLEAN_TIMEOUT_CONFIG_KEY, config.interval.uuid_cache_clean_timeout);
prefs.putString(API_URL_CONFIG_KEY, config.api.url);
prefs.putString(UUID_CHECK_ENDPOINT_CONFIG_KEY, config.api.uuid_check_endpoint);
prefs.putString(MQTT_HOST_CONFIG_KEY, config.mqtt.host);
prefs.putUShort(MQTT_PORT_CONFIG_KEY, config.mqtt.port);
prefs.putString(MQTT_USER_CONFIG_KEY, config.mqtt.username);
prefs.putString(MQTT_PASS_CONFIG_KEY, config.mqtt.password);
prefs.putString(MQTT_TOPIC_CONFIG_KEY, config.mqtt.topic);
prefs.putString(WIFI_SSID_CONFIG_KEY, config.wifi.ssid);
prefs.putString(WIFI_PASS_CONFIG_KEY, config.wifi.password);
prefs.putString(DEV_NAME_CONFIG_KEY, config.dev_name);
prefs.putString(TAG_NAME_CONFIG_KEY, config.tag_name);
prefs.end();
}
void loadConfig()
{
prefs.begin("config", true);
config.interval.cleanup = prefs.getUInt(CLEANUP_INTERVAL_CONFIG_KEY, CLEANUP_INTERVAL);
config.interval.tag_timeout = prefs.getUInt(TAG_TIMEOUT_CONFIG_KEY, TAG_TIMEOUT);
config.interval.uuid_cache_retry_timeout = prefs.getUInt(UUID_CACHE_RETRY_TIMEOUT_CONFIG_KEY, UUID_CACHE_RETRY_TIMEOUT);
config.interval.uuid_cache_clean_timeout = prefs.getUInt(UUID_CACHE_CLEAN_TIMEOUT_CONFIG_KEY, UUID_CACHE_CLEAN_TIMEOUT);
config.api.url = prefs.getString(API_URL_CONFIG_KEY, API_URL);
config.api.uuid_check_endpoint = prefs.getString(UUID_CHECK_ENDPOINT_CONFIG_KEY, UUID_CHECK_ENDPOINT);
config.mqtt.host = prefs.getString(MQTT_HOST_CONFIG_KEY, MQTT_HOST);
config.mqtt.port = prefs.getUShort(MQTT_PORT_CONFIG_KEY, MQTT_PORT);
config.mqtt.username = prefs.getString(MQTT_USER_CONFIG_KEY, MQTT_USER);
config.mqtt.password = prefs.getString(MQTT_PASS_CONFIG_KEY, MQTT_PASS);
config.mqtt.topic = prefs.getString(MQTT_TOPIC_CONFIG_KEY, MQTT_TOPIC);
config.wifi.ssid = prefs.getString(WIFI_SSID_CONFIG_KEY, WIFI_SSID);
config.wifi.password = prefs.getString(WIFI_PASS_CONFIG_KEY, WIFI_PASS);
config.dev_name = prefs.getString(DEV_NAME_CONFIG_KEY, DEV_NAME);
config.tag_name = prefs.getString(TAG_NAME_CONFIG_KEY, TAG_NAME);
prefs.end();
}
void handleCommand(String line)
{
if (line.startsWith("set "))
{
int p1 = line.indexOf(' ', 4);
String key = line.substring(4, p1);
String value = line.substring(p1 + 1);
if (key.length() == 0 || value.length() == 0)
return;
if (key == CLEANUP_INTERVAL_CONFIG_KEY)
config.interval.cleanup = (uint32_t)value.toInt();
else if (key == TAG_TIMEOUT_CONFIG_KEY)
config.interval.tag_timeout = (uint32_t)value.toInt();
else if (key == UUID_CACHE_RETRY_TIMEOUT_CONFIG_KEY)
config.interval.uuid_cache_retry_timeout = (uint32_t)value.toInt();
else if (key == UUID_CACHE_CLEAN_TIMEOUT_CONFIG_KEY)
config.interval.uuid_cache_clean_timeout = (uint32_t)value.toInt();
else if (key == API_URL_CONFIG_KEY)
config.api.url = value;
else if (key == UUID_CHECK_ENDPOINT_CONFIG_KEY)
config.api.uuid_check_endpoint = value;
else if (key == MQTT_HOST_CONFIG_KEY)
config.mqtt.host = value;
else if (key == MQTT_PORT_CONFIG_KEY)
config.mqtt.port = value.toInt();
else if (key == MQTT_USER_CONFIG_KEY)
config.mqtt.username = value;
else if (key == MQTT_PASS_CONFIG_KEY)
config.mqtt.password = value;
else if (key == MQTT_TOPIC_CONFIG_KEY)
config.mqtt.topic = value;
else if (key == WIFI_SSID_CONFIG_KEY)
config.wifi.ssid = value;
else if (key == WIFI_PASS_CONFIG_KEY)
config.wifi.password = value;
else if (key == DEV_NAME_CONFIG_KEY)
config.dev_name = value;
else if (key == TAG_NAME_CONFIG_KEY)
config.tag_name = value;
}
else if (line == "save")
saveConfig();
else if (line.startsWith("show "))
{
String key = line.substring(5);
if (key.length() == 0)
return;
if (key == CLEANUP_INTERVAL_CONFIG_KEY)
Serial.println(config.interval.cleanup);
else if (key == TAG_TIMEOUT_CONFIG_KEY)
Serial.println(config.interval.tag_timeout);
else if (key == UUID_CACHE_RETRY_TIMEOUT_CONFIG_KEY)
Serial.println(config.interval.uuid_cache_retry_timeout);
else if (key == UUID_CACHE_CLEAN_TIMEOUT_CONFIG_KEY)
Serial.println(config.interval.uuid_cache_clean_timeout);
else if (key == API_URL_CONFIG_KEY)
Serial.println(config.api.url);
else if (key == UUID_CHECK_ENDPOINT_CONFIG_KEY)
Serial.println(config.api.uuid_check_endpoint);
else if (key == MQTT_HOST_CONFIG_KEY)
Serial.println(config.mqtt.host);
else if (key == MQTT_PORT_CONFIG_KEY)
Serial.println(config.mqtt.port);
else if (key == MQTT_USER_CONFIG_KEY)
Serial.println(config.mqtt.username);
else if (key == MQTT_PASS_CONFIG_KEY)
Serial.println(config.mqtt.password);
else if (key == MQTT_TOPIC_CONFIG_KEY)
Serial.println(config.mqtt.topic);
else if (key == WIFI_SSID_CONFIG_KEY)
Serial.println(config.wifi.ssid);
else if (key == WIFI_PASS_CONFIG_KEY)
Serial.println(config.wifi.password);
else if (key == DEV_NAME_CONFIG_KEY)
Serial.println(config.dev_name);
else if (key == TAG_NAME_CONFIG_KEY)
Serial.println(config.tag_name);
}
else if (line == "reset")
{
prefs.begin("config", false);
prefs.clear();
prefs.end();
esp_restart();
}
else if (line == "reboot")
{
Serial.println("Rebooting...");
Serial.flush();
esp_restart();
}
else if (line == "help")
{
Serial.println("Commands:");
Serial.println(" set <key> <value> - Set a configuration value");
Serial.println(" show <key> - Show a configuration value");
Serial.println(" save - Save configuration to non-volatile storage");
Serial.println(" reset - Reset configuration to defaults");
Serial.println(" reboot - Reboot the device");
Serial.println(" help - Show this help message");
}
}
void setup() void setup()
{ {
Serial.begin(115200); Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASS); loadConfig();
while (WiFi.status() != WL_CONNECTED) WiFi.begin(config.wifi.ssid.c_str(), config.wifi.password.c_str());
{
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected"); MQTT_PUB_TOPIC = config.mqtt.topic + config.dev_name;
snprintf(MQTT_PUB_TOPIC, sizeof(MQTT_PUB_TOPIC), "%s%s", MQTT_TOPIC, DEV_NAME); mqtt.setServer(config.mqtt.host.c_str(), config.mqtt.port);
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setKeepAlive(60); mqtt.setKeepAlive(60);
mqtt.setSocketTimeout(5); mqtt.setSocketTimeout(5);
@@ -244,7 +418,7 @@ void setup()
xTaskCreatePinnedToCore(mqttTask, "mqtt", 4096, NULL, 1, NULL, 1); xTaskCreatePinnedToCore(mqttTask, "mqtt", 4096, NULL, 1, NULL, 1);
xTaskCreatePinnedToCore(httpTask, "http", 4096, NULL, 1, NULL, 1); xTaskCreatePinnedToCore(httpTask, "http", 4096, NULL, 1, NULL, 1);
NimBLEDevice::init(DEV_NAME); NimBLEDevice::init(config.dev_name.c_str());
NimBLEScan *scan = NimBLEDevice::getScan(); NimBLEScan *scan = NimBLEDevice::getScan();
@@ -264,10 +438,45 @@ void loop()
static uint32_t last_cleanup = 0; static uint32_t last_cleanup = 0;
if (millis() - last_cleanup >= CLEANUP_INTERVAL) if (millis() - last_cleanup >= config.interval.cleanup)
{ {
cleanupTags(); cleanupTags();
cleanupCache(); cleanupCache();
last_cleanup = millis(); last_cleanup = millis();
} }
while (Serial.available())
{
char c = Serial.read();
if (c == '\r')
continue;
if (c == '\n')
{
Serial.print(c);
serial_buffer.trim();
if (serial_buffer.length() > 0)
handleCommand(serial_buffer);
serial_buffer = "";
Serial.printf("%s> ", config.dev_name.c_str());
}
else if (c == '\b')
{
if (serial_buffer.length() > 0)
{
serial_buffer.remove(serial_buffer.length() - 1);
Serial.print("\b \b");
}
}
else
{
Serial.print(c);
serial_buffer += c;
}
}
} }
+58 -5
View File
@@ -5,12 +5,29 @@
#include <NimBLEDevice.h> #include <NimBLEDevice.h>
#include <string> #include <string>
#define CLEANUP_INTERVAL 5 * 1000 // ms #define CLEANUP_INTERVAL_CONFIG_KEY "int.cln"
#define TAG_TIMEOUT 60 * 1000 // ms #define TAG_TIMEOUT_CONFIG_KEY "int.tagto"
#define UUID_CACHE_RETRY_TIMEOUT 5 * 60 * 1000 // ms #define UUID_CACHE_RETRY_TIMEOUT_CONFIG_KEY "int.urtry"
#define UUID_CACHE_CLEAN_TIMEOUT_CONFIG_KEY "int.ucclean"
#define API_URL_CONFIG_KEY "api.url"
#define UUID_CHECK_ENDPOINT_CONFIG_KEY "api.uuidchk"
#define MQTT_HOST_CONFIG_KEY "mq.host"
#define MQTT_PORT_CONFIG_KEY "mq.port"
#define MQTT_USER_CONFIG_KEY "mq.user"
#define MQTT_PASS_CONFIG_KEY "mq.pass"
#define MQTT_TOPIC_CONFIG_KEY "mq.topic"
#define WIFI_SSID_CONFIG_KEY "wf.ssid"
#define WIFI_PASS_CONFIG_KEY "wf.pass"
#define DEV_NAME_CONFIG_KEY "dev.name"
#define TAG_NAME_CONFIG_KEY "tag.name"
#define CLEANUP_INTERVAL 5 * 1000 // ms
#define TAG_TIMEOUT 60 * 1000 // ms
#define UUID_CACHE_RETRY_TIMEOUT 5 * 60 * 1000 // ms
#define UUID_CACHE_CLEAN_TIMEOUT 60 * 60 * 1000 // ms #define UUID_CACHE_CLEAN_TIMEOUT 60 * 60 * 1000 // ms
#define API_URL "http://192.168.1.2"
#define UUID_CHECK_ENDPOINT "/check"
#define TAG_NAME "X6TAG" #define TAG_NAME "X6TAG"
#define UUID_CHECK_ENDPOINT "http://192.168.1.2/check/"
#define MQTT_HOST "192.168.1.2" #define MQTT_HOST "192.168.1.2"
#define MQTT_PORT 1883 #define MQTT_PORT 1883
#define MQTT_USER "user" #define MQTT_USER "user"
@@ -18,7 +35,42 @@
#define MQTT_TOPIC "scanners/" #define MQTT_TOPIC "scanners/"
#define WIFI_SSID "COSMOTE-489882" #define WIFI_SSID "COSMOTE-489882"
#define WIFI_PASS "x32hbh54673ngccdsfa9" #define WIFI_PASS "x32hbh54673ngccdsfa9"
#define DEV_NAME "Scanner_Room_A" #define DEV_NAME "572b29cb-6a93-480e-adf0-c5c44e9a58df"
struct Config
{
struct Interval
{
uint32_t cleanup;
uint32_t tag_timeout;
uint32_t uuid_cache_retry_timeout;
uint32_t uuid_cache_clean_timeout;
} interval;
struct API
{
String url;
String uuid_check_endpoint;
} api;
struct MQTT
{
String host;
uint16_t port;
String username;
String password;
String topic;
} mqtt;
struct WiFi
{
String ssid;
String password;
} wifi;
String dev_name;
String tag_name;
};
struct BleEvent struct BleEvent
{ {
@@ -40,6 +92,7 @@ struct HttpEvent
enum class UUIDState enum class UUIDState
{ {
PENDING, PENDING,
RETRY,
VALID, VALID,
INVALID INVALID
}; };
+249 -22
View File
@@ -1,21 +1,13 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "nvs_flash.h" #include "nvs_flash.h"
#include "nimble/nimble_port.h" #include "nimble/nimble_port.h"
#include "nimble/nimble_port_freertos.h" #include "nimble/nimble_port_freertos.h"
#include "host/ble_hs.h"
#include "services/gap/ble_svc_gap.h" #include "services/gap/ble_svc_gap.h"
#include "driver/usb_serial_jtag.h"
#include "main.h"
static const char *TAG = "BLE"; static config_t config;
static const ble_uuid128_t service_uuid =
BLE_UUID128_INIT(
0xF0, 0xDE, 0xBC, 0x9A,
0x78, 0x56, 0x34, 0x12,
0xF0, 0xDE, 0xBC, 0x9A,
0x78, 0x56, 0x34, 0x12);
static void start_adv(void) static void start_adv(void)
{ {
@@ -24,19 +16,18 @@ static void start_adv(void)
fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP; fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
fields.uuids128 = (ble_uuid128_t *)&service_uuid; fields.name = (uint8_t *)config.name;
fields.name_len = strlen(config.name);
fields.name_is_complete = 1;
fields.uuids128 = (ble_uuid128_t *)&config.uuid;
fields.num_uuids128 = 1; fields.num_uuids128 = 1;
fields.uuids128_is_complete = 1; fields.uuids128_is_complete = 1;
uint8_t mfg_data[5] = {0x34, 0x34, 0x34, 0x34, 0x34};
fields.mfg_data = mfg_data;
fields.mfg_data_len = sizeof(mfg_data);
int rc = ble_gap_adv_set_fields(&fields); int rc = ble_gap_adv_set_fields(&fields);
if (rc != 0) if (rc != 0)
{ {
ESP_LOGE(TAG, "adv set fields failed: %d", rc); ESP_LOGE(config.name, "adv set fields failed: %d", rc);
return; return;
} }
@@ -58,17 +49,17 @@ static void start_adv(void)
if (rc != 0) if (rc != 0)
{ {
ESP_LOGE(TAG, "adv start failed: %d", rc); ESP_LOGE(config.name, "adv start failed: %d", rc);
} }
else else
{ {
ESP_LOGI(TAG, "advertising started"); ESP_LOGI(config.name, "advertising started");
} }
} }
static void on_sync(void) static void on_sync(void)
{ {
ESP_LOGI(TAG, "BLE synced"); ESP_LOGI(config.name, "BLE synced");
start_adv(); start_adv();
} }
@@ -78,15 +69,251 @@ static void host_task(void *param)
nimble_port_run(); nimble_port_run();
} }
static bool uuid_from_string(const char *str, ble_uuid128_t *uuid)
{
unsigned int b[16];
int rc = sscanf(str,
"%02x%02x%02x%02x-"
"%02x%02x-"
"%02x%02x-"
"%02x%02x-"
"%02x%02x%02x%02x%02x%02x",
&b[15], &b[14], &b[13], &b[12],
&b[11], &b[10],
&b[9], &b[8],
&b[7], &b[6],
&b[5], &b[4], &b[3],
&b[2], &b[1], &b[0]);
if (rc != 16)
return false;
uuid->u.type = BLE_UUID_TYPE_128;
for (int i = 0; i < 16; i++)
uuid->value[i] = (uint8_t)b[i];
return true;
}
static esp_err_t reset_config()
{
nvs_handle_t nvs;
esp_err_t err = nvs_open("config", NVS_READWRITE, &nvs);
if (err != ESP_OK)
return err;
err = nvs_erase_all(nvs);
if (err != ESP_OK)
goto exit;
err = nvs_commit(nvs);
exit:
nvs_close(nvs);
return err;
}
static esp_err_t save_config()
{
nvs_handle_t nvs;
esp_err_t err = nvs_open("config", NVS_READWRITE, &nvs);
if (err != ESP_OK)
return err;
err = nvs_set_str(nvs, "uuid", config.uuid_str);
if (err != ESP_OK)
goto exit;
err = nvs_set_str(nvs, "name", config.name);
if (err != ESP_OK)
goto exit;
err = nvs_set_u32(nvs, "adv_int", config.adv_interval);
if (err != ESP_OK)
goto exit;
err = nvs_commit(nvs);
exit:
nvs_close(nvs);
return err;
}
static esp_err_t load_config()
{
nvs_handle_t nvs;
esp_err_t err = nvs_open("config", NVS_READONLY, &nvs);
strcpy(config.uuid_str, DEFAULT_UUID);
strcpy(config.name, DEFAULT_NAME);
config.adv_interval = DEFAULT_ADV_INTERVAL;
uuid_from_string(config.uuid_str, &config.uuid);
if (err != ESP_OK)
return err;
size_t len;
len = sizeof(config.uuid_str);
nvs_get_str(nvs, "uuid", config.uuid_str, &len);
len = sizeof(config.name);
nvs_get_str(nvs, "name", config.name, &len);
nvs_get_u32(nvs, "adv_int", &config.adv_interval);
nvs_close(nvs);
uuid_from_string(config.uuid_str, &config.uuid);
return ESP_OK;
}
void serial_task(void *arg)
{
char line[128];
char buf[64];
int pos = 0;
while (1)
{
uint8_t ch;
int len = usb_serial_jtag_read_bytes(&ch, 1, portMAX_DELAY);
if (len > 0)
{
if (ch == '\n' || ch == '\r')
{
usb_serial_jtag_write_bytes("\n", 1, 20 / portTICK_PERIOD_MS);
line[pos] = '\0';
if (pos > 0)
{
if (strncmp(line, "set uuid ", 9) == 0)
{
if (uuid_from_string(line + 9, &config.uuid))
strcpy(config.uuid_str, line + 9);
}
else if (strncmp(line, "set name ", 9) == 0)
{
strncpy(config.name, line + 9, sizeof(config.name) - 1);
config.name[sizeof(config.name) - 1] = '\0';
}
else if (strncmp(line, "set adv_interval ", 17) == 0)
{
uint32_t interval = atoi(line + 17);
if (interval > 0)
config.adv_interval = interval;
}
else if (strcmp(line, "show uuid") == 0)
{
usb_serial_jtag_write_bytes(config.uuid_str, strlen(config.uuid_str), 20 / portTICK_PERIOD_MS);
usb_serial_jtag_write_bytes("\n", 1, 20 / portTICK_PERIOD_MS);
}
else if (strcmp(line, "show name") == 0)
{
usb_serial_jtag_write_bytes(config.name, strlen(config.name), 20 / portTICK_PERIOD_MS);
usb_serial_jtag_write_bytes("\n", 1, 20 / portTICK_PERIOD_MS);
}
else if (strcmp(line, "show adv_interval") == 0)
{
int len = snprintf(buf, sizeof(buf), "%lu\n", (unsigned long)config.adv_interval);
usb_serial_jtag_write_bytes(buf, len, 20 / portTICK_PERIOD_MS);
}
else if (strcmp(line, "save") == 0)
save_config();
else if (strcmp(line, "reset") == 0)
{
reset_config();
esp_restart();
}
else if (strcmp(line, "reboot") == 0)
{
usb_serial_jtag_write_bytes("Rebooting...\n", 13, 20 / portTICK_PERIOD_MS);
esp_restart();
}
else if (strcmp(line, "help") == 0)
{
usb_serial_jtag_write_bytes("Commands:\n"
" set uuid <uuid>\n"
" set name <name>\n"
" set adv_interval <ms>\n"
" show uuid\n"
" show name\n"
" show adv_interval\n"
" save\n"
" reset\n"
" reboot\n"
" help\n",
145, 20 / portTICK_PERIOD_MS);
}
}
pos = 0;
int len = snprintf(buf, sizeof(buf), "%s> ", config.name);
usb_serial_jtag_write_bytes(buf, len, 20 / portTICK_PERIOD_MS);
}
else if (ch == 0x08)
{
if (pos > 0)
{
pos--;
usb_serial_jtag_write_bytes("\b \b", 3, 20 / portTICK_PERIOD_MS);
}
}
else
{
if (pos < sizeof(line) - 1)
{
line[pos++] = ch;
usb_serial_jtag_write_bytes((char *)&ch, 1, 20 / portTICK_PERIOD_MS);
}
}
}
}
}
void app_main(void) void app_main(void)
{ {
ESP_ERROR_CHECK(nvs_flash_init()); ESP_ERROR_CHECK(nvs_flash_init());
usb_serial_jtag_driver_config_t cfg = USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT();
usb_serial_jtag_driver_install(&cfg);
load_config();
nimble_port_init(); nimble_port_init();
ble_svc_gap_init(); ble_svc_gap_init();
ble_svc_gap_device_name_set("XIAO_C6"); ble_svc_gap_device_name_set("X6TAG");
ble_hs_cfg.sync_cb = on_sync; ble_hs_cfg.sync_cb = on_sync;
xTaskCreate(
serial_task,
"serial_task",
4096,
NULL,
5,
NULL);
nimble_port_freertos_init(host_task); nimble_port_freertos_init(host_task);
} }
+18
View File
@@ -0,0 +1,18 @@
#ifndef MAIN_H
#define MAIN_H
#include "host/ble_hs.h"
#define DEFAULT_UUID "12345678-9abc-def0-1234-56789abcdef0"
#define DEFAULT_NAME "X6TAG"
#define DEFAULT_ADV_INTERVAL 0x80
typedef struct
{
ble_uuid128_t uuid;
char uuid_str[37];
char name[32];
uint32_t adv_interval;
} config_t;
#endif