dt-common-device 2.0.7 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/README.md +352 -98
  2. package/dist/alerts/Alert.model.d.ts +28 -0
  3. package/dist/alerts/Alert.model.js +222 -0
  4. package/dist/alerts/Alert.repository.d.ts +106 -0
  5. package/dist/alerts/Alert.repository.js +374 -0
  6. package/dist/alerts/Alert.service.d.ts +137 -0
  7. package/dist/alerts/Alert.service.js +476 -0
  8. package/dist/alerts/AlertBuilder.d.ts +87 -0
  9. package/dist/alerts/AlertBuilder.example.d.ts +11 -0
  10. package/dist/alerts/AlertBuilder.example.js +117 -0
  11. package/dist/alerts/AlertBuilder.js +185 -0
  12. package/dist/alerts/AlertService.example.d.ts +55 -0
  13. package/dist/alerts/AlertService.example.js +148 -0
  14. package/dist/alerts/alert.types.d.ts +57 -0
  15. package/dist/alerts/alert.types.js +22 -0
  16. package/dist/alerts/index.d.ts +3 -0
  17. package/dist/alerts/index.js +19 -0
  18. package/dist/config/config.d.ts +4 -4
  19. package/dist/config/config.js +3 -3
  20. package/dist/config/config.types.d.ts +19 -0
  21. package/dist/config/config.types.js +2 -0
  22. package/dist/connection/Connection.repository.d.ts +8 -0
  23. package/dist/connection/Connection.repository.js +92 -0
  24. package/dist/connection/Connection.service.d.ts +8 -0
  25. package/dist/connection/Connection.service.js +32 -0
  26. package/dist/connection/IConnection.d.ts +26 -0
  27. package/dist/connection/IConnection.js +14 -0
  28. package/dist/connection/index.d.ts +2 -0
  29. package/dist/connection/index.js +18 -0
  30. package/dist/device/cloud/entities/CloudDevice.d.ts +2 -2
  31. package/dist/device/cloud/entities/CloudDeviceService.d.ts +1 -1
  32. package/dist/device/cloud/entities/DeviceFactory.d.ts +1 -1
  33. package/dist/device/cloud/entities/DeviceFactory.js +1 -1
  34. package/dist/device/cloud/interface.d.ts +101 -0
  35. package/dist/device/cloud/interface.js +3 -0
  36. package/dist/device/cloud/interfaces/ICloudDeviceService.d.ts +1 -1
  37. package/dist/device/cloud/interfaces/IDeviceConnectionService.d.ts +7 -0
  38. package/dist/device/cloud/interfaces/IDeviceConnectionService.js +3 -0
  39. package/dist/device/cloud/interfaces/IDevicesService.d.ts +9 -0
  40. package/dist/device/cloud/interfaces/IDevicesService.js +2 -0
  41. package/dist/device/cloud/interfaces/IRawDevice.d.ts +1 -1
  42. package/dist/device/cloud/services/Device.service.d.ts +39 -0
  43. package/dist/device/cloud/services/Device.service.js +9 -0
  44. package/dist/device/cloud/services/DeviceCloudService.d.ts +42 -0
  45. package/dist/device/cloud/services/DeviceCloudService.js +59 -0
  46. package/dist/device/cloud/services/DeviceHub.service.d.ts +3 -0
  47. package/dist/device/cloud/services/DeviceHub.service.js +6 -0
  48. package/dist/device/cloud/services/Hub.service.d.ts +25 -0
  49. package/dist/device/cloud/services/Hub.service.js +9 -0
  50. package/dist/device/cloud/services/SmartThingsDeviceService.d.ts +38 -0
  51. package/dist/device/cloud/services/SmartThingsDeviceService.js +52 -0
  52. package/dist/device/index.d.ts +4 -0
  53. package/dist/device/index.js +20 -0
  54. package/dist/device/local/events/EventHandler.js +6 -6
  55. package/dist/device/local/events/Events.d.ts +12 -33
  56. package/dist/device/local/events/Events.js +12 -33
  57. package/dist/device/local/interface.d.ts +0 -0
  58. package/dist/device/local/interface.js +1 -0
  59. package/dist/device/local/interfaces/index.d.ts +2 -3
  60. package/dist/device/local/interfaces/index.js +2 -3
  61. package/dist/device/local/repository/Device.repository.js +3 -3
  62. package/dist/device/local/repository/Hub.repository.js +4 -4
  63. package/dist/device/local/repository/Schedule.repository.js +2 -2
  64. package/dist/device/local/services/Device.service.d.ts +2 -2
  65. package/dist/device/local/services/Device.service.js +1 -1
  66. package/dist/device/local/services/DeviceHub.service.d.ts +11 -0
  67. package/dist/device/local/services/DeviceHub.service.js +40 -0
  68. package/dist/device/local/services/index.d.ts +0 -4
  69. package/dist/device/local/services/index.js +0 -4
  70. package/dist/events/BaseEventHandler.d.ts +2 -2
  71. package/dist/events/BaseEventHandler.js +2 -2
  72. package/dist/events/BaseEventTransformer.d.ts +1 -1
  73. package/dist/events/BaseEventTransformer.js +1 -1
  74. package/dist/events/DeviceEventHandler.d.ts +1 -1
  75. package/dist/events/DeviceEventHandler.js +2 -2
  76. package/dist/events/EventHandler.js +1 -1
  77. package/dist/events/EventHandlerOrchestrator.js +1 -1
  78. package/dist/events/EventProcessingService.js +1 -1
  79. package/dist/events/InternalEventSubscription.js +1 -1
  80. package/dist/index.d.ts +7 -5
  81. package/dist/index.js +16 -13
  82. package/dist/issues/Issue.model.d.ts +28 -0
  83. package/dist/issues/Issue.model.js +260 -0
  84. package/dist/issues/Issue.repository.d.ts +113 -0
  85. package/dist/issues/Issue.repository.js +401 -0
  86. package/dist/issues/Issue.service.d.ts +168 -0
  87. package/dist/issues/Issue.service.js +642 -0
  88. package/dist/issues/IssueBuilder.d.ts +109 -0
  89. package/dist/issues/IssueBuilder.example.d.ts +16 -0
  90. package/dist/issues/IssueBuilder.example.js +196 -0
  91. package/dist/issues/IssueBuilder.js +237 -0
  92. package/dist/issues/IssueService.example.d.ts +68 -0
  93. package/dist/issues/IssueService.example.js +177 -0
  94. package/dist/issues/index.d.ts +2 -0
  95. package/dist/issues/index.js +18 -0
  96. package/dist/issues/issue.types.d.ts +90 -0
  97. package/dist/issues/issue.types.js +40 -0
  98. package/dist/property/IProperty.d.ts +29 -0
  99. package/dist/property/IProperty.js +2 -0
  100. package/dist/property/Property.repository.d.ts +8 -0
  101. package/dist/property/Property.repository.js +95 -0
  102. package/dist/property/Property.service.d.ts +8 -0
  103. package/dist/property/Property.service.js +36 -0
  104. package/dist/property/index.d.ts +2 -0
  105. package/dist/property/index.js +18 -0
  106. package/dist/queue/entities/HybridHttpQueue.d.ts +24 -0
  107. package/dist/queue/entities/HybridHttpQueue.js +241 -0
  108. package/dist/queue/entities/index.d.ts +1 -0
  109. package/dist/queue/entities/index.js +17 -0
  110. package/dist/queue/index.d.ts +5 -0
  111. package/dist/queue/index.js +22 -0
  112. package/dist/queue/interfaces/IHttpRequestJob.d.ts +9 -0
  113. package/dist/queue/interfaces/IHttpRequestJob.js +2 -0
  114. package/dist/queue/interfaces/IHybridHttpQueue.d.ts +17 -0
  115. package/dist/queue/interfaces/IHybridHttpQueue.js +2 -0
  116. package/dist/queue/interfaces/IJobResult.d.ts +14 -0
  117. package/dist/queue/interfaces/IJobResult.js +2 -0
  118. package/dist/queue/interfaces/IRateLimitConfig.d.ts +5 -0
  119. package/dist/queue/interfaces/IRateLimitConfig.js +2 -0
  120. package/dist/queue/interfaces/index.d.ts +4 -0
  121. package/dist/queue/interfaces/index.js +20 -0
  122. package/dist/queue/services/QueueService.d.ts +19 -0
  123. package/dist/queue/services/QueueService.js +73 -0
  124. package/dist/queue/services/index.d.ts +1 -0
  125. package/dist/queue/services/index.js +17 -0
  126. package/dist/queue/types/http.types.d.ts +21 -0
  127. package/dist/queue/types/http.types.js +2 -0
  128. package/dist/queue/types/index.d.ts +2 -0
  129. package/dist/queue/types/index.js +18 -0
  130. package/dist/queue/types/queue.types.d.ts +31 -0
  131. package/dist/queue/types/queue.types.js +2 -0
  132. package/dist/queue/utils/index.d.ts +3 -0
  133. package/dist/queue/utils/index.js +19 -0
  134. package/dist/queue/utils/jobUtils.d.ts +10 -0
  135. package/dist/queue/utils/jobUtils.js +64 -0
  136. package/dist/queue/utils/queueUtils.d.ts +5 -0
  137. package/dist/queue/utils/queueUtils.js +60 -0
  138. package/dist/queue/utils/rateLimit.utils.d.ts +10 -0
  139. package/dist/queue/utils/rateLimit.utils.js +97 -0
  140. package/package.json +2 -1
  141. package/src/{device/local/models → alerts}/Alert.model.ts +1 -1
  142. package/src/{device/local/repository → alerts}/Alert.repository.ts +2 -2
  143. package/src/{device/local/services → alerts}/Alert.service.ts +14 -7
  144. package/src/{device/local/entities → alerts}/AlertBuilder.example.ts +2 -2
  145. package/src/{device/local/entities → alerts}/AlertBuilder.ts +14 -8
  146. package/src/{device/local/services → alerts}/AlertService.example.ts +6 -5
  147. package/src/{types → alerts}/alert.types.ts +2 -2
  148. package/src/alerts/index.ts +3 -0
  149. package/src/config/config.ts +7 -7
  150. package/src/{types → config}/config.types.ts +1 -1
  151. package/src/{device/local/repository → connection}/Connection.repository.ts +2 -2
  152. package/src/{device/local/services → connection}/Connection.service.ts +2 -2
  153. package/src/connection/index.ts +3 -0
  154. package/src/device/cloud/entities/CloudDevice.ts +2 -2
  155. package/src/device/cloud/entities/CloudDeviceService.ts +1 -1
  156. package/src/device/cloud/entities/DeviceFactory.ts +2 -2
  157. package/src/device/cloud/interfaces/ICloudDeviceService.ts +1 -1
  158. package/src/device/cloud/interfaces/IRawDevice.ts +1 -1
  159. package/src/device/local/interfaces/index.ts +2 -3
  160. package/src/device/local/repository/Device.repository.ts +3 -3
  161. package/src/device/local/repository/Hub.repository.ts +4 -4
  162. package/src/device/local/repository/Schedule.repository.ts +2 -2
  163. package/src/device/local/services/Device.service.ts +1 -1
  164. package/src/device/local/services/index.ts +0 -4
  165. package/{TROUBLESHOOTING.md → src/docs/TROUBLESHOOTING.md} +2 -2
  166. package/src/events/BaseEventHandler.ts +3 -3
  167. package/src/events/BaseEventTransformer.ts +2 -2
  168. package/src/events/DeviceEventHandler.ts +3 -3
  169. package/src/events/EventHandler.ts +1 -1
  170. package/src/events/EventHandlerOrchestrator.ts +2 -2
  171. package/src/events/EventProcessingService.ts +2 -2
  172. package/src/events/InternalEventSubscription.ts +2 -2
  173. package/src/index.ts +19 -13
  174. package/src/{device/local/models → issues}/Issue.model.ts +1 -1
  175. package/src/{device/local/repository → issues}/Issue.repository.ts +2 -2
  176. package/src/{device/local/services → issues}/Issue.service.ts +4 -4
  177. package/src/{device/local/entities → issues}/IssueBuilder.example.ts +1 -1
  178. package/src/{device/local/entities → issues}/IssueBuilder.ts +1 -1
  179. package/src/{device/local/services → issues}/IssueService.example.ts +6 -5
  180. package/src/issues/index.ts +2 -0
  181. package/src/{device/local/repository → property}/Property.repository.ts +2 -2
  182. package/src/{device/local/services → property}/Property.service.ts +1 -1
  183. package/src/property/index.ts +2 -0
  184. package/src/queue/entities/HybridHttpQueue.ts +272 -0
  185. package/src/queue/entities/index.ts +1 -0
  186. package/src/queue/index.ts +6 -0
  187. package/src/queue/interfaces/IHttpRequestJob.ts +10 -0
  188. package/src/queue/interfaces/IHybridHttpQueue.ts +24 -0
  189. package/src/queue/interfaces/IJobResult.ts +15 -0
  190. package/src/queue/interfaces/IRateLimitConfig.ts +5 -0
  191. package/src/queue/interfaces/index.ts +4 -0
  192. package/src/queue/services/QueueService.ts +39 -0
  193. package/src/queue/services/index.ts +1 -0
  194. package/src/queue/types/http.types.ts +22 -0
  195. package/src/queue/types/index.ts +2 -0
  196. package/src/queue/types/queue.types.ts +21 -0
  197. package/src/queue/utils/index.ts +3 -0
  198. package/src/queue/utils/jobUtils.ts +80 -0
  199. package/src/queue/utils/queueUtils.ts +91 -0
  200. package/src/queue/utils/rateLimit.utils.ts +131 -0
  201. package/tsconfig.json +4 -0
  202. package/src/device/local/entities/README.md +0 -173
  203. package/src/device/local/entities/index.ts +0 -2
  204. package/src/types/index.ts +0 -3
  205. /package/src/{device/local/interfaces → connection}/IConnection.ts +0 -0
  206. /package/src/{device/local/models → docs}/Alert.model.md +0 -0
  207. /package/src/{device/local/models/README.md → docs/Alerts&IssuesModel.md} +0 -0
  208. /package/src/{device/local/models → docs}/Issue.model.md +0 -0
  209. /package/{SECURITY.md → src/docs/SECURITY.md} +0 -0
  210. /package/src/{types → issues}/issue.types.ts +0 -0
  211. /package/src/{device/local/interfaces → property}/IProperty.ts +0 -0
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dt-common-device
2
2
 
