dt-common-device 3.1.1 → 3.1.2

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 (52) hide show
  1. package/dist/admin/Admin.repository.d.ts +7 -0
  2. package/dist/admin/Admin.repository.js +182 -0
  3. package/dist/admin/Admin.service.d.ts +5 -0
  4. package/dist/admin/Admin.service.js +17 -0
  5. package/dist/admin/index.d.ts +1 -0
  6. package/dist/{device → admin}/index.js +1 -4
  7. package/dist/audit/AuditProperties.d.ts +16 -0
  8. package/dist/audit/AuditUtils.d.ts +2 -0
  9. package/dist/audit/AuditUtils.js +36 -0
  10. package/dist/config/config.js +4 -0
  11. package/dist/config/config.types.d.ts +2 -0
  12. package/dist/device/cloud/entities/DeviceFactory.js +73 -14
  13. package/dist/device/local/events/EventHandler.js +6 -6
  14. package/dist/device/local/events/Events.d.ts +33 -12
  15. package/dist/device/local/events/Events.js +33 -12
  16. package/dist/device/local/services/Device.service.js +294 -239
  17. package/dist/device/local/services/Hub.service.js +92 -38
  18. package/dist/events/BaseEventHandler.js +6 -1
  19. package/dist/events/DeviceEventHandler.js +6 -1
  20. package/dist/events/EventHandler.js +158 -104
  21. package/dist/events/EventProcessingService.js +8 -3
  22. package/dist/index.d.ts +1 -0
  23. package/dist/index.js +2 -0
  24. package/dist/microservice/MicroServiceFactory.d.ts +1 -1
  25. package/dist/microservice/MicroServiceFactory.js +5 -3
  26. package/dist/property/Property.service.js +86 -27
  27. package/dist/queue/services/QueueService.js +6 -1
  28. package/dist/queue/utils/rateLimit.utils.js +9 -9
  29. package/dist/utils/http.utils.d.ts +2 -0
  30. package/dist/utils/http.utils.js +30 -0
  31. package/package.json +1 -1
  32. package/dist/device/cloud/interface.d.ts +0 -101
  33. package/dist/device/cloud/interface.js +0 -3
  34. package/dist/device/cloud/interfaces/IDeviceConnectionService.d.ts +0 -7
  35. package/dist/device/cloud/interfaces/IDeviceConnectionService.js +0 -3
  36. package/dist/device/cloud/interfaces/IDevicesService.d.ts +0 -9
  37. package/dist/device/cloud/services/Device.service.d.ts +0 -39
  38. package/dist/device/cloud/services/Device.service.js +0 -9
  39. package/dist/device/cloud/services/DeviceCloudService.d.ts +0 -42
  40. package/dist/device/cloud/services/DeviceCloudService.js +0 -59
  41. package/dist/device/cloud/services/DeviceHub.service.d.ts +0 -3
  42. package/dist/device/cloud/services/DeviceHub.service.js +0 -6
  43. package/dist/device/cloud/services/Hub.service.d.ts +0 -25
  44. package/dist/device/cloud/services/Hub.service.js +0 -9
  45. package/dist/device/cloud/services/SmartThingsDeviceService.d.ts +0 -38
  46. package/dist/device/cloud/services/SmartThingsDeviceService.js +0 -52
  47. package/dist/device/index.d.ts +0 -4
  48. package/dist/device/local/interface.d.ts +0 -0
  49. package/dist/device/local/interface.js +0 -1
  50. package/dist/device/local/services/DeviceHub.service.d.ts +0 -11
  51. package/dist/device/local/services/DeviceHub.service.js +0 -40
  52. /package/dist/{device/cloud/interfaces/IDevicesService.js → audit/AuditProperties.js} +0 -0
@@ -1,4 +1,42 @@
1
1
  "use strict";
