Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## 1.8.75

- Bridge: Bridge가 시작될 때마다 상세 조회가 모든 기기의 SmartThings 페이지를 다시 열어, 시작 후 약 3시간 동안 Bridge CPU가 30~40%로 높던 문제를 수정했습니다(239대 기준 약 319회 조회). 조회가 끝나면 2~3%로 돌아왔습니다.
- Bridge: 기기 컨트롤은 저장된 인벤토리에서 복원되므로, 상세 컨트롤이 이미 완성된 기기는 다시 조회하지 않습니다.
- Bridge: 2회 조회해도 완성되지 않은 기기는 `/data/detail-discovery.json`(기기 id, 이름의 sha256, 시각)에 기록하고 재시작 후에도 7일 동안 또는 이름이 바뀔 때까지 다시 조회하지 않습니다. 카메라 이미지 기기는 지금처럼 매번 조회합니다. 파일이 없거나 손상되면 다시 조회합니다.
- 이 버전으로 처음 시작할 때는 아직 기록이 없어 미완성 기기를 한 번 더 조회합니다. 효과는 그다음 재시작부터 나타납니다.
- 이 변경은 Bridge 앱 업데이트가 필요합니다. Bridge 앱과 HACS 통합 버전은 1.8.75입니다. 통합 코드는 바뀌지 않았습니다.

## 1.8.74

- Bridge: 30분 주기 상태 재조정 때마다 Advanced 새로고침 버튼 컨트롤이 사라지던 문제를 수정했습니다. 재조정 스냅샷이 새로고침 버튼을 다시 만든 직후, 명령 카탈로그 반영 단계가 `advanced:`로 시작하는 컨트롤을 모두 지우고 스위치 토글만 되살렸습니다. 이제 카탈로그 반영은 자기가 만드는 스위치 토글만 교체합니다.
Expand Down
8 changes: 8 additions & 0 deletions addon/smartthings_web_bridge/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## 1.8.75

- Bridge: Bridge가 시작될 때마다 상세 조회가 모든 기기의 SmartThings 페이지를 다시 열어, 시작 후 약 3시간 동안 Bridge CPU가 30~40%로 높던 문제를 수정했습니다(239대 기준 약 319회 조회). 조회가 끝나면 2~3%로 돌아왔습니다.
- Bridge: 기기 컨트롤은 저장된 인벤토리에서 복원되므로, 상세 컨트롤이 이미 완성된 기기는 다시 조회하지 않습니다.
- Bridge: 2회 조회해도 완성되지 않은 기기는 `/data/detail-discovery.json`(기기 id, 이름의 sha256, 시각)에 기록하고 재시작 후에도 7일 동안 또는 이름이 바뀔 때까지 다시 조회하지 않습니다. 카메라 이미지 기기는 지금처럼 매번 조회합니다. 파일이 없거나 손상되면 다시 조회합니다.
- 이 버전으로 처음 시작할 때는 아직 기록이 없어 미완성 기기를 한 번 더 조회합니다. 효과는 그다음 재시작부터 나타납니다.
- 이 변경은 Bridge 앱 업데이트가 필요합니다. Bridge 앱과 HACS 통합 버전은 1.8.75입니다. 통합 코드는 바뀌지 않았습니다.

## 1.8.74

- Bridge: 30분 주기 상태 재조정 때마다 Advanced 새로고침 버튼 컨트롤이 사라지던 문제를 수정했습니다. 재조정 스냅샷이 새로고침 버튼을 다시 만든 직후, 명령 카탈로그 반영 단계가 `advanced:`로 시작하는 컨트롤을 모두 지우고 스위치 토글만 되살렸습니다. 이제 카탈로그 반영은 자기가 만드는 스위치 토글만 교체합니다.
Expand Down
2 changes: 1 addition & 1 deletion addon/smartthings_web_bridge/config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: SmartThings Web Bridge
slug: smartthings_web_bridge
description: Headed Chromium bridge for observing SmartThings Web traffic from Home Assistant.
version: 1.8.74
version: 1.8.75
url: https://github.com/1bobby-git/HA-SmartThings_Web
startup: services
boot: auto
Expand Down
59 changes: 57 additions & 2 deletions bridge/src/browser/device-detail-discovery.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { createHash } from "node:crypto";