3
- A TypeScript library for device management, supporting both cloud and local device operations.
3
+ A comprehensive TypeScript library for device management, supporting both cloud and local device operations with advanced event handling, queue management, and audit logging.
4
4
 
5
5
  ## Installation
6
6
 
@@ -10,168 +10,350 @@ npm install dt-common-device
10
10
 
11
11
  ## Environment Variables Required
12
12
 
13
- **For audit logging to work (used in local device services), you must set the following environment variables in your application:**
13
+ **The following environment variables are REQUIRED for the library to function:**
14
14
 
15
- - `POSTHOG_API_KEY` — Your PostHog API key
16
- - `POSTHOG_HOST` — The PostHog host URL
15
+ ### AWS Configuration
16
+
17
+ - `AWS_SECRET_ACCESS_KEY` — Your AWS secret access key
18
+ - `AWS_REGION` — Your AWS region
19
+ - `AWS_ACCESS_KEY_ID` — Your AWS access key ID
20
+ - `EVENT_BUS_NAME` — Your AWS EventBridge event bus name
21
+
22
+ ### Database Configuration
17
23
 
18
- **You do NOT need to call `initializeAudit()` yourself.**
24
+ - `ADMIN_DB_URI` PostgreSQL database connection URI
25
+ - `MONGODB_URI` — MongoDB database connection URI
19
26
 