2
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
4
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
6
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
7
+ var _, done = false;
8
+ for (var i = decorators.length - 1; i >= 0; i--) {
9
+ var context = {};
10
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
11
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
12
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
13
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
14
+ if (kind === "accessor") {
15
+ if (result === void 0) continue;
16
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
17
+ if (_ = accept(result.get)) descriptor.get = _;
18
+ if (_ = accept(result.set)) descriptor.set = _;
19
+ if (_ = accept(result.init)) initializers.unshift(_);
20
+ }
21
+ else if (_ = accept(result)) {
22
+ if (kind === "field") initializers.unshift(_);
23
+ else descriptor[key] = _;
24
+ }
25
+ }
26
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
27
+ done = true;
28
+ };
29
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
30
+ var useValue = arguments.length > 2;
31
+ for (var i = 0; i < initializers.length; i++) {
32
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
33
+ }
34
+ return useValue ? value : void 0;
35
+ };
36
+ var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
37
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
38
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
39
+ };
2
40
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
41
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
42
  };
@@ -11,161 +49,181 @@ const typedi_1 = __importDefault(require("typedi"));
11
49
  const Alert_service_1 = require("../../../alerts/Alert.service");
12
50
  const Issue_service_1 = require("../../../issues/Issue.service");
13
51
  const config_1 = require("../../../config/config");