import type {
DetailDiscoveryExhaustion,
DetailDiscoveryExhaustionStore
} from "../state/detail-discovery-store.js";
import type { BridgeDevice, BridgeInventory } from "../state/device-store.js";

/** How long an exhausted, still-incomplete device is left alone across restarts. */
export const DETAIL_DISCOVERY_EXHAUSTED_RETRY_MS = 7 * 24 * 60 * 60 * 1_000;

interface DeviceDetailInspector {
inspectDeviceDetails(input: {
deviceName: string;
Expand All @@ -17,6 +26,8 @@ interface DeviceDetailDiscoveryOptions {
canInspect: () => boolean;
resolveCameraImageUrl?: (deviceId: string) => string | undefined;
maxAttempts?: number;
exhaustionStore?: DetailDiscoveryExhaustionStore;
now?: () => number;
}

export type DeviceDetailDiscoveryResult =
Expand All @@ -36,9 +47,19 @@ export class DeviceDetailDiscovery {
readonly #maxAttempts: number;
#running = false;
#lastFailure: DeviceDetailDiscoveryFailure | undefined;
readonly #exhausted: Map<string, DetailDiscoveryExhaustion>;
readonly #now: () => number;

constructor(private readonly options: DeviceDetailDiscoveryOptions) {
this.#maxAttempts = options.maxAttempts ?? 2;
this.#now = options.now ?? Date.now;
let loaded = new Map<string, DetailDiscoveryExhaustion>();
try {
loaded = options.exhaustionStore?.load() ?? loaded;
} catch {
// A missing or unreadable ledger only means devices get visited again.
}
this.#exhausted = loaded;
}

reset(): void {
Expand Down Expand Up @@ -85,6 +106,7 @@ export class DeviceDetailDiscovery {
...(cameraImageUrl ? { cameraImageUrl } : {})
});
this.#lastFailure = undefined;
this.#recordExhaustion(device);
return "inspected";
} catch (error) {
if (error instanceof Error && error.message === "detail_discovery_preempted") {
Expand All @@ -97,6 +119,7 @@ export class DeviceDetailDiscovery {
deviceId: device.id,
reason: safeFailureReason(error)
};
this.#recordExhaustion(device);
return "failed";
} finally {
this.#running = false;
Expand All @@ -106,9 +129,41 @@ export class DeviceDetailDiscovery {
#needsInspection(device: BridgeDevice): boolean {
const attempts = this.#attempts.get(device.id) ?? 0;
if (attempts >= this.#maxAttempts) return false;
if (attempts === 0) return true;
return !discoveryComplete(device) || isCameraImageDevice(device);
// Controls persist across Bridge restarts, so a device whose detail
// controls are already complete needs no page visit. Re-inspecting every
// device on each restart kept Chromium busy for hours.
if (isCameraImageDevice(device)) return true;
if (discoveryComplete(device)) return false;
return !this.#recentlyExhausted(device);
}

#recentlyExhausted(device: BridgeDevice): boolean {
const record = this.#exhausted.get(device.id);
return (
record !== undefined &&
record.nameHash === nameHash(device.name) &&
this.#now() - record.exhaustedAtMs < DETAIL_DISCOVERY_EXHAUSTED_RETRY_MS
);
}

#recordExhaustion(device: BridgeDevice): void {
// Cameras are visited every session for their image, so they never count.
if (!this.options.exhaustionStore || isCameraImageDevice(device)) return;
if ((this.#attempts.get(device.id) ?? 0) < this.#maxAttempts) return;
this.#exhausted.set(device.id, {
nameHash: nameHash(device.name),
exhaustedAtMs: this.#now()
});
try {
this.options.exhaustionStore.save(this.#exhausted);
} catch {
// Persisting is best effort; the in-memory ledger still applies.
}
}
}

function nameHash(name: string): string {
return createHash("sha256").update(name).digest("hex");
}

function safeFailureReason(error: unknown): string {
Expand Down
4 changes: 3 additions & 1 deletion bridge/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { SessionMaintenanceGate } from "./browser/session-maintenance.js";
import { BrowserSupervisor } from "./browser/browser-supervisor.js";
import { SmartThingsWebUiCommandExecutor } from "./browser/command-page.js";
import { DeviceDetailDiscovery } from "./browser/device-detail-discovery.js";
import { FileDetailDiscoveryStore } from "./state/detail-discovery-store.js";
import { AuthenticatedSmartThingsSession } from "./advanced/authenticated-session.js";
import { AdvancedInventoryAdapter } from "./advanced/inventory-adapter.js";
import { AdvancedCommandAdapter } from "./advanced/command-adapter.js";
Expand Down Expand Up @@ -118,7 +119,7 @@ type ObservableContext = BrowserContextLike & {
newCDPSession?: (page: BrowserPageLike) => Promise<CdpSessionLike>;
};

const bridgeVersion = "1.8.74";
const bridgeVersion = "1.8.75";
const SESSION_TOUCH_INTERVAL_MS = 5 * 60_000;
const DETAIL_DISCOVERY_INTERVAL_MS = 15_000;
const PROFILE_MAINTENANCE_REQUIRED_FILE = ".profile-maintenance-required";
Expand Down Expand Up @@ -550,6 +551,7 @@ export async function createBridgeRuntime(deps: BridgeRuntimeDependencies): Prom
inventory: () => devices.snapshot(),
inspector: legacyCommandExecutor,
resolveCameraImageUrl: (deviceId) => cameraImages.thumbnailRequestUrl(deviceId),
exhaustionStore: new FileDetailDiscoveryStore(paths.dataDir),
canInspect: () => {
const report = createHealthReport(status.getSnapshot());
return (
Expand Down
66 changes: 66 additions & 0 deletions bridge/src/state/detail-discovery-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { chmodSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join } from "node:path";

export interface DetailDiscoveryExhaustion {
/** sha256 of the device name the exhausted visits used. */
nameHash: string;
exhaustedAtMs: number;
}

export interface DetailDiscoveryExhaustionStore {
load(): Map<string, DetailDiscoveryExhaustion>;
save(records: ReadonlyMap<string, DetailDiscoveryExhaustion>): void;
}

const FILE_NAME = "detail-discovery.json";

/**
* Remembers devices whose detail visits ran out without completing their
* controls, so a Bridge restart does not reopen a page for each of them.
*/
export class FileDetailDiscoveryStore implements DetailDiscoveryExhaustionStore {
readonly #path: string;

constructor(dataDir: string) {
this.#path = join(dataDir, FILE_NAME);
}

load(): Map<string, DetailDiscoveryExhaustion> {
const records = new Map<string, DetailDiscoveryExhaustion>();
let parsed: unknown;
try {
parsed = JSON.parse(readFileSync(this.#path, "utf8"));
} catch {
return records;
}
if (!isRecord(parsed) || parsed.schemaVersion !== 1 || !isRecord(parsed.exhausted)) {
return records;
}
for (const [deviceId, value] of Object.entries(parsed.exhausted)) {
if (
isRecord(value) &&
typeof value.nameHash === "string" &&
typeof value.exhaustedAtMs === "number" &&
Number.isFinite(value.exhaustedAtMs)
) {
records.set(deviceId, { nameHash: value.nameHash, exhaustedAtMs: value.exhaustedAtMs });
}
}
return records;
}

save(records: ReadonlyMap<string, DetailDiscoveryExhaustion>): void {
const temp = `${this.#path}.tmp`;
writeFileSync(
temp,
JSON.stringify({ schemaVersion: 1, exhausted: Object.fromEntries(records) }),
{ encoding: "utf8", mode: 0o600 }
);
renameSync(temp, this.#path);
chmodSync(this.#path, 0o600);
}
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
Loading
Loading