20
- - `dt-common-device` will automatically initialize audit logging using these environment variables when you create a local device service.
21
- - If either variable is missing, the library will throw a clear error at runtime.
27
+ ### Redis Configuration
22
28
 
23
- ## Environment Variables
29
+ - `REDIS_HOST` — Redis server host
30
+ - `REDIS_PORT` — Redis server port
31
+
32
+ ### Audit Logging
33
+
34
+ - `POSTHOG_API_KEY` — Your PostHog API key
35
+ - `POSTHOG_HOST` — The PostHog host URL
24
36
 
25
- This library requires the following environment variable to be set in your project's environment or in a `.env` file:
37
+ ### SQS Configuration
26
38
 
27
- - `POSTGRESQL_DB_URI`: The connection URI for your PostgreSQL database.
39
+ - `SQS_QUEUE_URL` AWS SQS queue URL (configured during initialization)
28
40
 
29
41
  Example `.env` file:
30
42
 
31
43
  ```
32
- POSTGRESQL_DB_URI=postgres://username:password@host:port/database
44
+ # AWS Configuration
45
+ AWS_SECRET_ACCESS_KEY=your_secret_key
46
+ AWS_REGION=us-east-1
47
+ AWS_ACCESS_KEY_ID=your_access_key
48
+ EVENT_BUS_NAME=your-event-bus
49
+
50
+ # Database Configuration
51
+ ADMIN_DB_URI=postgres://username:password@host:port/database
52
+ MONGODB_URI=mongodb://username:password@host:port/database
53
+
54
+ # Redis Configuration
55
+ REDIS_HOST=localhost
56
+ REDIS_PORT=6379
57
+
58
+ # Audit Logging
59
+ POSTHOG_API_KEY=your_posthog_key
60
+ POSTHOG_HOST=https://app.posthog.com
61
+
62
+ # SQS Configuration (will be set during initialization)
63
+ SQS_QUEUE_URL=https://sqs.region.amazonaws.com/account/queue-name
33
64
  ```