14
- class LocalDeviceService {
15
- constructor() {
16
- this.eventHandler = new EventHandler_1.EventHandler();
17
- this.deviceRepository = typedi_1.default.get(Device_repository_1.DeviceRepository);
18
- this.alertService = typedi_1.default.get(Alert_service_1.AlertService);
19
- this.issueService = typedi_1.default.get(Issue_service_1.IssueService);
20
- this.logger = (0, config_1.getConfig)().LOGGER;
21
- }
22
- async createDevice(body) {
23
- const device = await this.deviceRepository.createDevice(body);
24
- await this.eventHandler.onDeviceCreate(device);
25
- return device;
26
- }
27
- async getDevice(deviceId, withHubDetails = false) {
28
- if (!deviceId) {
29
- throw new Error("Device ID is required");
52
+ const typedi_2 = require("typedi");
53
+ let LocalDeviceService = (() => {
54
+ let _classDecorators = [(0, typedi_2.Service)()];
55
+ let _classDescriptor;
56
+ let _classExtraInitializers = [];
57
+ let _classThis;
58
+ var LocalDeviceService = _classThis = class {
59
+ constructor() {
60
+ // Use dependency injection instead of creating new instances
61
+ this.eventHandler = typedi_1.default.get(EventHandler_1.EventHandler);
62
+ this.deviceRepository = typedi_1.default.get(Device_repository_1.DeviceRepository);
63
+ this.alertService = typedi_1.default.get(Alert_service_1.AlertService);
64
+ this.issueService = typedi_1.default.get(Issue_service_1.IssueService);
65
+ this.logger = (0, config_1.getConfig)().LOGGER;
30
66
  }
31
- return await this.deviceRepository.getDevice(deviceId, withHubDetails);
32
- }
33
- async getDevices(deviceIds, withHubDetails = false) {
34
- if (!deviceIds.length) {
35
- throw new Error("At least one device ID is required");
67
+ async createDevice(body) {
68
+ const device = await this.deviceRepository.createDevice(body);
69
+ await this.eventHandler.onDeviceCreate(device);
70
+ return device;
36
71
  }
37
- return await this.deviceRepository.getDevices(deviceIds, withHubDetails);
38
- }
39
- async getPropertyDevices(propertyId, selectDeviceId = false, type, withHubDetails = false) {
40
- if (!propertyId) {
41
- throw new Error("Property ID is required");
42
- }
43
- return await this.deviceRepository.getPropertyDevices(propertyId, selectDeviceId, type, withHubDetails);
44
- }
45
- async getPropertyDeviceIds(propertyId, selectDeviceId = false, type) {
46
- if (!propertyId) {
47
- throw new Error("Property ID is required");
48
- }
49
- return await this.deviceRepository.getPropertyDeviceIds(propertyId, selectDeviceId, type);
50
- }
51
- async updateDevice(deviceId, body) {
52
- if (!deviceId) {
53
- throw new Error("Device ID is required");
54
- }
55
- await this.deviceRepository.updateDevice(deviceId, body);
56
- return await this.eventHandler.onDeviceUpdate(deviceId, body);
57
- }
58
- async deleteDevice(deviceId) {
59
- if (!deviceId) {
60
- throw new Error("Device ID is required");
72
+ async getDevice(deviceId, withHubDetails = false) {
73
+ if (!deviceId) {
74
+ throw new Error("Device ID is required");
75
+ }
76
+ return await this.deviceRepository.getDevice(deviceId, withHubDetails);
61
77
  }
62
- await this.deviceRepository.deleteDevice(deviceId);
63
- return await this.eventHandler.onDeviceDelete(deviceId);
64
- }
65
- async getState(deviceId) {
66
- if (!deviceId) {
67
- throw new Error("Device ID is required");
78
+ async getDevices(deviceIds, withHubDetails = false) {
79
+ if (!deviceIds.length) {
80
+ throw new Error("At least one device ID is required");
81
+ }
82
+ return await this.deviceRepository.getDevices(deviceIds, withHubDetails);
68
83
  }
69
- return await this.deviceRepository.getState(deviceId);
70
- }
71
- async setState(deviceId, newState) {
72
- if (!deviceId || !newState) {
73
- throw new Error("Device ID and new state are required");
84
+ async getPropertyDevices(propertyId, selectDeviceId = false, type, withHubDetails = false) {
85
+ if (!propertyId) {
86
+ throw new Error("Property ID is required");
87
+ }
88
+ return await this.deviceRepository.getPropertyDevices(propertyId, selectDeviceId, type, withHubDetails);
74
89
  }
75
- // If old state and new state are different
76
- const oldState = (await this.getState(deviceId))?.data?.state ?? {};
77
- const changedKeys = Object.keys(newState).filter((key) => !(0, lodash_1.isEqual)(oldState[key], newState[key]));
78
- if (changedKeys.length > 0) {
79
- await this.deviceRepository.setState(deviceId, newState);
80
- return await this.eventHandler.onStateChange(deviceId, newState);
90
+ async getPropertyDeviceIds(propertyId, selectDeviceId = false, type) {
91
+ if (!propertyId) {
92
+ throw new Error("Property ID is required");
93
+ }
94
+ return await this.deviceRepository.getPropertyDeviceIds(propertyId, selectDeviceId, type);
81
95
  }
82
- }
83
- async getStatus(deviceId) {
84
- if (!deviceId) {
85
- throw new Error("Device ID is required");
96
+ async updateDevice(deviceId, body) {
97
+ if (!deviceId) {
98
+ throw new Error("Device ID is required");
99
+ }
100
+ await this.deviceRepository.updateDevice(deviceId, body);
101
+ return await this.eventHandler.onDeviceUpdate(deviceId, body);
86
102
  }
87
- return await this.deviceRepository.getStatus(deviceId);
88
- }
89
- async setStatus(deviceId, newStatus, source, reason) {
90
- if (!deviceId || !newStatus) {
91
- throw new Error("Device ID and new status are required");
103
+ async deleteDevice(deviceId) {
104
+ if (!deviceId) {
105
+ throw new Error("Device ID is required");
106
+ }
107
+ await this.deviceRepository.deleteDevice(deviceId);
108
+ return await this.eventHandler.onDeviceDelete(deviceId);
92
109
  }
93
- const device = await this.getDevice(deviceId);
94
- const oldStatus = device.status;
95
- const currentTime = new Date().toISOString();
96
- // Determine if the new status is ONLINE or OFFLINE
97
- const isNewStatusOnline = newStatus.liveStatus === "ONLINE";
98
- const isNewStatusOffline = newStatus.liveStatus === "OFFLINE";
99
- if (isNewStatusOffline) {
100
- // New Status = OFFLINE
101
- await this.handleOfflineStatus(deviceId, device, oldStatus, newStatus, source, reason, currentTime);
110
+ async getState(deviceId) {
111
+ if (!deviceId) {
112
+ throw new Error("Device ID is required");
113
+ }
114
+ return await this.deviceRepository.getState(deviceId);
102
115
  }
103
- else if (isNewStatusOnline) {
104
- // New Status = ONLINE
105
- await this.handleOnlineStatus(deviceId, device, oldStatus, newStatus, source, reason, currentTime);
116
+ async setState(deviceId, newState) {
117
+ if (!deviceId || !newState) {
118
+ throw new Error("Device ID and new state are required");
119
+ }
120
+ // If old state and new state are different
121
+ const oldState = (await this.getState(deviceId))?.data?.state ?? {};
122
+ const changedKeys = Object.keys(newState).filter((key) => !(0, lodash_1.isEqual)(oldState[key], newState[key]));
123
+ if (changedKeys.length > 0) {
124
+ await this.deviceRepository.setState(deviceId, newState);
125
+ return await this.eventHandler.onStateChange(deviceId, newState);
126
+ }
106
127
  }
107
- else {
108
- // For any other status, just update normally
109
- await this.deviceRepository.setStatus(deviceId, newStatus);
110
- await this.eventHandler.onStatusChange(deviceId, newStatus);
128
+ async getStatus(deviceId) {
129
+ if (!deviceId) {
130
+ throw new Error("Device ID is required");
131
+ }
132
+ return await this.deviceRepository.getStatus(deviceId);
111
133
  }
112
- }
113
- async handleOfflineStatus(deviceId, device, oldStatus, newStatus, source, reason, currentTime) {
114
- const isExistingStatusOnline = oldStatus?.online === true;
115
- const isExistingStatusOffline = oldStatus?.online === false;
116
- if (isExistingStatusOnline) {
117
- // Existing status is Online
118
- newStatus.online = true;
119
- newStatus.liveStatus = "OFFLINE";
120
- newStatus.lastUpdated = currentTime;
121
- newStatus.error = {
122
- type: "offline",
123
- message: reason || "Device went offline",
124
- default: {},
125
- };
126
- await this.deviceRepository.setStatus(deviceId, newStatus);
127
- await this.eventHandler.onStatusChange(deviceId, newStatus);
134
+ async setStatus(deviceId, newStatus, source, reason) {
135
+ if (!deviceId || !newStatus) {
136
+ throw new Error("Device ID and new status are required");
137
+ }
138
+ const device = await this.getDevice(deviceId);
139
+ const oldStatus = device.status;
140
+ const currentTime = new Date().toISOString();
141
+ // Determine if the new status is ONLINE or OFFLINE
142
+ const isNewStatusOnline = newStatus.liveStatus === "ONLINE";
143
+ const isNewStatusOffline = newStatus.liveStatus === "OFFLINE";
144
+ if (isNewStatusOffline) {
145
+ // New Status = OFFLINE
146
+ await this.handleOfflineStatus(deviceId, device, oldStatus, newStatus, source, reason, currentTime);
147
+ }
148
+ else if (isNewStatusOnline) {
149
+ // New Status = ONLINE
150
+ await this.handleOnlineStatus(deviceId, device, oldStatus, newStatus, source, reason, currentTime);
151
+ }
152
+ else {
153
+ // For any other status, just update normally
154
+ await this.deviceRepository.setStatus(deviceId, newStatus);
155
+ await this.eventHandler.onStatusChange(deviceId, newStatus);
156
+ }
128
157
  }
129
- else if (isExistingStatusOffline) {
130
- // Existing status is Offline
131
- const timeLapsed = oldStatus?.lastUpdated
132
- ? Date.now() - new Date(oldStatus.lastUpdated).getTime()
133
- : 0;
134
- const baselineTime = await this.getDeviceBaseline(deviceId);
135
- if (timeLapsed > baselineTime) {
136
- // When the time lapsed is higher than the baseline time
137
- newStatus.online = false;
158
+ async handleOfflineStatus(deviceId, device, oldStatus, newStatus, source, reason, currentTime) {
159
+ const isExistingStatusOnline = oldStatus?.online === true;
160
+ const isExistingStatusOffline = oldStatus?.online === false;
161
+ if (isExistingStatusOnline) {
162
+ // Existing status is Online
163
+ newStatus.online = true;
138
164
  newStatus.liveStatus = "OFFLINE";
139
165
  newStatus.lastUpdated = currentTime;
140
166
  newStatus.error = {
141
167
  type: "offline",
142
- message: reason || "Device has been offline for longer than baseline",
168
+ message: reason || "Device went offline",
143
169
  default: {},
144
170
  };
145
171
  await this.deviceRepository.setStatus(deviceId, newStatus);
146
172
  await this.eventHandler.onStatusChange(deviceId, newStatus);
147
- // Raise alert
148
- await this.alertService.raiseDeviceOfflineAlert(device, source, reason);
149
- // Raise issue when the device goes offline if longer than the baseline
150
- await this.issueService.createDeviceOfflineIssue(device, source, reason);
173
+ }
174
+ else if (isExistingStatusOffline) {
175
+ // Existing status is Offline
176
+ const timeLapsed = oldStatus?.lastUpdated
177
+ ? Date.now() - new Date(oldStatus.lastUpdated).getTime()
178
+ : 0;
179
+ const baselineTime = await this.getDeviceBaseline(deviceId);
180
+ if (timeLapsed > baselineTime) {
181
+ // When the time lapsed is higher than the baseline time
182
+ newStatus.online = false;
183
+ newStatus.liveStatus = "OFFLINE";
184
+ newStatus.lastUpdated = currentTime;
185
+ newStatus.error = {
186
+ type: "offline",
187
+ message: reason || "Device has been offline for longer than baseline",
188
+ default: {},
189
+ };
190
+ await this.deviceRepository.setStatus(deviceId, newStatus);
191
+ await this.eventHandler.onStatusChange(deviceId, newStatus);
192
+ // Raise alert
193
+ await this.alertService.raiseDeviceOfflineAlert(device, source, reason);
194
+ // Raise issue when the device goes offline if longer than the baseline
195
+ await this.issueService.createDeviceOfflineIssue(device, source, reason);
196
+ }
151
197
  }
152
198
  }
153
- }
154
- async handleOnlineStatus(deviceId, device, oldStatus, newStatus, source, reason, currentTime) {
155
- const isExistingStatusOnline = oldStatus?.online === true;
156
- const isExistingStatusOffline = oldStatus?.online === false;
157
- if (isExistingStatusOnline) {
158
- // Existing status is Online
159
- if (oldStatus?.liveStatus === "ONLINE") {
160
- // liveStatus = Online → Do nothing
161
- return;
199
+ async handleOnlineStatus(deviceId, device, oldStatus, newStatus, source, reason, currentTime) {
200
+ const isExistingStatusOnline = oldStatus?.online === true;
201
+ const isExistingStatusOffline = oldStatus?.online === false;
202
+ if (isExistingStatusOnline) {
203
+ // Existing status is Online
204
+ if (oldStatus?.liveStatus === "ONLINE") {
205
+ // liveStatus = Online → Do nothing
206
+ return;
207
+ }
208
+ else if (oldStatus?.liveStatus === "OFFLINE") {
209
+ // liveStatus = Offline → Follow the step #2 (same as existing status is Offline)
210
+ newStatus.online = true;
211
+ newStatus.liveStatus = "ONLINE";
212
+ newStatus.lastUpdated = currentTime;
213
+ newStatus.error = {}; // Clear the error
214
+ await this.deviceRepository.setStatus(deviceId, newStatus);
215
+ await this.eventHandler.onStatusChange(deviceId, newStatus);
216
+ //TODO: ALERT NEEDED?
217
+ // Raise alert
218
+ await this.alertService.raiseDeviceOnlineAlert(device, source, reason);
219
+ }
162
220
  }
163
- else if (oldStatus?.liveStatus === "OFFLINE") {
164
- // liveStatus = Offline → Follow the step #2 (same as existing status is Offline)
221
+ else if (isExistingStatusOffline) {
222
+ // Existing status is Offline
165
223
  newStatus.online = true;
166
224
  newStatus.liveStatus = "ONLINE";
167
225
  newStatus.lastUpdated = currentTime;
168
- newStatus.error = {}; // Clear the error
226
+ newStatus.error = undefined; // Clear the error
169
227
  await this.deviceRepository.setStatus(deviceId, newStatus);
170
228
  await this.eventHandler.onStatusChange(deviceId, newStatus);
171
229
  //TODO: ALERT NEEDED?
@@ -173,128 +231,125 @@ class LocalDeviceService {
173
231
  await this.alertService.raiseDeviceOnlineAlert(device, source, reason);
174
232
  }
175
233
  }
176
- else if (isExistingStatusOffline) {
177
- // Existing status is Offline
178
- newStatus.online = true;
179
- newStatus.liveStatus = "ONLINE";
180
- newStatus.lastUpdated = currentTime;
181
- newStatus.error = undefined; // Clear the error
182
- await this.deviceRepository.setStatus(deviceId, newStatus);
183
- await this.eventHandler.onStatusChange(deviceId, newStatus);
184
- //TODO: ALERT NEEDED?
185
- // Raise alert
186
- await this.alertService.raiseDeviceOnlineAlert(device, source, reason);
187
- }
188
- }
189
- async getDeviceBaseline(deviceId) {
190
- // TODO: Implement device baseline retrieval
191
- // This should return the baseline time in milliseconds for the specific device
192
- // For now, returning a default value of 5 minutes (300000ms)
193
- // In a real implementation, this would fetch from device configuration or settings
194
- return 3600000; // 1 hour in milliseconds
195
- }
196
- async getBatteryLevel(deviceId) {
197
- if (!deviceId) {
198
- throw new Error("Device ID is required");
234
+ async getDeviceBaseline(deviceId) {
235
+ // TODO: Implement device baseline retrieval
236
+ // This should return the baseline time in milliseconds for the specific device
237
+ // For now, returning a default value of 5 minutes (300000ms)
238
+ // In a real implementation, this would fetch from device configuration or settings
239
+ return 3600000; // 1 hour in milliseconds
199
240
  }
200
- return await this.deviceRepository.getBatteryLevel(deviceId);
201
- }
202
- async setBatteryLevel(deviceId, batteryLevel, source) {
203
- if (!deviceId || batteryLevel === undefined || batteryLevel === null) {
204
- throw new Error("Device ID and battery level are required");
241
+ async getBatteryLevel(deviceId) {
242
+ if (!deviceId) {
243
+ throw new Error("Device ID is required");
244
+ }
245
+ return await this.deviceRepository.getBatteryLevel(deviceId);
205
246
  }
206
- // Get device information
207
- const device = await this.getDevice(deviceId);
208
- // Fetch the old battery level state
209
- const oldBatteryLevel = device.state?.batteryPercentage;
210
- // Check if battery level has changed
211
- const isDifferent = !(0, lodash_1.isEqual)(oldBatteryLevel?.value, batteryLevel);
212
- if (isDifferent) {
213
- // Check if current time is greater than or equal to last updated time (8-hour logic)
214
- const shouldUpdate = this.shouldUpdateBatteryLevel(oldBatteryLevel?.lastUpdated);
215
- if (shouldUpdate) {
216
- // Save the battery level in the device
217
- await this.deviceRepository.setBatteryLevel(deviceId, batteryLevel);
218
- await this.eventHandler.onBatteryLevelChange(deviceId, batteryLevel);
219
- // Get property threshold
220
- const propertyThreshold = await this.getPropertyBatteryThreshold(device.propertyId);
221
- // Check if battery level is below threshold
222
- if (batteryLevel < propertyThreshold) {
223
- // Raise alert
224
- await this.alertService.raiseDeviceBatteryAlert(device, batteryLevel, propertyThreshold, source);
225
- // Raise issue when the level is below threshold
226
- await this.issueService.createDeviceBatteryIssue(device, batteryLevel, propertyThreshold, source);
247
+ async setBatteryLevel(deviceId, batteryLevel, source) {
248
+ if (!deviceId || batteryLevel === undefined || batteryLevel === null) {
249
+ throw new Error("Device ID and battery level are required");
250
+ }
251
+ // Get device information
252
+ const device = await this.getDevice(deviceId);
253
+ // Fetch the old battery level state
254
+ const oldBatteryLevel = device.state?.batteryPercentage;
255
+ // Check if battery level has changed
256
+ const isDifferent = !(0, lodash_1.isEqual)(oldBatteryLevel?.value, batteryLevel);
257
+ if (isDifferent) {
258
+ // Check if current time is greater than or equal to last updated time (8-hour logic)
259
+ const shouldUpdate = this.shouldUpdateBatteryLevel(oldBatteryLevel?.lastUpdated);
260
+ if (shouldUpdate) {
261
+ // Save the battery level in the device
262
+ await this.deviceRepository.setBatteryLevel(deviceId, batteryLevel);
263
+ await this.eventHandler.onBatteryLevelChange(deviceId, batteryLevel);
264
+ // Get property threshold
265
+ const propertyThreshold = await this.getPropertyBatteryThreshold(device.propertyId);
266
+ // Check if battery level is below threshold
267
+ if (batteryLevel < propertyThreshold) {
268
+ // Raise alert
269
+ await this.alertService.raiseDeviceBatteryAlert(device, batteryLevel, propertyThreshold, source);
270
+ // Raise issue when the level is below threshold
271
+ await this.issueService.createDeviceBatteryIssue(device, batteryLevel, propertyThreshold, source);
272
+ }
227
273
  }
228
274
  }
229
275
  }
230
- }
231
- shouldUpdateBatteryLevel(lastUpdated) {
232
- if (!lastUpdated) {
233
- return true; // No previous update, so we should update
276
+ shouldUpdateBatteryLevel(lastUpdated) {
277
+ if (!lastUpdated) {
278
+ return true; // No previous update, so we should update
279
+ }
280
+ const lastUpdateTime = new Date(lastUpdated).getTime();
281
+ const currentTime = Date.now();
282
+ const eightHoursInMs = 8 * 60 * 60 * 1000; // 8 hours in milliseconds
283
+ // Return true if current time is greater than or equal to last updated time + 8 hours
284
+ return currentTime >= lastUpdateTime + eightHoursInMs;
234
285
  }
235
- const lastUpdateTime = new Date(lastUpdated).getTime();
236
- const currentTime = Date.now();
237
- const eightHoursInMs = 8 * 60 * 60 * 1000; // 8 hours in milliseconds
238
- // Return true if current time is greater than or equal to last updated time + 8 hours
239
- return currentTime >= lastUpdateTime + eightHoursInMs;
240
- }
241
- async getPropertyBatteryThreshold(propertyId) {
242
- // TODO: Implement property battery threshold retrieval
243
- // This should return the battery threshold for the specific property
244
- // For now, returning a default value of 20%
245
- // In a real implementation, this would fetch from property configuration or settings
246
- return 20; // 20% default threshold
247
- }
248
- async getMetaData(deviceId) {
249
- if (!deviceId) {
250
- throw new Error("Device ID is required");
286
+ async getPropertyBatteryThreshold(propertyId) {
287
+ // TODO: Implement property battery threshold retrieval
288
+ // This should return the battery threshold for the specific property
289
+ // For now, returning a default value of 20%
290
+ // In a real implementation, this would fetch from property configuration or settings
291
+ return 20; // 20% default threshold
251
292
  }
252
- return await this.deviceRepository.getMetaData(deviceId);
253
- }
254
- async setMetaData(deviceId, metaData) {
255
- if (!deviceId || !metaData) {
256
- throw new Error("Device ID and meta data are required");
293
+ async getMetaData(deviceId) {
294
+ if (!deviceId) {
295
+ throw new Error("Device ID is required");
296
+ }
297
+ return await this.deviceRepository.getMetaData(deviceId);
257
298
  }
258
- await this.eventHandler.onDeviceMetaChange(deviceId, metaData);
259
- return await this.deviceRepository.setMetaData(deviceId, metaData);
260
- }
261
- async getDevicesByZone(zoneId) {
262
- if (!zoneId) {
263
- throw new Error("Zone ID is required");
299
+ async setMetaData(deviceId, metaData) {
300
+ if (!deviceId || !metaData) {
301
+ throw new Error("Device ID and meta data are required");
302
+ }
303
+ await this.eventHandler.onDeviceMetaChange(deviceId, metaData);
304
+ return await this.deviceRepository.setMetaData(deviceId, metaData);
264
305
  }
265
- return await this.deviceRepository.getDevicesByZone(zoneId);
266
- }
267
- async getDevicesByAccessGroup(accessGroupId) {
268
- if (!accessGroupId) {
269
- throw new Error("Access Group ID is required");
306
+ async getDevicesByZone(zoneId) {
307
+ if (!zoneId) {
308
+ throw new Error("Zone ID is required");
309
+ }
310
+ return await this.deviceRepository.getDevicesByZone(zoneId);
270
311
  }
271
- return await this.deviceRepository.getDevicesByAccessGroup(accessGroupId);
272
- }
273
- async querySelect(query, fields) {
274
- if (!query || Object.keys(query).length === 0) {
275
- throw new Error("Query is required");
312
+ async getDevicesByAccessGroup(accessGroupId) {
313
+ if (!accessGroupId) {
314
+ throw new Error("Access Group ID is required");
315
+ }
316
+ return await this.deviceRepository.getDevicesByAccessGroup(accessGroupId);
276
317
  }
277
- return await this.deviceRepository.querySelect(query, fields);
278
- }
279
- async queryCount(query) {
280
- if (!query || Object.keys(query).length === 0) {
281
- throw new Error("Query is required");
318
+ async querySelect(query, fields) {
319
+ if (!query || Object.keys(query).length === 0) {
320
+ throw new Error("Query is required");
321
+ }
322
+ return await this.deviceRepository.querySelect(query, fields);
282
323
  }
283
- const count = await this.deviceRepository.queryCount(query);
284
- return count;
285
- }
286
- async deleteDevices(query) {
287
- if (!query || Object.keys(query).length === 0) {
288
- throw new Error("Query is required");
324
+ async queryCount(query) {
325
+ if (!query || Object.keys(query).length === 0) {
326
+ throw new Error("Query is required");
327
+ }
328
+ const count = await this.deviceRepository.queryCount(query);
329
+ return count;
289
330
  }
290
- return await this.deviceRepository.deleteDevices(query);
291
- }
292
- async queryDevices(query) {
293
- if (!query || Object.keys(query).length === 0) {
294
- throw new Error("Query is required");
331
+ async deleteDevices(query) {
332
+ if (!query || Object.keys(query).length === 0) {
333
+ throw new Error("Query is required");
334
+ }
335
+ return await this.deviceRepository.deleteDevices(query);
295
336
  }
296
- const res = await this.deviceRepository.queryDevices(query);
297
- return res;
298
- }
299
- }
337
+ async queryDevices(query) {
338
+ if (!query || Object.keys(query).length === 0) {
339
+ throw new Error("Query is required");
340
+ }
341
+ const res = await this.deviceRepository.queryDevices(query);
342
+ return res;
343
+ }
344
+ };
345
+ __setFunctionName(_classThis, "LocalDeviceService");
346
+ (() => {
347
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
348
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
349
+ LocalDeviceService = _classThis = _classDescriptor.value;
350
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
351
+ __runInitializers(_classThis, _classExtraInitializers);
352
+ })();
353
+ return LocalDeviceService = _classThis;
354
+ })();
300
355
  exports.LocalDeviceService = LocalDeviceService;