34
65
 
35
- The library will throw an error if this variable is not set when attempting to connect to the database.
66
+ The library will throw clear errors if any required environment variables are missing.
36
67
 
37
68
  ---
38
69
 
39
70
  ## Initialization (Required)
40
71
 
41
- Before using any service, you **must** call `initialize()` in your main entry file:
72
+ Before using any service, you **must** call `initialize()` in your main entry file with the required configuration:
42
73
 
43
74
  ```ts
44
75
  import { initialize } from "dt-common-device";
45
76
 
46
- initialize({
47
- DEVICE_SERVICE: "https://api.example.com/device",
48
- ADMIN_SERVICE: "https://api.example.com/admin",
49
- OPERATIONAL_SERVICE: "https://api.example.com/ops",
50
- MONITORING_SERVICE: "https://api.example.com/monitor",
51
- // ...other config as needed
77
+ // Create a logger instance
78
+ const logger = {
79
+ info: (message: string, ...args: any[]) => console.log(message, ...args),
80
+ warn: (message: string, ...args: any[]) => console.warn(message, ...args),
81
+ error: (message: string, ...args: any[]) => console.error(message, ...args),
82
+ };
83
+
84
+ // Initialize the library
85
+ await initialize({
86
+ SOURCE: "ADMIN_SERVICE", // or "ACCESS_SERVICE" or "ENERGY_SERVICE"
87
+ SQS_QUEUE_URL: "https://sqs.region.amazonaws.com/account/queue-name",
88
+ DEVICE_SERVICE: "https://api.example.com/device", // Optional
89
+ ADMIN_SERVICE: "https://api.example.com/admin", // Optional
90
+ ACCESS_SERVICE: "https://api.example.com/access", // Optional
91
+ ENERGY_SERVICE: "https://api.example.com/energy", // Optional
92
+ INTERNAL_EVENT_HANDLER: {
93
+ // Your event handler implementation
94
+ handleEvent: async (event) => {
95
+ // Handle internal events
96
+ console.log("Handling event:", event);
97
+ },
98
+ },
99
+ LOGGER: logger,
52
100
  });
53
101
  ```
54
102
 
55
- At least one service URL must be provided.
103
+ ### Configuration Options
104
+
105
+ - `SOURCE`: Required. Must be one of: `"ADMIN_SERVICE"`, `"ACCESS_SERVICE"`, or `"ENERGY_SERVICE"`
106
+ - `SQS_QUEUE_URL`: Required. Your AWS SQS queue URL
107
+ - `DEVICE_SERVICE`, `ADMIN_SERVICE`, `ACCESS_SERVICE`, `ENERGY_SERVICE`: Optional service URLs
108
+ - `INTERNAL_EVENT_HANDLER`: Required. Your event handler implementation
109
+ - `LOGGER`: Required. Logger instance with info, warn, and error methods
56
110
 
57
111
  ---
58
112
 
59
- ## Implementing Abstract Classes (Cloud Connection Example)
113
+ ## Available Services
114
+
115
+ ### Local Device Service
116
+
117
+ ```ts
118
+ import { LocalDeviceService } from "dt-common-device";
60
119
 
61
- This library provides abstract classes (such as `ConnectionService`) that define the required contract for cloud connection managers. **You should extend these abstract classes and implement all required methods.**
120
+ const deviceService = new LocalDeviceService();
62
121
 
63
- **You do NOT need to instantiate your class unless you want to use it in your application logic.**
122
+ // Create a device
123
+ const device = await deviceService.createDevice(deviceBody);
64
124
 
65
- ### Example: Implementing a Cloud Connection Service
125
+ // Get a device
126
+ const device = await deviceService.getDevice(deviceId);
127
+
128
+ // Get multiple devices
129
+ const devices = await deviceService.getDevices(deviceIds);
130
+
131
+ // Get devices by property
132
+ const propertyDevices = await deviceService.getPropertyDevices(propertyId);
133
+
134
+ // Update a device
135
+ await deviceService.updateDevice(deviceId, updateBody);
136
+
137
+ // Delete a device
138
+ await deviceService.deleteDevice(deviceId);
139
+
140
+ // State management
141
+ const state = await deviceService.getState(deviceId);
142
+ await deviceService.setState(deviceId, newState);
143
+
144
+ // Status management
145
+ const status = await deviceService.getStatus(deviceId);
146
+ await deviceService.setStatus(deviceId, newStatus);
147
+
148
+ // Battery management
149
+ const battery = await deviceService.getBatteryLevel(deviceId);
150
+ await deviceService.setBatteryLevel(deviceId, batteryLevel);
151
+
152
+ // Metadata management
153
+ const metadata = await deviceService.getMetaData(deviceId);
154
+ await deviceService.setMetaData(deviceId, metadata);
155
+
156
+ // Query operations
157
+ const devices = await deviceService.queryDevices(query);
158
+ const count = await deviceService.queryCount(query);
159
+ await deviceService.deleteDevices(query);
160
+ ```
161
+
162
+ ### Local Hub Service
66
163
 
67
164
  ```ts
68
- import {
69
- ConnectionService,
70
- IConnection,
71
- IDevice,
72
- IDeviceAccountResponse,
73
- IConnectionConnectParams,
74
- } from "dt-common-device";
165
+ import { LocalHubService } from "dt-common-device";
166
+
167
+ const hubService = new LocalHubService();
168
+
169
+ // Add a hub
170
+ const hub = await hubService.addHub(hubBody);
171
+
172
+ // Get hubs
173
+ const hubs = await hubService.getHubs(hubIds);
174
+
175
+ // Get a single hub
176
+ const hub = await hubService.getHub(hubId);
177
+
178
+ // Update a hub
179
+ await hubService.updateHub(hubId, updateBody);
180
+
181
+ // Get hub status
182
+ const status = await hubService.getStatus(hubId);
75
183
 
76
- class MyConnectionService extends ConnectionService {
77
- async createConnection(data: IConnection, userId: string): Promise<any> {
78
- // Your implementation
79
- }
80
-
81
- async getDeviceAccount(
82
- connection: IConnection
83
- ): Promise<IDeviceAccountResponse> {
84
- // Your implementation
85
- }
86
-
87
- async getDevices(connection: IConnection): Promise<IDevice[]> {
88
- // Your implementation
89
- }
90
-
91
- async filterDevices(
92
- connection: IConnection,
93
- devices: Record<string, any>[]
94
- ): Promise<IDevice[]> {
95
- // Your implementation
96
- }
97
-
98
- async connect(
99
- connection: IConnection,
100
- connectionConnect: IConnectionConnectParams
101
- ): Promise<any> {
102
- // Your implementation
103
- }
104
- }
105
- ```
106
-
107
- - TypeScript will enforce that you implement all required methods.
108
- - If you miss any, you will get a compile-time error.
109
- - You only need to instantiate your class if you want to use it in your application logic:
184
+ // Delete a hub
185
+ await hubService.deleteHub(hubId);
186
+
187
+ // Delete multiple hubs
188
+ await hubService.deleteAllHubs(hubIds);
189
+ ```
190
+
191
+ ### Local Schedule Service
110
192
 
111
193
  ```ts
112
- const myService = new MyConnectionService();
113
- myService.createConnection(...);
194
+ import { LocalScheduleService } from "dt-common-device";
195
+
196
+ const scheduleService = new LocalScheduleService();
197
+
198
+ // Get a schedule
199
+ const schedule = await scheduleService.getSchedule(scheduleId);
200
+
201
+ // Set a schedule
202
+ await scheduleService.setSchedule(scheduleId, schedule);
203
+
204
+ // Get schedule by zone
205
+ const zoneSchedule = await scheduleService.getScheduleByZone(zoneId);
114
206
  ```
115
207
 
116
- ---
208
+ ### Local Connection Service
209
+
210
+ ```ts
211
+ import { LocalConnectionService } from "dt-common-device";
117
212
 
118
- ## Importing Services
213
+ const connectionService = new LocalConnectionService();
214
+
215
+ // Create a connection
216
+ const connection = await connectionService.createConnection({
217
+ connectionName: "My Connection",
218
+ connectionRefId: "ref-123",
219
+ propertyId: "prop-456",
220
+ connectionProvider: "Sensibo",
221
+ });
222
+
223
+ // Get a connection
224
+ const connection = await connectionService.getConnection(connectionId);
225
+
226
+ // Update a connection
227
+ await connectionService.updateConnection(connectionId, updateData);
228
+ ```
119
229
 
120
230
  ### Cloud Device Service
121
231
 
122
232
  ```ts
123
- import { CloudDeviceService } from "dt-common-device";
233
+ import { CloudDeviceService, DeviceFactory } from "dt-common-device";
124
234
 
125
235
  const cloudService = new CloudDeviceService();
236
+ const deviceFactory = new DeviceFactory();
126
237
 
127
- // Example: get devices (must implement in your project)
238
+ // Get cloud devices (must implement in your project)
128
239
  // await cloudService.getDevices(connection);
240
+
241
+ // Get device using factory
242
+ const device = await deviceFactory.getDevice(deviceId);
129
243
  ```
130
244
 
131
- ### Local Device Service
245
+ ### Property Service
132
246
 
133
247
  ```ts
134
- import { LocalDeviceService } from "dt-common-device";
248
+ import { PropertyService } from "dt-common-device";
135
249
 
136
- const localService = new LocalDeviceService();
250
+ const propertyService = new PropertyService();
137
251
 
138
- // Create a device
139
- await localService.createDevice(deviceBody);
252
+ // Property operations (implementation specific)
253
+ // await propertyService.getProperty(propertyId);
254
+ ```
140
255
 
141
- // Get a device
142
- const device = await localService.getDevice(deviceId);
256
+ ---
143
257
 
144
- // Update a device
145
- await localService.updateDevice(deviceId, updateBody);
258
+ ## Event System
146
259
 
147
- // Delete a device
148
- await localService.deleteDevice(deviceId);
260
+ The library includes a comprehensive event handling system:
261
+
262
+ ```ts
263
+ import {
264
+ EventHandler,
265
+ EventProcessingService,
266
+ DeviceEventHandler,
267
+ EventHandlerOrchestrator,
268
+ } from "dt-common-device";
269
+
270
+ // Event handler for device operations
271
+ const eventHandler = new EventHandler();
272
+
273
+ // Device-specific event handler
274
+ const deviceEventHandler = new DeviceEventHandler();
275
+
276
+ // Event processing service
277
+ const eventProcessingService = new EventProcessingService();
278
+
279
+ // Event handler orchestrator
280
+ const orchestrator = new EventHandlerOrchestrator();
149
281
  ```
150
282
 
151
- ### Local Device Hub Service
283
+ ---
284
+
285
+ ## Queue System
286
+
287
+ The library provides a hybrid HTTP queue system for managing HTTP requests:
152
288
 
153
289
  ```ts
154
- import { LocalDeviceHubService } from "dt-common-device";
290
+ import { QueueService } from "dt-common-device";
291
+
292
+ const queueService = new QueueService();
293
+
294
+ // Make a rate-limited HTTP request
295
+ const response = await queueService.request({
296
+ method: "GET",
297
+ url: "https://api.example.com/data",
298
+ headers: { "Content-Type": "application/json" },
299
+ queueOptions: {
300
+ connectionId: "connection-123",
301
+ connectionProvider: "Sensibo",
302
+ microservice: "smart-energy",
303
+ },
304
+ });
305
+ ```
155
306
 
156
- const deviceHubService = new LocalDeviceHubService();
307
+ ### Features
157
308
 
158
- // Add a hub
159
- await deviceHubService.addHub(hubBody);
309
+ - **Rate Limiting**: Automatic rate limiting per provider and connection
310
+ - **Retry Logic**: Exponential backoff with configurable retry attempts
311
+ - **Audit Logging**: Automatic audit logging for all requests
312
+ - **Queue Management**: Redis-based queue with BullMQ
313
+ - **Error Handling**: Comprehensive error handling and logging
160
314
 
161
- // Get hubs
162
- const hubs = await deviceHubService.getHubs(hubIds);
315
+ ---
163
316
 
164
- // Get a single hub
165
- const hub = await deviceHubService.getHub(hubId);
317
+ ## Alert and Issue Management
166
318
 
167
- // Update a hub
168
- await deviceHubService.updateHub(hubId, updateBody);
319
+ ```ts
320
+ import {
321
+ AlertService,
322
+ IssueService,
323
+ AlertBuilder,
324
+ IssueBuilder,
325
+ } from "dt-common-device";
169
326
 
170
- // Delete a hub
171
- await deviceHubService.deleteHub(hubId);
327
+ // Alert service
328
+ const alertService = new AlertService();
329
+
330
+ // Issue service
331
+ const issueService = new IssueService();
332
+
333
+ // Build alerts
334
+ const alert = new AlertBuilder()
335
+ .setTitle("Device Offline")
336
+ .setDescription("Device has been offline for more than 24 hours")
337
+ .setSeverity("HIGH")
338
+ .build();
339
+
340
+ // Build issues
341
+ const issue = new IssueBuilder()
342
+ .setTitle("Connection Failed")
343
+ .setDescription("Failed to connect to device")
344
+ .setPriority("HIGH")
345
+ .build();
346
+ ```
172
347
 
173
- // Delete multiple hubs
174
- await deviceHubService.deleteAllHubs(hubIds);
348
+ ---
349
+
350
+ ## Graceful Shutdown
351
+
352
+ ```ts
353
+ import { shutdown } from "dt-common-device";
354
+
355
+ // Gracefully shutdown the library
356
+ await shutdown();
175
357
  ```
176
358
 
177
359
  ---
@@ -181,13 +363,85 @@ await deviceHubService.deleteAllHubs(hubIds);
181
363
  All types and interfaces are available as named exports:
182
364
 
183
365
  ```ts
184
- import { IDevice, IHub, IConnection } from "dt-common-device";
366
+ import {
367
+ IDevice,
368
+ IHub,
369
+ IConnection,
370
+ ISchedule,
371
+ IProperty,
372
+ IAlert,
373
+ IIssue,
374
+ } from "dt-common-device";
185
375
  ```
186
376
 
187
377
  ---
188
378
 
379
+ ## Dependencies
380
+
381
+ The library requires the following major dependencies:
382
+
383
+ - `axios`: HTTP client
384
+ - `bullmq`: Queue management
385
+ - `dt-audit-library`: Audit logging
386
+ - `dt-pub-sub`: Event publishing/subscribing
387
+ - `ioredis`: Redis client
388
+ - `mongoose`: MongoDB ODM
389
+ - `pg`: PostgreSQL client
390
+ - `typedi`: Dependency injection
391
+
392
+ ---
393
+
189
394
  ## Notes
190
395
 
191
396
  - You **must** call `initialize()` before using any service. If not, you will get a runtime error.
192
397
  - **You must set `POSTHOG_API_KEY` and `POSTHOG_HOST` in your environment before using any local device service.**
193
398
  - You do **not** need to call `initializeAudit()`
399
+
400
+ ## Rate Limiting
401
+
402
+ The queue system now implements intelligent rate limiting that delays requests instead of dropping them when rate limits are exceeded.
403
+
404
+ ### How it works
405
+
406
+ 1. **Rate Limit Check**: Before processing each HTTP request, the system checks if the rate limit for the provider/connection combination has been exceeded.
407
+
408
+ 2. **Delay Instead of Drop**: If the rate limit is exceeded, instead of immediately failing the request, the system:
409
+
410
+ - Calculates when the next request can be processed (after the rate limit window expires)
411
+ - Delays the job execution by the calculated time
412
+ - Re-checks the rate limit after the delay
413
+ - Only fails if still rate limited after the delay
414
+
415
+ 3. **Example Scenario**:
416
+
417
+ ```
418
+ Rate Limit: 5 requests per 60 seconds
419
+
420
+ Timeline:
421
+ 0s: Request 1 (processed immediately)
422
+ 10s: Request 2 (processed immediately)
423
+ 20s: Request 3 (processed immediately)
424
+ 30s: Request 4 (processed immediately)
425
+ 40s: Request 5 (processed immediately)
426
+ 45s: Request 6 (delayed by 15s, processed at 60s)
427
+ 50s: Request 7 (delayed by 10s, processed at 60s)
428
+ ```
429
+
430
+ ### Configuration
431
+
432
+ Rate limits are configured per provider in `src/queue/utils/rateLimit.utils.ts`:
433
+
434
+ ```typescript
435
+ configs.set("Sensibo", {
436
+ maxRequests: 5, // Maximum requests allowed
437
+ windowMs: 60000, // Time window in milliseconds
438
+ provider: "Sensibo",
439
+ });
440
+ ```
441
+
442
+ ### Benefits
443
+
444
+ - **No Lost Requests**: Requests are delayed rather than dropped
445
+ - **Automatic Recovery**: System automatically processes delayed requests when rate limits reset
446
+ - **Better User Experience**: Users don't see immediate failures due to rate limits
447
+ - **Audit Trail**: All rate limit events are logged for monitoring
@@ -0,0 +1,28 @@
1
+ import mongoose, { Model } from "mongoose";
2
+ import { AlertCategory, AlertSeverity, EntityType, AlertDocument as IAlertDocument, CreateAlertData, UpdateAlertData } from "./alert.types";
3
+ interface IAlertMethods {
4
+ markAsRead(updatedBy: string): void;
5
+ markAsUnread(updatedBy: string): void;
6
+ activate(updatedBy: string): void;
7
+ deactivate(updatedBy: string): void;
8
+ snooze(until: Date, updatedBy: string): void;
9
+ unsnooze(updatedBy: string): void;
10
+ }
11
+ interface IAlertModel extends Model<IAlertDocument, {}, IAlertMethods> {
12
+ findByProperty(propertyId: string, includeDeleted?: boolean): Promise<IAlertDocument[]>;
13
+ findByEntity(entityId: string, entityType: EntityType, includeDeleted?: boolean): Promise<IAlertDocument[]>;
14
+ findByCategory(category: AlertCategory, includeDeleted?: boolean): Promise<IAlertDocument[]>;
15
+ findBySeverity(severity: AlertSeverity, includeDeleted?: boolean): Promise<IAlertDocument[]>;
16
+ findActive(includeDeleted?: boolean): Promise<IAlertDocument[]>;
17
+ findUnread(includeDeleted?: boolean): Promise<IAlertDocument[]>;
18
+ findSnoozed(includeDeleted?: boolean): Promise<IAlertDocument[]>;
19
+ findExpiredSnooze(includeDeleted?: boolean): Promise<IAlertDocument[]>;
20
+ }
21
+ declare const AlertSchema: mongoose.Schema<IAlertDocument, IAlertModel, IAlertMethods, {}, {}, {}, mongoose.DefaultSchemaOptions, IAlertDocument, mongoose.Document<unknown, {}, mongoose.FlatRecord<IAlertDocument>, {}> & Omit<mongoose.FlatRecord<IAlertDocument> & Required<{
22
+ _id: string;
23
+ }> & {
24
+ __v: number;
25
+ }, keyof IAlertMethods> & IAlertMethods>;
26
+ export declare const AlertModel: IAlertModel;
27
+ export { AlertSchema };
28
+ export type { IAlertDocument, CreateAlertData, UpdateAlertData, IAlertMethods, IAlertModel, };