@hyjk2000/homebridge-bravia 0.0.3 → 0.0.5

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.
package/README.md CHANGED
@@ -1,34 +1,33 @@
1
1
  # Sony BRAVIA for Homebridge
2
2
 
3
- Expose Sony BRAVIA televisions in Apple Home through `@hyjk2000/homebridge-bravia`. Supports power, volume, mute, input selection, application launching, and remote-control keys through the TV's local Sony APIs.
3
+ Control Sony BRAVIA TVs in Apple Home: power, volume, mute, inputs, apps, and remote keys.
4
4
 
5
5
  ## Requirements
6
6
 
7
- - Node.js 24 or later and Homebridge 1.8.0 or later, within the package's declared peer dependency range.
8
- - A Sony BRAVIA TV with Sony JSON-RPC and IRCC IP control support. Available inputs, applications, and commands depend on the model and firmware; not every BRAVIA model is supported.
9
- - LAN connectivity from Homebridge to the TV. Enable IP/remote control and network standby (sometimes called Remote Start) in the TV settings. A DHCP reservation is recommended.
7
+ - Node.js 24+ and Homebridge 1.8.0+ within the declared peer dependency range.
8
+ - A LAN-accessible BRAVIA TV with JSON-RPC and IRCC IP control enabled. Support varies by model and firmware.
9
+ - Network standby/Remote Start enabled for wake support. A DHCP reservation is recommended.
10
10
 
11
11
  ## Installation and setup
12
12
 
13
- 1. Search for `@hyjk2000/homebridge-bravia` in the Homebridge UI Plugins tab and install it. Alternatively, install it in your Homebridge environment with `npm install -g @hyjk2000/homebridge-bravia`.
14
- 2. Open the plugin settings and add each TV with a unique name and its IP address or hostname. Enter only the address, not a URL or port; use the separate `port` setting if needed.
15
- 3. Turn the TV on, save the settings, and restart Homebridge or the plugin's child bridge.
16
- 4. Authenticate using one of the methods below.
17
- 5. In Apple Home, choose **Add Accessory → More Options**, select each TV, and enter the pairing code for the Homebridge instance or child bridge running the plugin. TVs are published as separate external accessories by default; pairing Homebridge alone does not add them.
13
+ 1. Install `@hyjk2000/homebridge-bravia` from the Homebridge UI.
14
+ 2. Add each TV in the plugin settings with a unique name and IP address or hostname. Use `port` separately if needed.
15
+ 3. Turn the TV on, save, restart the bridge, and authenticate below.
16
+ 4. In Apple Home, choose **Add Accessory → More Options** and pair each TV using the bridge's pairing code. TVs are separate accessories by default.
18
17
 
19
18
  ### TV authentication
20
19
 
21
- **Pre-shared key:** Enable pre-shared-key authentication in the TV's IP control settings, choose a key, and enter the same value in the plugin's `psk` field.
20
+ **Pre-shared key:** Set a key in the TV's IP control settings and enter it as `psk`.
22
21
 
23
- **PIN pairing:** Leave `psk` blank. After restarting, open the full local URL printed in the Homebridge logs and enter the PIN displayed on the TV into that page. No terminal input is required. Saved sessions and valid pre-shared keys skip this step.
22
+ **PIN:** Leave `psk` blank. Open the full URL in the Homebridge logs and enter the PIN shown on the TV. Saved sessions skip pairing.
24
23
 
25
- The temporary PIN page listens on an automatically selected free port on the Homebridge host and closes after pairing. Your browser must be able to reach that host and port. If the logged hostname cannot be resolved, replace only the hostname with the Homebridge host's LAN IP, keeping the port and full path. In Docker, host networking lets the browser reach the dynamically allocated pairing port.
24
+ The temporary pairing page uses a dynamic port on the Homebridge host. If needed, replace only the URL's hostname with the host's LAN IP; preserve the port and path. Docker host networking allows access to this port.
26
25
 
27
- Use PIN pairing only on a trusted LAN. Do not expose the PIN server to the internet or share its capability URL. TV control and the pairing page use local HTTP, not HTTPS.
26
+ Pair only on a trusted LAN: TV control and PIN entry use HTTP. Never expose the pairing server publicly or share its URL.
28
27
 
29
28
  ## Configuration
30
29
 
31
- The Homebridge UI provides a settings form. For manual configuration, add this entry to the `platforms` array in Homebridge's `config.json`:
30
+ Use the plugin settings, or add this to `platforms` in Homebridge's `config.json`:
32
31
 
33
32
  ```json
34
33
  {
@@ -43,7 +42,7 @@ The Homebridge UI provides a settings form. For manual configuration, add this e
43
42
  }
44
43
  ```
45
44
 
46
- Each `tvs` entry supports these options. All intervals and delays are in milliseconds.
45
+ Options per TV; times are in milliseconds.
47
46
 
48
47
  | Option | Default | Description |
49
48
  | ------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------- |
@@ -63,33 +62,28 @@ Each `tvs` entry supports these options. All intervals and delays are in millise
63
62
  | `externalaccessory` | `true` | Publish each TV separately. Set `false` to publish through the bridge instead. |
64
63
  | `debug` | `false` | Log TV command and refresh errors at info level; otherwise these use Homebridge debug logging. |
65
64
 
66
- When `sources` is omitted, the plugin scans `extInput:hdmi`, `extInput:component`, `extInput:scart`, `extInput:cec`, and `extInput:widi`. Set `sources: []` to disable those categories. Set `applications: []` or omit it to expose no apps. At most 95 inputs and applications are exposed per TV.
65
+ Default sources: `extInput:hdmi`, `extInput:component`, `extInput:scart`, `extInput:cec`, and `extInput:widi`. Use `sources: []` to disable them. Apps are opt-in. Each TV supports up to 95 inputs/apps combined.
67
66
 
68
- Input identifiers, HomeKit input names, and visibility are preserved across rescans. Accessory identity uses the configured MAC when present, otherwise the host address. Keep these identity fields stable; adding or changing a MAC, or changing the host without a configured MAC, changes accessory identity.
67
+ Input IDs, names, and visibility survive rescans. Keep `mac` (or the host address when no MAC is set) stable to preserve accessory identity.
69
68
 
70
69
  ## Troubleshooting
71
70
 
72
- - **No PIN or pairing page:** Turn the TV on, check its IP control/authentication settings, and restart the plugin. Use the full URL from the latest logs; its path changes when the plugin restarts. Check firewall and container port access.
73
- - **TV will not wake:** Enable network standby/Remote Start. Configure `mac` for Wake-on-LAN and check that `woladdress` reaches the TV's network. Increase `starttimeout` if commands arrive before the TV is ready.
74
- - **TV missing from Apple Home:** Add each external TV separately using the Homebridge or child bridge pairing code. Check that mDNS discovery works between your Apple device and Homebridge.
75
- - **Missing inputs or apps:** Turn the TV on and check `sources`, `tvsource`, and application title filters. Unsupported Sony source categories are skipped. Discovery depends on the model and firmware.
76
- - **Connection failures:** Check the TV address, HTTP port, credentials, and LAN reachability. Cached services are restored when the TV is offline; initialization is retried while Homebridge is running.
71
+ - **Pairing page unavailable:** Turn the TV on, check IP control settings, and use the latest log URL. Check firewall/container access.
72
+ - **Will not wake:** Enable Remote Start, check `mac`/`woladdress`, and increase `starttimeout` if commands arrive too early.
73
+ - **Missing TV:** Pair it separately and check mDNS connectivity.
74
+ - **Missing inputs/apps:** Turn the TV on and check `sources`, `tvsource`, and case-sensitive app filters. Availability varies by firmware.
75
+ - **Connection failures:** Check address, port, credentials, and LAN access. Offline TVs retain cached services; initialization retries automatically.
77
76
 
78
- When reporting an issue, include the plugin, Homebridge, and Node.js versions, TV model/firmware, sanitized configuration, and relevant logs. Remove pre-shared keys, cookies, PINs, and pairing URLs before sharing.
77
+ Report issues with versions, TV model/firmware, sanitized config, and logs. Remove keys, cookies, PINs, and pairing URLs.
79
78
 
80
79
  ## Storage
81
80
 
82
- Sessions and external-accessory state are stored under `<Homebridge storage>/plugin-persist/hyjk2000-homebridge-bravia/<uuid>.json`, outside the plugin installation. Treat these files and Homebridge backups as credentials. Pre-shared keys remain in your Homebridge configuration.
81
+ Sessions and accessory state live in `<Homebridge storage>/plugin-persist/hyjk2000-homebridge-bravia/<uuid>.json`. Protect these files and backups as credentials. Pre-shared keys remain in Homebridge's config.
83
82
 
84
- ## Development and publishing
83
+ ## Development
85
84
 
86
- From the repository root, use Node.js 24 and the pinned pnpm version. Run `pnpm install`, then `pnpm build` before plugin tests. Use `pnpm --filter @hyjk2000/homebridge-bravia test` for plugin tests and `pnpm --filter @hyjk2000/homebridge-bravia dev` to watch and rebuild the plugin.
87
-
88
- For publishable changes, run `pnpm changeset` and commit the generated file. Push to `master`, then merge the **Version Packages** PR when ready to publish. Docs, tests, and tooling changes need no changeset. See the [official Changesets guide](https://changesets.dev/guide/automating).
89
-
90
- Setup: allow GitHub Actions to create pull requests and configure npm trusted publishers for both packages using `release.yml`. No npm token or Changesets bot is needed.
91
-
92
- Authoring references: [official plugin template](https://github.com/homebridge/homebridge-plugin-template) and [Homebridge verification requirements](https://github.com/homebridge/plugins/wiki/Verified-Plugins#current-requirements). This plugin is not claimed to be Homebridge Verified. Its Node.js 24 minimum excludes Node.js 22, which is currently required by the verification program.
85
+ See the [monorepo README](../../README.md) for setup. Build before running
86
+ `pnpm --filter @hyjk2000/homebridge-bravia test`; use `pnpm dev` to watch and rebuild.
93
87
 
94
88
  ## License
95
89
 
package/dist/index.js CHANGED
@@ -375,6 +375,7 @@ var Television = class {
375
375
  stopped = false;
376
376
  power = false;
377
377
  currentUri;
378
+ statusRevision = 0;
378
379
  boot;
379
380
  api;
380
381
  log;
@@ -486,31 +487,21 @@ var Television = class {
486
487
  this.information.setCharacteristic(C.Manufacturer, interfaceInfo?.productName || "Sony").setCharacteristic(C.Model, systemInfo?.model || interfaceInfo?.modelName || "Bravia TV").setCharacteristic(C.SerialNumber, systemInfo?.serial || systemInfo?.macAddr || this.accessory.UUID);
487
488
  this.save();
488
489
  }
489
- async readPower() {
490
- const on = (await this.client.system.getPowerStatus()).result[0].status === "active";
491
- if (!this.stopped) {
492
- this.power = on;
493
- this.tv.updateCharacteristic(this.api.hap.Characteristic.Active, Number(on));
494
- if (!on) {
495
- this.currentUri = void 0;
496
- this.updateIdentifier();
497
- }
490
+ async readPower(revision = this.statusRevision) {
491
+ try {
492
+ const on = (await this.client.system.getPowerStatus()).result[0].status === "active";
493
+ this.commitStatus({ power: on }, revision);
494
+ } catch (error) {
495
+ if (revision === this.statusRevision) throw error;
498
496
  }
499
- return on;
497
+ return this.power;
500
498
  }
501
499
  async setPower(on) {
502
500
  if (this.config.mac) {
503
501
  if (on) await wake(this.config.mac, this.config.woladdress ?? "255.255.255.255");
504
502
  else await this.client.ircc.sendCode(IRCC_CODES.PowerOff);
505
503
  } else await this.client.system.setPowerStatus({ status: on });
506
- if (!this.stopped) {
507
- this.power = on;
508
- this.tv.updateCharacteristic(this.api.hap.Characteristic.Active, Number(on));
509
- if (!on) {
510
- this.currentUri = void 0;
511
- this.updateIdentifier();
512
- }
513
- }
504
+ this.commitStatus({ power: on });
514
505
  }
515
506
  async selectInput(identifier) {
516
507
  const input = [...this.inputs.values()].find((entry) => entry.identifier === identifier);
@@ -525,10 +516,7 @@ var Television = class {
525
516
  if (this.stopped) return;
526
517
  if (input.type === this.api.hap.Characteristic.InputSourceType.APPLICATION) await this.client.appControl.setActiveApp({ uri: input.uri });
527
518
  else await this.client.avContent.setPlayContent({ uri: input.uri });
528
- if (!this.stopped) {
529
- this.currentUri = input.uri;
530
- this.updateIdentifier();
531
- }
519
+ this.commitStatus({ uri: input.uri });
532
520
  }
533
521
  async readAudio() {
534
522
  const output = (await this.client.audio.getVolumeInformation()).result[0].find((value) => value.target === (this.config.soundoutput ?? "speaker"));
@@ -539,27 +527,36 @@ var Television = class {
539
527
  const identifier = this.currentUri ? this.inputs.get(this.currentUri)?.identifier ?? 0 : 0;
540
528
  return this.services.has(identifier) ? identifier : 0;
541
529
  }
530
+ commitStatus(change, observedAt) {
531
+ if (this.stopped) return;
532
+ if (observedAt === void 0) this.statusRevision++;
533
+ else if (observedAt !== this.statusRevision) return;
534
+ const { Characteristic: C, HapStatusError, HAPStatus } = this.api.hap;
535
+ if ("power" in change) {
536
+ this.power = change.power;
537
+ if (!change.power) this.currentUri = void 0;
538
+ this.tv.updateCharacteristic(C.Active, Number(change.power));
539
+ if (!change.power) this.updateIdentifier();
540
+ } else if ("uri" in change) {
541
+ this.currentUri = change.uri;
542
+ this.updateIdentifier();
543
+ } else this.tv.updateCharacteristic(C.Active, new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE));
544
+ }
542
545
  updateIdentifier() {
543
546
  this.tv.updateCharacteristic(this.api.hap.Characteristic.ActiveIdentifier, this.activeIdentifier);
544
547
  }
545
548
  async poll() {
549
+ const revision = this.statusRevision;
546
550
  try {
547
- if (!await this.readPower() || this.stopped) return;
551
+ if (!await this.readPower(revision) || this.stopped || revision !== this.statusRevision) return;
548
552
  try {
549
553
  const uri = (await this.client.avContent.getPlayingContentInfo()).result[0].uri;
550
- if (!this.stopped) {
551
- this.currentUri = uri;
552
- this.updateIdentifier();
553
- }
554
+ this.commitStatus({ uri }, revision);
554
555
  } catch (error) {
555
- if (!this.stopped) {
556
- this.currentUri = void 0;
557
- this.updateIdentifier();
558
- }
559
556
  this.debug(`${this.config.name}: playing content unavailable`, error);
560
557
  }
561
558
  } catch (error) {
562
- if (!this.stopped) this.tv.updateCharacteristic(this.api.hap.Characteristic.Active, new this.api.hap.HapStatusError(this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE));
559
+ this.commitStatus({ powerUnavailable: true }, revision);
563
560
  this.debug(`${this.config.name}: status unavailable`, error);
564
561
  } finally {
565
562
  if (!this.stopped) this.save();
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["delay"],"sources":["../authentication.ts","../config.ts","../wake.ts","../television.ts","../platform.ts","../index.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { hostname } from \"node:os\";\nimport { Bravia, BraviaError } from \"@hyjk2000/bravia-sdk\";\nimport type { Logging } from \"homebridge\";\nimport type { TvConfig } from \"./config.ts\";\n\nconst MAX_BODY_BYTES = 1024;\n\nfunction authenticationRequired(error: unknown): boolean {\n if (error instanceof BraviaError) {\n return error.id === 401 || error.id === 403;\n }\n if (typeof error !== \"object\" || error === null || !(\"response\" in error)) {\n return false;\n }\n const response = error.response;\n return (\n typeof response === \"object\" &&\n response !== null &&\n \"status\" in response &&\n (response.status === 401 || response.status === 403)\n );\n}\n\nfunction respond(response: ServerResponse, status: number, body: string, html = false): void {\n if (response.destroyed || response.writableEnded) {\n return;\n }\n response.writeHead(status, {\n \"Content-Type\": html ? \"text/html; charset=utf-8\" : \"text/plain; charset=utf-8\",\n \"Content-Length\": Buffer.byteLength(body),\n \"Cache-Control\": \"no-store\",\n \"Content-Security-Policy\":\n \"default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'\",\n \"X-Content-Type-Options\": \"nosniff\",\n \"Referrer-Policy\": \"same-origin\",\n Connection: \"close\",\n });\n response.end(body);\n}\n\nclass FormError extends Error {\n readonly status: number;\n\n constructor(status: number, message: string) {\n super(message);\n this.status = status;\n }\n}\n\nfunction readForm(request: IncomingMessage): Promise<URLSearchParams> {\n const { promise, resolve, reject } = Promise.withResolvers<URLSearchParams>();\n let size = 0;\n let complete = false;\n const chunks: Buffer[] = [];\n request.on(\"data\", (chunk: Buffer) => {\n if (complete) {\n return;\n }\n size += chunk.length;\n if (size > MAX_BODY_BYTES) {\n complete = true;\n chunks.length = 0;\n reject(new FormError(413, \"Request body is too large.\\n\"));\n return;\n }\n chunks.push(chunk);\n });\n request.on(\"end\", () => {\n if (!complete) {\n complete = true;\n resolve(new URLSearchParams(Buffer.concat(chunks, size).toString(\"utf8\")));\n }\n });\n request.on(\"error\", () => {\n if (!complete) {\n complete = true;\n reject(new FormError(400, \"Could not read request.\\n\"));\n }\n });\n request.on(\"aborted\", () => {\n if (!complete) {\n complete = true;\n reject(new FormError(400, \"Request was interrupted.\\n\"));\n }\n });\n return promise;\n}\n\ninterface PendingRegistration {\n client: Bravia;\n resolve: (client: Bravia) => void;\n reject: (error: Error) => void;\n}\n\nexport interface AuthenticationOptions {\n config: TvConfig;\n baseUrl: string;\n cookie?: string;\n clientId: string;\n log: Logging;\n}\n\n/** A single TV's registration session; the HTTP server exists only while a PIN is needed. */\nexport class Authentication {\n private stopped = false;\n private server?: Server;\n private pending?: PendingRegistration;\n private submitting = false;\n private client?: Bravia;\n private readonly formToken = randomBytes(24).toString(\"base64url\");\n\n private readonly options: AuthenticationOptions;\n\n constructor(options: AuthenticationOptions) {\n this.options = options;\n }\n\n async authenticate(): Promise<Bravia> {\n this.assertRunning();\n const { baseUrl, config, clientId } = this.options;\n const cookie = this.client?.cookie ?? this.options.cookie;\n let client = new Bravia({ baseUrl, cookie, psk: config.psk });\n this.client = client;\n if (cookie || config.psk) {\n try {\n await client.system.getPowerStatus();\n this.assertRunning();\n return client;\n } catch (error) {\n this.assertRunning();\n if (!authenticationRequired(error)) {\n throw error;\n }\n }\n }\n\n // Never reuse a rejected cookie or PSK for PIN-based registration.\n client = new Bravia({ baseUrl });\n this.client = client;\n const registeredCookie = await client.accessControl.actRegister({\n clientid: clientId,\n nickname: \"Homebridge Bravia\",\n });\n this.assertRunning();\n if (registeredCookie) {\n return client;\n }\n return this.waitForPin(client);\n }\n\n stop(): void {\n this.stopped = true;\n const pending = this.pending;\n this.pending = undefined;\n pending?.reject(new Error(\"TV authentication stopped.\"));\n this.closeServer(true);\n }\n\n private assertRunning(): void {\n if (this.stopped) {\n throw new Error(\"TV authentication stopped.\");\n }\n }\n\n private waitForPin(client: Bravia): Promise<Bravia> {\n this.assertRunning();\n const { promise, resolve, reject } = Promise.withResolvers<Bravia>();\n this.pending = { client, resolve, reject };\n const server = createServer({ maxHeaderSize: 8192 }, (request, response) => {\n void this.handleRequest(request, response).catch(() => {\n this.options.log.error(\"[%s] Could not handle the PIN request.\", this.options.config.name);\n respond(response, 500, \"Could not process request.\\n\");\n });\n });\n this.server = server;\n server.requestTimeout = 30_000;\n server.headersTimeout = 10_000;\n server.setTimeout(30_000, (socket) => socket.destroy());\n server.on(\"error\", () => {\n const pending = this.pending;\n this.pending = undefined;\n this.options.log.error(\n \"[%s] Could not listen for PIN registration.\",\n this.options.config.name,\n );\n pending?.reject(new Error(\"Could not start the local PIN server.\"));\n this.closeServer(true);\n });\n try {\n server.listen(0, \"0.0.0.0\", () => {\n if (this.stopped) {\n this.closeServer(true);\n return;\n }\n const address = server.address() as AddressInfo;\n this.options.log.info(\n \"[%s] Enter the PIN displayed by the TV at http://%s:%s/%s\",\n this.options.config.name,\n hostname(),\n address.port,\n this.formToken,\n );\n });\n } catch {\n this.pending = undefined;\n this.closeServer(true);\n reject(new Error(\"Could not start the local PIN server.\"));\n }\n return promise;\n }\n\n private async handleRequest(request: IncomingMessage, response: ServerResponse): Promise<void> {\n if (this.stopped || !this.pending) {\n respond(response, 503, \"Registration is not available.\\n\");\n request.resume();\n return;\n }\n const origin = request.headers.origin;\n if (origin && origin !== `http://${request.headers.host}`) {\n respond(response, 403, \"Invalid request origin.\\n\");\n request.resume();\n return;\n }\n const formPath = `/${this.formToken}`;\n if (request.method === \"GET\" && request.url === formPath) {\n respond(\n response,\n 200,\n `<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><title>Pair BRAVIA TV</title><h1>Pair BRAVIA TV</h1><p>Enter the PIN displayed by your TV.</p><form method=\"post\" action=\"${formPath}/pair\"><label>PIN <input type=\"password\" name=\"pin\" inputmode=\"numeric\" autocomplete=\"off\" maxlength=\"16\" required></label><button type=\"submit\">Pair</button></form></html>`,\n true,\n );\n request.resume();\n return;\n }\n if (request.url !== `${formPath}/pair`) {\n respond(response, 404, \"Not found.\\n\");\n request.resume();\n return;\n }\n if (request.method !== \"POST\") {\n respond(response, 405, \"Use POST to submit the PIN.\\n\");\n request.resume();\n return;\n }\n if (\n request.headers[\"content-type\"]?.split(\";\", 1)[0]?.trim() !==\n \"application/x-www-form-urlencoded\"\n ) {\n respond(response, 415, \"Use the PIN form to submit a request.\\n\");\n request.resume();\n return;\n }\n let form: URLSearchParams;\n try {\n form = await readForm(request);\n } catch (error) {\n respond(\n response,\n error instanceof FormError ? error.status : 400,\n error instanceof FormError ? error.message : \"Invalid request.\\n\",\n );\n request.resume();\n return;\n }\n const pin = form.get(\"pin\");\n if (!pin || !/^\\d{1,16}$/.test(pin)) {\n respond(response, 400, \"Enter the numeric PIN displayed by the TV.\\n\");\n return;\n }\n if (this.submitting) {\n respond(response, 409, \"A registration request is already in progress.\\n\");\n return;\n }\n const pending = this.pending;\n if (this.stopped || !pending) {\n respond(response, 503, \"Registration is not available.\\n\");\n return;\n }\n this.submitting = true;\n try {\n const cookie = await pending.client.accessControl.actRegister({\n clientid: this.options.clientId,\n nickname: \"Homebridge Bravia\",\n pin,\n });\n if (this.stopped || this.pending !== pending) {\n respond(response, 503, \"Registration has stopped.\\n\");\n return;\n }\n if (!cookie) {\n respond(response, 401, \"The TV did not accept the PIN. Reload the form and try again.\\n\");\n return;\n }\n this.pending = undefined;\n respond(response, 200, \"TV paired. You may close this page.\\n\");\n pending.resolve(pending.client);\n this.closeServer(false);\n } catch {\n this.options.log.warn(\n \"[%s] TV registration failed; try submitting the PIN again.\",\n this.options.config.name,\n );\n respond(response, 502, \"TV registration failed. Reload the form and try again.\\n\");\n } finally {\n this.submitting = false;\n }\n }\n\n private closeServer(force: boolean): void {\n const server = this.server;\n if (!server) {\n return;\n }\n server.close(() => {\n if (this.server === server) {\n this.server = undefined;\n }\n });\n if (force) {\n server.closeAllConnections();\n }\n }\n}\n","import { isIP } from \"node:net\";\nimport type { Logging, PlatformConfig } from \"homebridge\";\n\nexport interface TvConfig {\n name: string;\n ip: string;\n port?: number | string;\n mac?: string;\n woladdress?: string;\n tvsource?: string;\n soundoutput?: string;\n updaterate?: number;\n channelupdaterate?: number;\n starttimeout?: number;\n sources?: { source: string }[];\n applications?: { title: string }[];\n psk?: string;\n externalaccessory?: boolean;\n debug?: boolean;\n}\n\nexport interface BraviaPlatformConfig extends PlatformConfig {\n tvs?: TvConfig[];\n}\n\nfunction isHost(value: unknown): value is string {\n if (typeof value !== \"string\" || !value || value.length > 253) return false;\n if (isIP(value)) return true;\n return value.split(\".\").every((label) => /^[a-z\\d](?:[a-z\\d-]{0,61}[a-z\\d])?$/i.test(label));\n}\n\nfunction isPort(value: unknown): boolean {\n return (\n (typeof value === \"number\" || (typeof value === \"string\" && /^\\d+$/.test(value))) &&\n Number.isInteger(Number(value)) &&\n Number(value) >= 1 &&\n Number(value) <= 65535\n );\n}\n\nexport function parseConfig(config: BraviaPlatformConfig | undefined, log: Logging): TvConfig[] {\n if (!config) return [];\n if (config.compatibilitymode === true) {\n log.error(\n \"compatibilitymode is unsupported: the legacy implementation sent authentication to an unrelated public host. Remove it and use local TV authentication.\",\n );\n return [];\n }\n if (config.tvs === undefined) return [];\n if (!Array.isArray(config.tvs)) {\n log.error(\"BraviaPlatform: tvs must be an array.\");\n return [];\n }\n const candidates: { tv: TvConfig; index: number; keys: string[] }[] = [];\n const counts = new Map<string, number>();\n for (const [index, entry] of config.tvs.entries()) {\n const errors: string[] = [];\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n log.error(`BraviaPlatform: TV ${index + 1} must be an object.`);\n continue;\n }\n const raw = entry as unknown as Record<string, unknown>;\n if (raw.compatibilitymode === true)\n errors.push(\n \"compatibilitymode is unsafe and unsupported: legacy authentication was sent to an unrelated public host; remove it\",\n );\n if (typeof raw.name !== \"string\" || !raw.name.trim())\n errors.push(\"name must be a nonempty string\");\n if (!isHost(raw.ip))\n errors.push(\n \"ip must be an IP address or hostname, without a URL scheme, path, port, or credentials\",\n );\n if (raw.port !== undefined && !isPort(raw.port))\n errors.push(\"port must be an integer from 1 to 65535\");\n if (\n raw.mac !== undefined &&\n (typeof raw.mac !== \"string\" ||\n !/^(?:[\\da-f]{2}:){5}[\\da-f]{2}$|^(?:[\\da-f]{2}-){5}[\\da-f]{2}$/i.test(raw.mac))\n )\n errors.push(\"mac must contain six colon- or hyphen-separated hexadecimal octets\");\n if (raw.woladdress !== undefined && !isHost(raw.woladdress))\n errors.push(\"woladdress must be an IP address or hostname\");\n for (const field of [\"updaterate\", \"channelupdaterate\", \"starttimeout\"] as const) {\n const value = raw[field];\n if (\n value !== undefined &&\n (typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n (field === \"channelupdaterate\" ? value < 0 : value <= 0))\n )\n errors.push(\n `${field} must be ${field === \"channelupdaterate\" ? \"nonnegative (0 disables polling)\" : \"positive\"}`,\n );\n }\n for (const field of [\"tvsource\", \"soundoutput\", \"psk\"] as const) {\n if (raw[field] !== undefined && typeof raw[field] !== \"string\")\n errors.push(`${field} must be a string`);\n }\n for (const field of [\"externalaccessory\", \"debug\"] as const) {\n if (raw[field] !== undefined && typeof raw[field] !== \"boolean\")\n errors.push(`${field} must be a boolean`);\n }\n if (\n raw.sources !== undefined &&\n (!Array.isArray(raw.sources) ||\n !raw.sources.every(\n (value) =>\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n typeof value.source === \"string\" &&\n value.source.trim(),\n ))\n )\n errors.push(\"sources must be a list of objects with nonempty source categories\");\n if (\n raw.applications !== undefined &&\n (!Array.isArray(raw.applications) ||\n !raw.applications.every(\n (value) =>\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n typeof value.title === \"string\" &&\n value.title.trim(),\n ))\n )\n errors.push(\"applications must be a list of objects with nonempty titles\");\n if (errors.length) {\n log.error(`BraviaPlatform: TV ${index + 1} is invalid: ${errors.join(\"; \")}.`);\n continue;\n }\n const tv: TvConfig = {\n ...entry,\n name: entry.name.trim(),\n externalaccessory: entry.externalaccessory ?? true,\n };\n const keys = [`name:${tv.name.toLowerCase()}`, `host:${tv.ip.toLowerCase()}`];\n if (tv.mac) keys.push(`mac:${tv.mac.replace(/[:-]/g, \"\").toLowerCase()}`);\n for (const key of keys) counts.set(key, (counts.get(key) ?? 0) + 1);\n candidates.push({ tv, index, keys });\n }\n return candidates\n .filter(({ index, keys }) => {\n const duplicates = keys.filter((key) => counts.get(key)! > 1);\n if (!duplicates.length) return true;\n log.error(\n `BraviaPlatform: TV ${index + 1} has a duplicate name or device identity; every colliding entry is skipped.`,\n );\n return false;\n })\n .map(({ tv }) => tv);\n}\n","import { createSocket } from \"node:dgram\";\n\n/** Resolve only after the broadcast has been handed to the network stack. */\nexport function wake(mac: string, address: string): Promise<void> {\n const hardwareAddress = Buffer.from(mac.replace(/[:-]/g, \"\"), \"hex\");\n const packet = Buffer.alloc(102, 0xff);\n for (let offset = 6; offset < packet.length; offset += 6) {\n hardwareAddress.copy(packet, offset);\n }\n const { promise, resolve, reject } = Promise.withResolvers<void>();\n const socket = createSocket(\"udp4\");\n let finished = false;\n const finish = (error?: Error | null) => {\n if (finished) return;\n finished = true;\n socket.close();\n if (error) reject(error);\n else resolve();\n };\n socket.once(\"error\", finish);\n socket.bind(() => {\n try {\n socket.setBroadcast(true);\n socket.send(packet, 9, address, finish);\n } catch (error) {\n finish(error instanceof Error ? error : new Error(String(error)));\n }\n });\n return promise;\n}\n","import { createHash } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport {\n Bravia,\n IRCC_CODES,\n type InterfaceInformation,\n type SystemInformation,\n} from \"@hyjk2000/bravia-sdk\";\nimport type { CharacteristicValue, Logging, PlatformAccessory, Service } from \"homebridge\";\nimport type { TvConfig } from \"./config.ts\";\nimport type { RuntimeAPI } from \"./hap.ts\";\nimport { wake } from \"./wake.ts\";\n\ninterface Input {\n uri: string;\n title: string;\n group: string;\n type: number;\n identifier: number;\n configuredName?: string;\n visibility?: number;\n}\n\nconst DEFAULT_SOURCES = [\n \"extInput:hdmi\",\n \"extInput:component\",\n \"extInput:scart\",\n \"extInput:cec\",\n \"extInput:widi\",\n];\n// Leave room for the information, TV, speaker and protocol services (HAP limit: 100).\nconst MAX_INPUTS = 95;\n\nexport class Television {\n private readonly tv: Service;\n private readonly speaker: Service;\n private readonly information: Service;\n private readonly inputs = new Map<string, Input>();\n private readonly services = new Map<number, Service>();\n private readonly abort = new AbortController();\n private statusTimer?: NodeJS.Timeout;\n private sourceTimer?: NodeJS.Timeout;\n private stopped = false;\n private power = false;\n private currentUri?: string;\n private boot?: Promise<void>;\n private readonly api: RuntimeAPI;\n private readonly log: Logging;\n private readonly config: TvConfig;\n private readonly accessory: PlatformAccessory;\n private readonly client: Bravia;\n private readonly save: () => void;\n\n constructor(\n api: RuntimeAPI,\n log: Logging,\n config: TvConfig,\n accessory: PlatformAccessory,\n client: Bravia,\n save: () => void,\n ) {\n this.api = api;\n this.log = log;\n this.config = config;\n this.accessory = accessory;\n this.client = client;\n this.save = save;\n const { Service: S, Characteristic: C } = api.hap;\n accessory.category = api.hap.Categories.TELEVISION;\n this.information =\n accessory.getService(S.AccessoryInformation) ?? accessory.addService(S.AccessoryInformation);\n this.tv = accessory.getService(S.Television) ?? accessory.addService(S.Television, config.name);\n this.speaker =\n accessory.getService(S.TelevisionSpeaker) ??\n accessory.addService(S.TelevisionSpeaker, config.soundoutput ?? \"speaker\");\n this.tv.setPrimaryService();\n this.tv.addLinkedService(this.speaker);\n this.tv\n .setCharacteristic(C.ConfiguredName, config.name)\n .setCharacteristic(C.SleepDiscoveryMode, C.SleepDiscoveryMode.ALWAYS_DISCOVERABLE);\n this.speaker\n .setCharacteristic(C.Active, C.Active.ACTIVE)\n .setCharacteristic(C.VolumeControlType, C.VolumeControlType.ABSOLUTE);\n const interfaceInfo = accessory.context.interfaceInfo as InterfaceInformation | undefined;\n const systemInfo = accessory.context.systemInfo as SystemInformation | undefined;\n this.information\n .setCharacteristic(C.Manufacturer, interfaceInfo?.productName || \"Sony\")\n .setCharacteristic(C.Model, systemInfo?.model || interfaceInfo?.modelName || \"Bravia TV\")\n .setCharacteristic(\n C.SerialNumber,\n systemInfo?.serial || systemInfo?.macAddr || accessory.UUID,\n );\n\n const groups = this.sourceGroups();\n for (const input of (accessory.context.inputs ?? []) as Input[]) {\n if (\n groups.has(input.group) &&\n (input.group !== \"applications\" ||\n config.applications?.some((filter) => input.title.includes(filter.title)))\n )\n this.inputs.set(input.uri, input);\n }\n this.syncInputs();\n this.tv\n .getCharacteristic(C.Active)\n .onGet(() => this.handle(async () => Number(await this.readPower())))\n .onSet((value) => this.handle(() => this.setPower(Number(value) === C.Active.ACTIVE)));\n this.tv\n .getCharacteristic(C.ActiveIdentifier)\n .onGet(() => this.activeIdentifier)\n .onSet((value) => this.handle(() => this.selectInput(Number(value))));\n const keys = new Map<number, string>([\n [C.RemoteKey.REWIND, IRCC_CODES.Rewind],\n [C.RemoteKey.FAST_FORWARD, IRCC_CODES.Forward],\n [C.RemoteKey.NEXT_TRACK, IRCC_CODES.Next],\n [C.RemoteKey.PREVIOUS_TRACK, IRCC_CODES.Prev],\n [C.RemoteKey.ARROW_UP, IRCC_CODES.Up],\n [C.RemoteKey.ARROW_DOWN, IRCC_CODES.Down],\n [C.RemoteKey.ARROW_LEFT, IRCC_CODES.Left],\n [C.RemoteKey.ARROW_RIGHT, IRCC_CODES.Right],\n [C.RemoteKey.SELECT, IRCC_CODES.Confirm],\n [C.RemoteKey.BACK, IRCC_CODES.Back],\n [C.RemoteKey.EXIT, IRCC_CODES.Exit],\n [C.RemoteKey.PLAY_PAUSE, IRCC_CODES.Play],\n [C.RemoteKey.INFORMATION, IRCC_CODES.Display],\n ]);\n this.tv.getCharacteristic(C.RemoteKey).onSet((value) =>\n this.handle(async () => {\n const code = keys.get(Number(value));\n if (code) await this.client.ircc.sendCode(code);\n else throw new api.hap.HapStatusError(api.hap.HAPStatus.INVALID_VALUE_IN_REQUEST);\n }),\n );\n this.speaker\n .getCharacteristic(C.VolumeSelector)\n .onSet((value) =>\n this.handle(() =>\n this.client.ircc.sendCode(\n Number(value) === C.VolumeSelector.INCREMENT\n ? IRCC_CODES.VolumeUp\n : IRCC_CODES.VolumeDown,\n ),\n ),\n );\n this.speaker\n .getCharacteristic(C.Mute)\n .onGet(() => this.handle(async () => (this.power ? (await this.readAudio()).mute : false)))\n .onSet((value) =>\n this.handle(async () => {\n if (this.power) await this.client.audio.setAudioMute({ status: Boolean(value) });\n }),\n );\n this.speaker\n .getCharacteristic(C.Volume)\n .onGet(() =>\n this.handle(async () => (this.power ? Number((await this.readAudio()).volume) : 0)),\n )\n .onSet((value) =>\n this.handle(async () => {\n if (this.power)\n await this.client.audio.setAudioVolume({\n target: config.soundoutput ?? \"speaker\",\n volume: String(value as number),\n });\n }),\n );\n }\n\n async start(): Promise<void> {\n if (this.stopped) return;\n await this.probeInformation();\n if (this.stopped) return;\n await this.poll();\n if (this.stopped) return;\n await this.scan();\n this.scheduleStatus();\n this.scheduleSources();\n }\n\n stop(): void {\n this.stopped = true;\n this.abort.abort();\n clearTimeout(this.statusTimer);\n clearTimeout(this.sourceTimer);\n }\n\n private async handle<T extends CharacteristicValue | void>(\n operation: () => Promise<T>,\n ): Promise<T> {\n try {\n if (this.stopped) throw new Error(\"Plugin is shutting down\");\n return await operation();\n } catch (error) {\n this.debug(`${this.config.name}: command failed`, error);\n if (error instanceof this.api.hap.HapStatusError) throw error;\n throw new this.api.hap.HapStatusError(this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE);\n } finally {\n if (!this.stopped) this.save();\n }\n }\n\n private async probeInformation(): Promise<void> {\n const { Characteristic: C } = this.api.hap;\n let interfaceInfo = this.accessory.context.interfaceInfo as InterfaceInformation | undefined;\n let systemInfo = this.accessory.context.systemInfo as SystemInformation | undefined;\n try {\n interfaceInfo = (await this.client.system.getInterfaceInformation()).result[0];\n this.accessory.context.interfaceInfo = interfaceInfo;\n } catch (error) {\n this.debug(`${this.config.name}: interface information unavailable`, error);\n }\n if (this.stopped) return;\n try {\n systemInfo = (await this.client.system.getSystemInformation()).result[0];\n this.accessory.context.systemInfo = systemInfo;\n } catch (error) {\n this.debug(`${this.config.name}: system information unavailable`, error);\n }\n if (this.stopped) return;\n this.information\n .setCharacteristic(C.Manufacturer, interfaceInfo?.productName || \"Sony\")\n .setCharacteristic(C.Model, systemInfo?.model || interfaceInfo?.modelName || \"Bravia TV\")\n .setCharacteristic(\n C.SerialNumber,\n systemInfo?.serial || systemInfo?.macAddr || this.accessory.UUID,\n );\n this.save();\n }\n\n private async readPower(): Promise<boolean> {\n const on = (await this.client.system.getPowerStatus()).result[0].status === \"active\";\n if (!this.stopped) {\n this.power = on;\n this.tv.updateCharacteristic(this.api.hap.Characteristic.Active, Number(on));\n if (!on) {\n this.currentUri = undefined;\n this.updateIdentifier();\n }\n }\n return on;\n }\n\n private async setPower(on: boolean): Promise<void> {\n if (this.config.mac) {\n if (on) await wake(this.config.mac, this.config.woladdress ?? \"255.255.255.255\");\n else await this.client.ircc.sendCode(IRCC_CODES.PowerOff);\n } else {\n await this.client.system.setPowerStatus({ status: on });\n }\n if (!this.stopped) {\n this.power = on;\n this.tv.updateCharacteristic(this.api.hap.Characteristic.Active, Number(on));\n if (!on) {\n this.currentUri = undefined;\n this.updateIdentifier();\n }\n }\n }\n\n private async selectInput(identifier: number): Promise<void> {\n const input = [...this.inputs.values()].find((entry) => entry.identifier === identifier);\n if (!input || !this.services.has(identifier))\n throw new this.api.hap.HapStatusError(this.api.hap.HAPStatus.INVALID_VALUE_IN_REQUEST);\n if (!this.power) {\n this.boot ??= (async () => {\n await this.setPower(true);\n await delay(this.config.starttimeout ?? 5000, undefined, { signal: this.abort.signal });\n })().finally(() => {\n this.boot = undefined;\n });\n }\n if (this.boot) await this.boot;\n if (this.stopped) return;\n if (input.type === this.api.hap.Characteristic.InputSourceType.APPLICATION) {\n await this.client.appControl.setActiveApp({ uri: input.uri });\n } else {\n await this.client.avContent.setPlayContent({ uri: input.uri });\n }\n if (!this.stopped) {\n this.currentUri = input.uri;\n this.updateIdentifier();\n }\n }\n\n private async readAudio() {\n const values = (await this.client.audio.getVolumeInformation()).result[0];\n const output = values.find((value) => value.target === (this.config.soundoutput ?? \"speaker\"));\n if (!output) throw new Error(\"Configured audio output is unavailable\");\n return output;\n }\n\n private get activeIdentifier(): number {\n const identifier = this.currentUri ? (this.inputs.get(this.currentUri)?.identifier ?? 0) : 0;\n return this.services.has(identifier) ? identifier : 0;\n }\n\n private updateIdentifier(): void {\n this.tv.updateCharacteristic(\n this.api.hap.Characteristic.ActiveIdentifier,\n this.activeIdentifier,\n );\n }\n\n private async poll(): Promise<void> {\n try {\n if (!(await this.readPower()) || this.stopped) return;\n try {\n const uri = (await this.client.avContent.getPlayingContentInfo()).result[0].uri;\n if (!this.stopped) {\n this.currentUri = uri;\n this.updateIdentifier();\n }\n } catch (error) {\n // Apps and standby displays may not expose playing-content information.\n if (!this.stopped) {\n this.currentUri = undefined;\n this.updateIdentifier();\n }\n this.debug(`${this.config.name}: playing content unavailable`, error);\n }\n } catch (error) {\n if (!this.stopped)\n this.tv.updateCharacteristic(\n this.api.hap.Characteristic.Active,\n new this.api.hap.HapStatusError(this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE),\n );\n this.debug(`${this.config.name}: status unavailable`, error);\n } finally {\n if (!this.stopped) this.save();\n }\n }\n\n private scheduleStatus(): void {\n if (this.stopped) return;\n this.statusTimer = setTimeout(() => {\n void this.poll()\n .catch((error) =>\n this.log.error(`${this.config.name}: status refresh failed`, String(error)),\n )\n .finally(() => this.scheduleStatus());\n }, this.config.updaterate ?? 5000);\n this.statusTimer.unref();\n }\n\n private scheduleSources(): void {\n if (this.stopped || this.config.channelupdaterate === 0) return;\n this.sourceTimer = setTimeout(() => {\n void this.scan()\n .catch((error) =>\n this.log.error(`${this.config.name}: source refresh failed`, String(error)),\n )\n .finally(() => this.scheduleSources());\n }, this.config.channelupdaterate ?? 30000);\n this.sourceTimer.unref();\n }\n\n private sourceType(source: string): number {\n const T = this.api.hap.Characteristic.InputSourceType;\n if (source.includes(\"hdmi\")) return T.HDMI;\n if (source.includes(\"component\")) return T.COMPONENT_VIDEO;\n if (source.includes(\"scart\")) return T.S_VIDEO;\n if (source.includes(\"widi\")) return T.AIRPLAY;\n if (source.includes(\"tv:\") || source.includes(\"dvb\")) return T.TUNER;\n return T.OTHER;\n }\n\n private sourceGroups(): Set<string> {\n const groups = new Set(this.config.sources === undefined ? DEFAULT_SOURCES : undefined);\n if (this.config.sources) for (const entry of this.config.sources) groups.add(entry.source);\n if (this.config.tvsource) groups.add(this.config.tvsource);\n if (this.config.applications?.length) groups.add(\"applications\");\n return groups;\n }\n\n private async scan(): Promise<void> {\n if (this.stopped || !this.power) return;\n const groups = this.sourceGroups();\n for (const [uri, input] of this.inputs) if (!groups.has(input.group)) this.inputs.delete(uri);\n for (const group of groups) {\n if (this.stopped) return;\n try {\n const found: { title?: string | null; uri: string }[] = [];\n if (group === \"applications\") {\n const apps = (await this.client.appControl.getApplicationList()).result[0];\n const filters = this.config.applications ?? [];\n found.push(\n ...apps\n .filter((app) => filters.some((filter) => app.title.includes(filter.title)))\n .sort((a, b) => a.title.localeCompare(b.title)),\n );\n } else {\n let start = 0;\n while (!this.stopped) {\n const page = (\n await this.client.avContent.getContentList({ source: group, stIdx: start, cnt: 100 })\n ).result[0];\n found.push(...page);\n if (page.length < 100) break;\n start += page.length;\n }\n }\n if (this.stopped) return;\n const uris = new Set(found.map((input) => input.uri));\n // Only a successful complete scan is allowed to delete cached inputs.\n for (const [uri, input] of this.inputs)\n if (input.group === group && !uris.has(uri)) this.inputs.delete(uri);\n for (const item of found) {\n const previous = this.inputs.get(item.uri);\n const nextIdentifier = Number(this.accessory.context.nextInputIdentifier ?? 1);\n this.inputs.set(item.uri, {\n ...previous,\n uri: item.uri,\n title: item.title || item.uri,\n group,\n type:\n group === \"applications\"\n ? this.api.hap.Characteristic.InputSourceType.APPLICATION\n : this.sourceType(group),\n identifier: previous?.identifier ?? nextIdentifier,\n });\n if (!previous) this.accessory.context.nextInputIdentifier = nextIdentifier + 1;\n }\n } catch (error) {\n this.debug(`${this.config.name}: cannot scan ${group}`, error);\n }\n }\n if (!this.stopped) {\n this.syncInputs();\n this.save();\n }\n }\n\n private syncInputs(): void {\n const { Service: S, Characteristic: C } = this.api.hap;\n const exposed = [...this.inputs.values()].slice(0, MAX_INPUTS);\n if (this.inputs.size > MAX_INPUTS)\n this.log.warn(\n `${this.config.name}: exposing only ${MAX_INPUTS} inputs to respect HomeKit's service limit; narrow sources/applications.`,\n );\n const wanted = new Set(exposed.map((input) => this.subtype(input.uri)));\n for (let index = this.accessory.services.length - 1; index >= 0; index--) {\n const service = this.accessory.services[index]!;\n if (service.UUID === S.InputSource.UUID && !wanted.has(service.subtype ?? \"\")) {\n this.tv.removeLinkedService(service);\n this.accessory.removeService(service);\n }\n }\n this.services.clear();\n for (const input of exposed) {\n const service =\n this.accessory.getServiceById(S.InputSource, this.subtype(input.uri)) ??\n this.accessory.addService(S.InputSource, input.title, this.subtype(input.uri));\n service\n .updateCharacteristic(C.Identifier, input.identifier)\n .updateCharacteristic(C.ConfiguredName, input.configuredName ?? input.title)\n .updateCharacteristic(C.InputSourceType, input.type)\n .updateCharacteristic(C.IsConfigured, C.IsConfigured.CONFIGURED)\n .updateCharacteristic(\n C.CurrentVisibilityState,\n input.visibility ?? C.CurrentVisibilityState.SHOWN,\n )\n .updateCharacteristic(\n C.TargetVisibilityState,\n input.visibility ?? C.TargetVisibilityState.SHOWN,\n );\n service.getCharacteristic(C.ConfiguredName).onSet((value) => {\n input.configuredName = value as string;\n service.updateCharacteristic(C.ConfiguredName, input.configuredName);\n this.persistInputs();\n this.save();\n });\n service.getCharacteristic(C.TargetVisibilityState).onSet((value) => {\n input.visibility = Number(value);\n service.updateCharacteristic(C.CurrentVisibilityState, input.visibility);\n service.updateCharacteristic(C.TargetVisibilityState, input.visibility);\n this.persistInputs();\n this.save();\n });\n this.tv.addLinkedService(service);\n this.services.set(input.identifier, service);\n }\n this.updateIdentifier();\n this.persistInputs();\n }\n\n private persistInputs(): void {\n this.accessory.context.inputs = [...this.inputs.values()];\n }\n\n private debug(message: string, error: unknown): void {\n if (this.config.debug) this.log.info(message, String(error));\n else this.log.debug(message, String(error));\n }\n\n private subtype(uri: string): string {\n return createHash(\"sha256\").update(uri).digest(\"hex\");\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { BraviaError, type Bravia } from \"@hyjk2000/bravia-sdk\";\nimport type { DynamicPlatformPlugin, Logging, PlatformAccessory } from \"homebridge\";\nimport type { SerializedPlatformAccessory } from \"homebridge/lib/platformAccessory.js\";\nimport { Authentication } from \"./authentication.ts\";\nimport { parseConfig, type BraviaPlatformConfig, type TvConfig } from \"./config.ts\";\nimport type { RuntimeAPI } from \"./hap.ts\";\nimport { Television } from \"./television.ts\";\n\nexport const PLUGIN_NAME = \"@hyjk2000/homebridge-bravia\";\nexport const PLATFORM_NAME = \"BraviaPlatform\";\n\nconst STATE_DIRECTORY = \"hyjk2000-homebridge-bravia\";\nconst STATE_FILE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\.json$/i;\n\ninterface DeviceState {\n version: 1;\n plugin: typeof PLUGIN_NAME;\n uuid: string;\n clientId: string;\n cookie?: string;\n accessory?: SerializedPlatformAccessory;\n}\n\ninterface ConfiguredDevice {\n config: TvConfig;\n uuid: string;\n baseUrl: string;\n}\n\ninterface Device extends ConfiguredDevice {\n state: DeviceState;\n accessory: PlatformAccessory;\n authentication: Authentication;\n client?: Bravia;\n television?: Television;\n published: boolean;\n persistedJson?: string;\n bridgedAccessoryJson?: string;\n retryTimer?: NodeJS.Timeout;\n}\n\nfunction baseUrl(config: TvConfig): string {\n const host = config.ip.includes(\":\") ? `[${config.ip}]` : config.ip;\n return new URL(`http://${host}:${config.port ?? 80}`).origin;\n}\n\nfunction failureDescription(error: unknown): string {\n if (error instanceof BraviaError) {\n return `TV API code ${error.id}`;\n }\n if (typeof error === \"object\" && error !== null) {\n if (\"name\" in error && error.name === \"TimeoutError\") {\n return \"request timed out\";\n }\n if (\"code\" in error && typeof error.code === \"string\" && /^[A-Z_0-9]+$/.test(error.code)) {\n return error.code;\n }\n if (\n \"response\" in error &&\n typeof error.response === \"object\" &&\n error.response !== null &&\n \"status\" in error.response &&\n typeof error.response.status === \"number\"\n ) {\n return `HTTP status ${error.response.status}`;\n }\n }\n // Error objects may contain HTTP headers and credentials; never pass them to the logger.\n return \"connection or initialization error\";\n}\n\nfunction isDeviceState(value: unknown, uuid: string): value is DeviceState {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const state = value as Partial<DeviceState>;\n return (\n state.version === 1 &&\n state.plugin === PLUGIN_NAME &&\n state.uuid === uuid &&\n typeof state.clientId === \"string\" &&\n state.clientId.length > 0 &&\n (state.cookie === undefined || typeof state.cookie === \"string\")\n );\n}\n\nexport class BraviaPlatform implements DynamicPlatformPlugin {\n private readonly configured: ConfiguredDevice[];\n private readonly cached = new Map<string, PlatformAccessory>();\n private readonly devices: Device[] = [];\n private readonly stateDirectory: string;\n private readonly cleanupAllowed: boolean;\n private readonly blockedIdentities = new Set<string>();\n private stopped = false;\n private launched = false;\n private readonly log: Logging;\n private readonly api: RuntimeAPI;\n\n constructor(log: Logging, config: BraviaPlatformConfig | undefined, api: RuntimeAPI) {\n this.log = log;\n this.api = api;\n const tvs = parseConfig(config, log);\n const candidates: ConfiguredDevice[] = [];\n for (const tv of tvs) {\n try {\n const origin = baseUrl(tv);\n const identity = tv.mac\n ? `mac:${tv.mac.replace(/[:-]/g, \"\").toLowerCase()}`\n : `ip:${new URL(origin).hostname.toLowerCase()}`;\n candidates.push({\n config: tv,\n uuid: api.hap.uuid.generate(`${PLUGIN_NAME}:${identity}`),\n baseUrl: origin,\n });\n } catch {\n log.error(\"[%s] Could not construct the TV address; this TV is skipped.\", tv.name);\n }\n }\n const counts = new Map<string, number>();\n for (const device of candidates) {\n counts.set(device.uuid, (counts.get(device.uuid) ?? 0) + 1);\n }\n this.configured = candidates.filter((device) => {\n if (counts.get(device.uuid)! > 1) {\n log.error(\"[%s] Duplicate TV identity; this TV is skipped.\", device.config.name);\n return false;\n }\n return true;\n });\n // An invalid entry is not an intentional removal. Preserve all old state until config is valid.\n this.cleanupAllowed =\n config !== undefined &&\n config.compatibilitymode !== true &&\n Array.isArray(config.tvs) &&\n this.configured.length === config.tvs.length;\n this.stateDirectory = join(api.user.storagePath(), \"plugin-persist\", STATE_DIRECTORY);\n api.on(\"didFinishLaunching\", () => {\n void this.launch().catch((error: unknown) => {\n if (!this.stopped) {\n this.log.error(\"Could not initialize BraviaPlatform (%s).\", failureDescription(error));\n }\n });\n });\n api.on(\"shutdown\", () => this.shutdown());\n }\n\n configureAccessory(accessory: PlatformAccessory): void {\n this.cached.set(accessory.UUID, accessory);\n }\n\n private async launch(): Promise<void> {\n if (this.stopped || this.launched) {\n return;\n }\n this.launched = true;\n try {\n mkdirSync(this.stateDirectory, { recursive: true, mode: 0o700 });\n chmodSync(this.stateDirectory, 0o700);\n } catch {\n this.log.error(\n \"Could not create private BRAVIA storage; check Homebridge storage permissions.\",\n );\n }\n this.removeObsoleteAccessories();\n this.removeObsoleteState();\n // Each task catches its own failure, so one offline or unpaired TV cannot block another.\n await Promise.all(this.configured.map((configured) => this.startDevice(configured)));\n }\n\n private async startDevice(configured: ConfiguredDevice): Promise<void> {\n if (this.stopped || this.blockedIdentities.has(configured.uuid)) {\n return;\n }\n try {\n const state = this.loadState(configured.uuid);\n const cachedAccessory = this.cached.get(configured.uuid);\n let accessory = cachedAccessory;\n if (!accessory && state.accessory) {\n try {\n if (\n state.accessory.UUID !== configured.uuid ||\n state.accessory.plugin !== PLUGIN_NAME ||\n state.accessory.platform !== PLATFORM_NAME\n ) {\n throw new Error(\"Stored accessory identity does not match.\");\n }\n accessory = this.api.platformAccessory.deserialize(state.accessory);\n } catch {\n this.log.warn(\n \"[%s] Could not restore stored TV services; creating a new accessory.\",\n configured.config.name,\n );\n }\n }\n accessory ??= new this.api.platformAccessory(\n configured.config.name,\n configured.uuid,\n this.api.hap.Categories.TELEVISION,\n );\n accessory.displayName = configured.config.name;\n accessory.category = this.api.hap.Categories.TELEVISION;\n const authentication = new Authentication({\n config: configured.config,\n baseUrl: configured.baseUrl,\n cookie: state.cookie,\n clientId: state.clientId,\n log: this.log,\n });\n const device: Device = {\n ...configured,\n state,\n accessory,\n authentication,\n published: configured.config.externalaccessory === false && cachedAccessory !== undefined,\n };\n this.devices.push(device);\n this.markUnavailable(device);\n // Publish restored services before any network request, including while the TV is offline.\n this.publishDevice(device);\n this.saveDevice(device);\n await this.connectDevice(device);\n } catch (error) {\n if (!this.stopped) {\n this.log.error(\n \"[%s] Could not initialize TV (%s).\",\n configured.config.name,\n failureDescription(error),\n );\n }\n }\n }\n\n private async connectDevice(device: Device): Promise<void> {\n if (this.stopped) {\n return;\n }\n try {\n device.client = await device.authentication.authenticate();\n if (this.stopped) {\n return;\n }\n device.state.cookie = device.client.cookie;\n this.saveDevice(device);\n device.television = new Television(\n this.api,\n this.log,\n device.config,\n device.accessory,\n device.client,\n () => {\n if (!this.stopped) {\n this.saveDevice(device);\n }\n },\n );\n await device.television.start();\n if (this.stopped) {\n device.television.stop();\n return;\n }\n this.publishDevice(device);\n this.saveDevice(device);\n } catch (error) {\n if (this.stopped) {\n return;\n }\n this.log.error(\n \"[%s] Could not start TV (%s); initialization will be retried.\",\n device.config.name,\n failureDescription(error),\n );\n try {\n device.television?.stop();\n device.television = undefined;\n this.markUnavailable(device);\n this.publishDevice(device);\n this.saveDevice(device);\n } catch (publishError) {\n this.log.error(\n \"[%s] Could not restore unavailable TV (%s).\",\n device.config.name,\n failureDescription(publishError),\n );\n }\n this.scheduleRetry(device);\n }\n }\n\n private markUnavailable(device: Device): void {\n const service = device.accessory.getService(this.api.hap.Service.Television);\n if (!service) {\n return;\n }\n const unavailable = () => {\n throw new this.api.hap.HapStatusError(this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE);\n };\n service\n .getCharacteristic(this.api.hap.Characteristic.Active)\n .onGet(unavailable)\n .onSet(unavailable);\n }\n\n private scheduleRetry(device: Device): void {\n if (this.stopped || device.retryTimer) {\n return;\n }\n const delay = Math.max(1, Math.min(device.config.updaterate ?? 5000, 2_147_483_647));\n device.retryTimer = setTimeout(() => {\n device.retryTimer = undefined;\n if (!this.stopped) {\n void this.connectDevice(device).catch(() => {\n if (!this.stopped) {\n this.log.error(\"[%s] Could not retry TV initialization.\", device.config.name);\n this.scheduleRetry(device);\n }\n });\n }\n }, delay);\n }\n\n private publishDevice(device: Device): void {\n if (\n this.stopped ||\n device.published ||\n !device.accessory.getService(this.api.hap.Service.Television)\n ) {\n return;\n }\n if (device.config.externalaccessory === false) {\n this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [device.accessory]);\n } else {\n this.api.publishExternalAccessories(PLUGIN_NAME, [device.accessory]);\n }\n device.published = true;\n }\n\n private loadState(uuid: string): DeviceState {\n const path = join(this.stateDirectory, `${uuid}.json`);\n try {\n if (!lstatSync(path).isFile()) {\n throw new Error(\"Private state must be a regular file.\");\n }\n chmodSync(path, 0o600);\n const state: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n if (!isDeviceState(state, uuid)) {\n throw new Error(\"Invalid private device state.\");\n }\n return state;\n } catch (error) {\n if (\n !(typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\")\n ) {\n this.log.warn(\n \"Could not read private TV state for %s; creating a fresh controller session.\",\n uuid,\n );\n }\n }\n return { version: 1, plugin: PLUGIN_NAME, uuid, clientId: `Homebridge:${randomUUID()}` };\n }\n\n private saveDevice(device: Device): void {\n let temporaryPath: string | undefined;\n try {\n if (device.client) {\n device.state.cookie = device.client.cookie;\n }\n if (device.accessory.getService(this.api.hap.Service.Television)) {\n // Homebridge's serializer requires both identifiers, including for external accessories.\n device.accessory._associatedPlugin = PLUGIN_NAME;\n device.accessory._associatedPlatform = PLATFORM_NAME;\n const serialized = this.api.platformAccessory.serialize(device.accessory);\n if (device.config.externalaccessory !== false) {\n device.state.accessory = serialized;\n } else {\n delete device.state.accessory;\n if (!this.stopped && device.published) {\n const accessoryJson = JSON.stringify(serialized);\n if (accessoryJson !== device.bridgedAccessoryJson) {\n this.api.updatePlatformAccessories([device.accessory]);\n device.bridgedAccessoryJson = accessoryJson;\n }\n }\n }\n } else {\n delete device.state.accessory;\n }\n const stateJson = JSON.stringify(device.state);\n if (stateJson === device.persistedJson) {\n return;\n }\n const path = join(this.stateDirectory, `${device.uuid}.json`);\n temporaryPath = `${path}.${randomUUID()}.tmp`;\n writeFileSync(temporaryPath, stateJson, { flag: \"wx\", mode: 0o600 });\n renameSync(temporaryPath, path);\n temporaryPath = undefined;\n device.persistedJson = stateJson;\n } catch {\n this.log.error(\n \"[%s] Could not save private TV state; check Homebridge storage permissions.\",\n device.config.name,\n );\n } finally {\n if (temporaryPath) {\n try {\n unlinkSync(temporaryPath);\n } catch {\n // A failed write may not have created its temporary file.\n }\n }\n }\n }\n\n private removeObsoleteAccessories(): void {\n const configured = new Map(this.configured.map((device) => [device.uuid, device.config]));\n for (const [uuid, accessory] of this.cached) {\n const config = configured.get(uuid);\n if (config?.externalaccessory === false || (!config && !this.cleanupAllowed)) {\n continue;\n }\n try {\n this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);\n if (!config) {\n this.cached.delete(uuid);\n }\n } catch (error) {\n this.log.error(\"Could not remove an obsolete bridged TV (%s).\", failureDescription(error));\n if (config) {\n this.blockedIdentities.add(uuid);\n }\n }\n }\n }\n\n private removeObsoleteState(): void {\n if (!this.cleanupAllowed) {\n return;\n }\n const active = new Set(this.configured.map((device) => `${device.uuid}.json`));\n try {\n for (const entry of readdirSync(this.stateDirectory, { withFileTypes: true })) {\n if (!entry.isFile() || !STATE_FILE.test(entry.name) || active.has(entry.name)) {\n continue;\n }\n try {\n const path = join(this.stateDirectory, entry.name);\n const uuid = entry.name.slice(0, -5);\n const value: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n if (isDeviceState(value, uuid)) {\n unlinkSync(path);\n }\n } catch {\n this.log.warn(\"Could not inspect or remove an obsolete private TV state file.\");\n }\n }\n } catch (error) {\n if (\n !(typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\")\n ) {\n this.log.warn(\"Could not inspect private TV state for obsolete devices.\");\n }\n }\n }\n\n private shutdown(): void {\n if (this.stopped) {\n return;\n }\n this.stopped = true;\n for (const device of this.devices) {\n if (device.retryTimer) {\n clearTimeout(device.retryTimer);\n device.retryTimer = undefined;\n }\n try {\n device.authentication.stop();\n } catch {\n this.log.warn(\"[%s] Could not close the PIN server cleanly.\", device.config.name);\n }\n try {\n device.television?.stop();\n } catch {\n this.log.warn(\"[%s] Could not stop TV activity cleanly.\", device.config.name);\n }\n this.saveDevice(device);\n }\n }\n}\n","import type { API } from \"homebridge\";\nimport { BraviaPlatform, PLATFORM_NAME, PLUGIN_NAME } from \"./platform.ts\";\n\nexport default function initialize(api: API): void {\n api.registerPlatform(PLUGIN_NAME, PLATFORM_NAME, BraviaPlatform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AAS,MAAM,SAAS,WAEnF,KAAK,IAAI,KAAK,0DAA0D;EAE5E;CACF;CAEQ,WAAiB;EACvB,IAAI,KAAK,SACP;EAEF,KAAK,UAAU;EACf,KAAK,MAAM,UAAU,KAAK,SAAS;GACjC,IAAI,OAAO,YAAY;IACrB,aAAa,OAAO,UAAU;IAC9B,OAAO,aAAa,KAAA;GACtB;GACA,IAAI;IACF,OAAO,eAAe,KAAK;GAC7B,QAAQ;IACN,KAAK,IAAI,KAAK,gDAAgD,OAAO,OAAO,IAAI;GAClF;GACA,IAAI;IACF,OAAO,YAAY,KAAK;GAC1B,QAAQ;IACN,KAAK,IAAI,KAAK,4CAA4C,OAAO,OAAO,IAAI;GAC9E;GACA,KAAK,WAAW,MAAM;EACxB;CACF;AACF;;AChfA,SAAwB,WAAW,KAAgB;CACjD,IAAI,iBAAiB,aAAa,eAAe,cAAc;AACjE"}
1
+ {"version":3,"file":"index.js","names":["delay"],"sources":["../authentication.ts","../config.ts","../wake.ts","../television.ts","../platform.ts","../index.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { hostname } from \"node:os\";\nimport { Bravia, BraviaError } from \"@hyjk2000/bravia-sdk\";\nimport type { Logging } from \"homebridge\";\nimport type { TvConfig } from \"./config.ts\";\n\nconst MAX_BODY_BYTES = 1024;\n\nfunction authenticationRequired(error: unknown): boolean {\n if (error instanceof BraviaError) {\n return error.id === 401 || error.id === 403;\n }\n if (typeof error !== \"object\" || error === null || !(\"response\" in error)) {\n return false;\n }\n const response = error.response;\n return (\n typeof response === \"object\" &&\n response !== null &&\n \"status\" in response &&\n (response.status === 401 || response.status === 403)\n );\n}\n\nfunction respond(response: ServerResponse, status: number, body: string, html = false): void {\n if (response.destroyed || response.writableEnded) {\n return;\n }\n response.writeHead(status, {\n \"Content-Type\": html ? \"text/html; charset=utf-8\" : \"text/plain; charset=utf-8\",\n \"Content-Length\": Buffer.byteLength(body),\n \"Cache-Control\": \"no-store\",\n \"Content-Security-Policy\":\n \"default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'\",\n \"X-Content-Type-Options\": \"nosniff\",\n \"Referrer-Policy\": \"same-origin\",\n Connection: \"close\",\n });\n response.end(body);\n}\n\nclass FormError extends Error {\n readonly status: number;\n\n constructor(status: number, message: string) {\n super(message);\n this.status = status;\n }\n}\n\nfunction readForm(request: IncomingMessage): Promise<URLSearchParams> {\n const { promise, resolve, reject } = Promise.withResolvers<URLSearchParams>();\n let size = 0;\n let complete = false;\n const chunks: Buffer[] = [];\n request.on(\"data\", (chunk: Buffer) => {\n if (complete) {\n return;\n }\n size += chunk.length;\n if (size > MAX_BODY_BYTES) {\n complete = true;\n chunks.length = 0;\n reject(new FormError(413, \"Request body is too large.\\n\"));\n return;\n }\n chunks.push(chunk);\n });\n request.on(\"end\", () => {\n if (!complete) {\n complete = true;\n resolve(new URLSearchParams(Buffer.concat(chunks, size).toString(\"utf8\")));\n }\n });\n request.on(\"error\", () => {\n if (!complete) {\n complete = true;\n reject(new FormError(400, \"Could not read request.\\n\"));\n }\n });\n request.on(\"aborted\", () => {\n if (!complete) {\n complete = true;\n reject(new FormError(400, \"Request was interrupted.\\n\"));\n }\n });\n return promise;\n}\n\ninterface PendingRegistration {\n client: Bravia;\n resolve: (client: Bravia) => void;\n reject: (error: Error) => void;\n}\n\nexport interface AuthenticationOptions {\n config: TvConfig;\n baseUrl: string;\n cookie?: string;\n clientId: string;\n log: Logging;\n}\n\n/** A single TV's registration session; the HTTP server exists only while a PIN is needed. */\nexport class Authentication {\n private stopped = false;\n private server?: Server;\n private pending?: PendingRegistration;\n private submitting = false;\n private client?: Bravia;\n private readonly formToken = randomBytes(24).toString(\"base64url\");\n\n private readonly options: AuthenticationOptions;\n\n constructor(options: AuthenticationOptions) {\n this.options = options;\n }\n\n async authenticate(): Promise<Bravia> {\n this.assertRunning();\n const { baseUrl, config, clientId } = this.options;\n const cookie = this.client?.cookie ?? this.options.cookie;\n let client = new Bravia({ baseUrl, cookie, psk: config.psk });\n this.client = client;\n if (cookie || config.psk) {\n try {\n await client.system.getPowerStatus();\n this.assertRunning();\n return client;\n } catch (error) {\n this.assertRunning();\n if (!authenticationRequired(error)) {\n throw error;\n }\n }\n }\n\n // Never reuse a rejected cookie or PSK for PIN-based registration.\n client = new Bravia({ baseUrl });\n this.client = client;\n const registeredCookie = await client.accessControl.actRegister({\n clientid: clientId,\n nickname: \"Homebridge Bravia\",\n });\n this.assertRunning();\n if (registeredCookie) {\n return client;\n }\n return this.waitForPin(client);\n }\n\n stop(): void {\n this.stopped = true;\n const pending = this.pending;\n this.pending = undefined;\n pending?.reject(new Error(\"TV authentication stopped.\"));\n this.closeServer(true);\n }\n\n private assertRunning(): void {\n if (this.stopped) {\n throw new Error(\"TV authentication stopped.\");\n }\n }\n\n private waitForPin(client: Bravia): Promise<Bravia> {\n this.assertRunning();\n const { promise, resolve, reject } = Promise.withResolvers<Bravia>();\n this.pending = { client, resolve, reject };\n const server = createServer({ maxHeaderSize: 8192 }, (request, response) => {\n void this.handleRequest(request, response).catch(() => {\n this.options.log.error(\"[%s] Could not handle the PIN request.\", this.options.config.name);\n respond(response, 500, \"Could not process request.\\n\");\n });\n });\n this.server = server;\n server.requestTimeout = 30_000;\n server.headersTimeout = 10_000;\n server.setTimeout(30_000, (socket) => socket.destroy());\n server.on(\"error\", () => {\n const pending = this.pending;\n this.pending = undefined;\n this.options.log.error(\n \"[%s] Could not listen for PIN registration.\",\n this.options.config.name,\n );\n pending?.reject(new Error(\"Could not start the local PIN server.\"));\n this.closeServer(true);\n });\n try {\n server.listen(0, \"0.0.0.0\", () => {\n if (this.stopped) {\n this.closeServer(true);\n return;\n }\n const address = server.address() as AddressInfo;\n this.options.log.info(\n \"[%s] Enter the PIN displayed by the TV at http://%s:%s/%s\",\n this.options.config.name,\n hostname(),\n address.port,\n this.formToken,\n );\n });\n } catch {\n this.pending = undefined;\n this.closeServer(true);\n reject(new Error(\"Could not start the local PIN server.\"));\n }\n return promise;\n }\n\n private async handleRequest(request: IncomingMessage, response: ServerResponse): Promise<void> {\n if (this.stopped || !this.pending) {\n respond(response, 503, \"Registration is not available.\\n\");\n request.resume();\n return;\n }\n const origin = request.headers.origin;\n if (origin && origin !== `http://${request.headers.host}`) {\n respond(response, 403, \"Invalid request origin.\\n\");\n request.resume();\n return;\n }\n const formPath = `/${this.formToken}`;\n if (request.method === \"GET\" && request.url === formPath) {\n respond(\n response,\n 200,\n `<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><title>Pair BRAVIA TV</title><h1>Pair BRAVIA TV</h1><p>Enter the PIN displayed by your TV.</p><form method=\"post\" action=\"${formPath}/pair\"><label>PIN <input type=\"password\" name=\"pin\" inputmode=\"numeric\" autocomplete=\"off\" maxlength=\"16\" required></label><button type=\"submit\">Pair</button></form></html>`,\n true,\n );\n request.resume();\n return;\n }\n if (request.url !== `${formPath}/pair`) {\n respond(response, 404, \"Not found.\\n\");\n request.resume();\n return;\n }\n if (request.method !== \"POST\") {\n respond(response, 405, \"Use POST to submit the PIN.\\n\");\n request.resume();\n return;\n }\n if (\n request.headers[\"content-type\"]?.split(\";\", 1)[0]?.trim() !==\n \"application/x-www-form-urlencoded\"\n ) {\n respond(response, 415, \"Use the PIN form to submit a request.\\n\");\n request.resume();\n return;\n }\n let form: URLSearchParams;\n try {\n form = await readForm(request);\n } catch (error) {\n respond(\n response,\n error instanceof FormError ? error.status : 400,\n error instanceof FormError ? error.message : \"Invalid request.\\n\",\n );\n request.resume();\n return;\n }\n const pin = form.get(\"pin\");\n if (!pin || !/^\\d{1,16}$/.test(pin)) {\n respond(response, 400, \"Enter the numeric PIN displayed by the TV.\\n\");\n return;\n }\n if (this.submitting) {\n respond(response, 409, \"A registration request is already in progress.\\n\");\n return;\n }\n const pending = this.pending;\n if (this.stopped || !pending) {\n respond(response, 503, \"Registration is not available.\\n\");\n return;\n }\n this.submitting = true;\n try {\n const cookie = await pending.client.accessControl.actRegister({\n clientid: this.options.clientId,\n nickname: \"Homebridge Bravia\",\n pin,\n });\n if (this.stopped || this.pending !== pending) {\n respond(response, 503, \"Registration has stopped.\\n\");\n return;\n }\n if (!cookie) {\n respond(response, 401, \"The TV did not accept the PIN. Reload the form and try again.\\n\");\n return;\n }\n this.pending = undefined;\n respond(response, 200, \"TV paired. You may close this page.\\n\");\n pending.resolve(pending.client);\n this.closeServer(false);\n } catch {\n this.options.log.warn(\n \"[%s] TV registration failed; try submitting the PIN again.\",\n this.options.config.name,\n );\n respond(response, 502, \"TV registration failed. Reload the form and try again.\\n\");\n } finally {\n this.submitting = false;\n }\n }\n\n private closeServer(force: boolean): void {\n const server = this.server;\n if (!server) {\n return;\n }\n server.close(() => {\n if (this.server === server) {\n this.server = undefined;\n }\n });\n if (force) {\n server.closeAllConnections();\n }\n }\n}\n","import { isIP } from \"node:net\";\nimport type { Logging, PlatformConfig } from \"homebridge\";\n\nexport interface TvConfig {\n name: string;\n ip: string;\n port?: number | string;\n mac?: string;\n woladdress?: string;\n tvsource?: string;\n soundoutput?: string;\n updaterate?: number;\n channelupdaterate?: number;\n starttimeout?: number;\n sources?: { source: string }[];\n applications?: { title: string }[];\n psk?: string;\n externalaccessory?: boolean;\n debug?: boolean;\n}\n\nexport interface BraviaPlatformConfig extends PlatformConfig {\n tvs?: TvConfig[];\n}\n\nfunction isHost(value: unknown): value is string {\n if (typeof value !== \"string\" || !value || value.length > 253) return false;\n if (isIP(value)) return true;\n return value.split(\".\").every((label) => /^[a-z\\d](?:[a-z\\d-]{0,61}[a-z\\d])?$/i.test(label));\n}\n\nfunction isPort(value: unknown): boolean {\n return (\n (typeof value === \"number\" || (typeof value === \"string\" && /^\\d+$/.test(value))) &&\n Number.isInteger(Number(value)) &&\n Number(value) >= 1 &&\n Number(value) <= 65535\n );\n}\n\nexport function parseConfig(config: BraviaPlatformConfig | undefined, log: Logging): TvConfig[] {\n if (!config) return [];\n if (config.compatibilitymode === true) {\n log.error(\n \"compatibilitymode is unsupported: the legacy implementation sent authentication to an unrelated public host. Remove it and use local TV authentication.\",\n );\n return [];\n }\n if (config.tvs === undefined) return [];\n if (!Array.isArray(config.tvs)) {\n log.error(\"BraviaPlatform: tvs must be an array.\");\n return [];\n }\n const candidates: { tv: TvConfig; index: number; keys: string[] }[] = [];\n const counts = new Map<string, number>();\n for (const [index, entry] of config.tvs.entries()) {\n const errors: string[] = [];\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n log.error(`BraviaPlatform: TV ${index + 1} must be an object.`);\n continue;\n }\n const raw = entry as unknown as Record<string, unknown>;\n if (raw.compatibilitymode === true)\n errors.push(\n \"compatibilitymode is unsafe and unsupported: legacy authentication was sent to an unrelated public host; remove it\",\n );\n if (typeof raw.name !== \"string\" || !raw.name.trim())\n errors.push(\"name must be a nonempty string\");\n if (!isHost(raw.ip))\n errors.push(\n \"ip must be an IP address or hostname, without a URL scheme, path, port, or credentials\",\n );\n if (raw.port !== undefined && !isPort(raw.port))\n errors.push(\"port must be an integer from 1 to 65535\");\n if (\n raw.mac !== undefined &&\n (typeof raw.mac !== \"string\" ||\n !/^(?:[\\da-f]{2}:){5}[\\da-f]{2}$|^(?:[\\da-f]{2}-){5}[\\da-f]{2}$/i.test(raw.mac))\n )\n errors.push(\"mac must contain six colon- or hyphen-separated hexadecimal octets\");\n if (raw.woladdress !== undefined && !isHost(raw.woladdress))\n errors.push(\"woladdress must be an IP address or hostname\");\n for (const field of [\"updaterate\", \"channelupdaterate\", \"starttimeout\"] as const) {\n const value = raw[field];\n if (\n value !== undefined &&\n (typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n (field === \"channelupdaterate\" ? value < 0 : value <= 0))\n )\n errors.push(\n `${field} must be ${field === \"channelupdaterate\" ? \"nonnegative (0 disables polling)\" : \"positive\"}`,\n );\n }\n for (const field of [\"tvsource\", \"soundoutput\", \"psk\"] as const) {\n if (raw[field] !== undefined && typeof raw[field] !== \"string\")\n errors.push(`${field} must be a string`);\n }\n for (const field of [\"externalaccessory\", \"debug\"] as const) {\n if (raw[field] !== undefined && typeof raw[field] !== \"boolean\")\n errors.push(`${field} must be a boolean`);\n }\n if (\n raw.sources !== undefined &&\n (!Array.isArray(raw.sources) ||\n !raw.sources.every(\n (value) =>\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n typeof value.source === \"string\" &&\n value.source.trim(),\n ))\n )\n errors.push(\"sources must be a list of objects with nonempty source categories\");\n if (\n raw.applications !== undefined &&\n (!Array.isArray(raw.applications) ||\n !raw.applications.every(\n (value) =>\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n typeof value.title === \"string\" &&\n value.title.trim(),\n ))\n )\n errors.push(\"applications must be a list of objects with nonempty titles\");\n if (errors.length) {\n log.error(`BraviaPlatform: TV ${index + 1} is invalid: ${errors.join(\"; \")}.`);\n continue;\n }\n const tv: TvConfig = {\n ...entry,\n name: entry.name.trim(),\n externalaccessory: entry.externalaccessory ?? true,\n };\n const keys = [`name:${tv.name.toLowerCase()}`, `host:${tv.ip.toLowerCase()}`];\n if (tv.mac) keys.push(`mac:${tv.mac.replace(/[:-]/g, \"\").toLowerCase()}`);\n for (const key of keys) counts.set(key, (counts.get(key) ?? 0) + 1);\n candidates.push({ tv, index, keys });\n }\n return candidates\n .filter(({ index, keys }) => {\n const duplicates = keys.filter((key) => counts.get(key)! > 1);\n if (!duplicates.length) return true;\n log.error(\n `BraviaPlatform: TV ${index + 1} has a duplicate name or device identity; every colliding entry is skipped.`,\n );\n return false;\n })\n .map(({ tv }) => tv);\n}\n","import { createSocket } from \"node:dgram\";\n\n/** Resolve only after the broadcast has been handed to the network stack. */\nexport function wake(mac: string, address: string): Promise<void> {\n const hardwareAddress = Buffer.from(mac.replace(/[:-]/g, \"\"), \"hex\");\n const packet = Buffer.alloc(102, 0xff);\n for (let offset = 6; offset < packet.length; offset += 6) {\n hardwareAddress.copy(packet, offset);\n }\n const { promise, resolve, reject } = Promise.withResolvers<void>();\n const socket = createSocket(\"udp4\");\n let finished = false;\n const finish = (error?: Error | null) => {\n if (finished) return;\n finished = true;\n socket.close();\n if (error) reject(error);\n else resolve();\n };\n socket.once(\"error\", finish);\n socket.bind(() => {\n try {\n socket.setBroadcast(true);\n socket.send(packet, 9, address, finish);\n } catch (error) {\n finish(error instanceof Error ? error : new Error(String(error)));\n }\n });\n return promise;\n}\n","import { createHash } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport {\n Bravia,\n IRCC_CODES,\n type InterfaceInformation,\n type SystemInformation,\n} from \"@hyjk2000/bravia-sdk\";\nimport type { CharacteristicValue, Logging, PlatformAccessory, Service } from \"homebridge\";\nimport type { TvConfig } from \"./config.ts\";\nimport type { RuntimeAPI } from \"./hap.ts\";\nimport { wake } from \"./wake.ts\";\n\ninterface Input {\n uri: string;\n title: string;\n group: string;\n type: number;\n identifier: number;\n configuredName?: string;\n visibility?: number;\n}\n\ntype StatusChange = { power: boolean } | { uri: string | undefined } | { powerUnavailable: true };\n\nconst DEFAULT_SOURCES = [\n \"extInput:hdmi\",\n \"extInput:component\",\n \"extInput:scart\",\n \"extInput:cec\",\n \"extInput:widi\",\n];\n// Leave room for the information, TV, speaker and protocol services (HAP limit: 100).\nconst MAX_INPUTS = 95;\n\nexport class Television {\n private readonly tv: Service;\n private readonly speaker: Service;\n private readonly information: Service;\n private readonly inputs = new Map<string, Input>();\n private readonly services = new Map<number, Service>();\n private readonly abort = new AbortController();\n private statusTimer?: NodeJS.Timeout;\n private sourceTimer?: NodeJS.Timeout;\n private stopped = false;\n private power = false;\n private currentUri?: string;\n private statusRevision = 0;\n private boot?: Promise<void>;\n private readonly api: RuntimeAPI;\n private readonly log: Logging;\n private readonly config: TvConfig;\n private readonly accessory: PlatformAccessory;\n private readonly client: Bravia;\n private readonly save: () => void;\n\n constructor(\n api: RuntimeAPI,\n log: Logging,\n config: TvConfig,\n accessory: PlatformAccessory,\n client: Bravia,\n save: () => void,\n ) {\n this.api = api;\n this.log = log;\n this.config = config;\n this.accessory = accessory;\n this.client = client;\n this.save = save;\n const { Service: S, Characteristic: C } = api.hap;\n accessory.category = api.hap.Categories.TELEVISION;\n this.information =\n accessory.getService(S.AccessoryInformation) ?? accessory.addService(S.AccessoryInformation);\n this.tv = accessory.getService(S.Television) ?? accessory.addService(S.Television, config.name);\n this.speaker =\n accessory.getService(S.TelevisionSpeaker) ??\n accessory.addService(S.TelevisionSpeaker, config.soundoutput ?? \"speaker\");\n this.tv.setPrimaryService();\n this.tv.addLinkedService(this.speaker);\n this.tv\n .setCharacteristic(C.ConfiguredName, config.name)\n .setCharacteristic(C.SleepDiscoveryMode, C.SleepDiscoveryMode.ALWAYS_DISCOVERABLE);\n this.speaker\n .setCharacteristic(C.Active, C.Active.ACTIVE)\n .setCharacteristic(C.VolumeControlType, C.VolumeControlType.ABSOLUTE);\n const interfaceInfo = accessory.context.interfaceInfo as InterfaceInformation | undefined;\n const systemInfo = accessory.context.systemInfo as SystemInformation | undefined;\n this.information\n .setCharacteristic(C.Manufacturer, interfaceInfo?.productName || \"Sony\")\n .setCharacteristic(C.Model, systemInfo?.model || interfaceInfo?.modelName || \"Bravia TV\")\n .setCharacteristic(\n C.SerialNumber,\n systemInfo?.serial || systemInfo?.macAddr || accessory.UUID,\n );\n\n const groups = this.sourceGroups();\n for (const input of (accessory.context.inputs ?? []) as Input[]) {\n if (\n groups.has(input.group) &&\n (input.group !== \"applications\" ||\n config.applications?.some((filter) => input.title.includes(filter.title)))\n )\n this.inputs.set(input.uri, input);\n }\n this.syncInputs();\n this.tv\n .getCharacteristic(C.Active)\n .onGet(() => this.handle(async () => Number(await this.readPower())))\n .onSet((value) => this.handle(() => this.setPower(Number(value) === C.Active.ACTIVE)));\n this.tv\n .getCharacteristic(C.ActiveIdentifier)\n .onGet(() => this.activeIdentifier)\n .onSet((value) => this.handle(() => this.selectInput(Number(value))));\n const keys = new Map<number, string>([\n [C.RemoteKey.REWIND, IRCC_CODES.Rewind],\n [C.RemoteKey.FAST_FORWARD, IRCC_CODES.Forward],\n [C.RemoteKey.NEXT_TRACK, IRCC_CODES.Next],\n [C.RemoteKey.PREVIOUS_TRACK, IRCC_CODES.Prev],\n [C.RemoteKey.ARROW_UP, IRCC_CODES.Up],\n [C.RemoteKey.ARROW_DOWN, IRCC_CODES.Down],\n [C.RemoteKey.ARROW_LEFT, IRCC_CODES.Left],\n [C.RemoteKey.ARROW_RIGHT, IRCC_CODES.Right],\n [C.RemoteKey.SELECT, IRCC_CODES.Confirm],\n [C.RemoteKey.BACK, IRCC_CODES.Back],\n [C.RemoteKey.EXIT, IRCC_CODES.Exit],\n [C.RemoteKey.PLAY_PAUSE, IRCC_CODES.Play],\n [C.RemoteKey.INFORMATION, IRCC_CODES.Display],\n ]);\n this.tv.getCharacteristic(C.RemoteKey).onSet((value) =>\n this.handle(async () => {\n const code = keys.get(Number(value));\n if (code) await this.client.ircc.sendCode(code);\n else throw new api.hap.HapStatusError(api.hap.HAPStatus.INVALID_VALUE_IN_REQUEST);\n }),\n );\n this.speaker\n .getCharacteristic(C.VolumeSelector)\n .onSet((value) =>\n this.handle(() =>\n this.client.ircc.sendCode(\n Number(value) === C.VolumeSelector.INCREMENT\n ? IRCC_CODES.VolumeUp\n : IRCC_CODES.VolumeDown,\n ),\n ),\n );\n this.speaker\n .getCharacteristic(C.Mute)\n .onGet(() => this.handle(async () => (this.power ? (await this.readAudio()).mute : false)))\n .onSet((value) =>\n this.handle(async () => {\n if (this.power) await this.client.audio.setAudioMute({ status: Boolean(value) });\n }),\n );\n this.speaker\n .getCharacteristic(C.Volume)\n .onGet(() =>\n this.handle(async () => (this.power ? Number((await this.readAudio()).volume) : 0)),\n )\n .onSet((value) =>\n this.handle(async () => {\n if (this.power)\n await this.client.audio.setAudioVolume({\n target: config.soundoutput ?? \"speaker\",\n volume: String(value as number),\n });\n }),\n );\n }\n\n async start(): Promise<void> {\n if (this.stopped) return;\n await this.probeInformation();\n if (this.stopped) return;\n await this.poll();\n if (this.stopped) return;\n await this.scan();\n this.scheduleStatus();\n this.scheduleSources();\n }\n\n stop(): void {\n this.stopped = true;\n this.abort.abort();\n clearTimeout(this.statusTimer);\n clearTimeout(this.sourceTimer);\n }\n\n private async handle<T extends CharacteristicValue | void>(\n operation: () => Promise<T>,\n ): Promise<T> {\n try {\n if (this.stopped) throw new Error(\"Plugin is shutting down\");\n return await operation();\n } catch (error) {\n this.debug(`${this.config.name}: command failed`, error);\n if (error instanceof this.api.hap.HapStatusError) throw error;\n throw new this.api.hap.HapStatusError(this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE);\n } finally {\n if (!this.stopped) this.save();\n }\n }\n\n private async probeInformation(): Promise<void> {\n const { Characteristic: C } = this.api.hap;\n let interfaceInfo = this.accessory.context.interfaceInfo as InterfaceInformation | undefined;\n let systemInfo = this.accessory.context.systemInfo as SystemInformation | undefined;\n try {\n interfaceInfo = (await this.client.system.getInterfaceInformation()).result[0];\n this.accessory.context.interfaceInfo = interfaceInfo;\n } catch (error) {\n this.debug(`${this.config.name}: interface information unavailable`, error);\n }\n if (this.stopped) return;\n try {\n systemInfo = (await this.client.system.getSystemInformation()).result[0];\n this.accessory.context.systemInfo = systemInfo;\n } catch (error) {\n this.debug(`${this.config.name}: system information unavailable`, error);\n }\n if (this.stopped) return;\n this.information\n .setCharacteristic(C.Manufacturer, interfaceInfo?.productName || \"Sony\")\n .setCharacteristic(C.Model, systemInfo?.model || interfaceInfo?.modelName || \"Bravia TV\")\n .setCharacteristic(\n C.SerialNumber,\n systemInfo?.serial || systemInfo?.macAddr || this.accessory.UUID,\n );\n this.save();\n }\n\n private async readPower(revision = this.statusRevision): Promise<boolean> {\n try {\n const on = (await this.client.system.getPowerStatus()).result[0].status === \"active\";\n this.commitStatus({ power: on }, revision);\n } catch (error) {\n if (revision === this.statusRevision) throw error;\n }\n // A HomeKit getter must return the committed value, not the superseded response.\n return this.power;\n }\n\n private async setPower(on: boolean): Promise<void> {\n if (this.config.mac) {\n if (on) await wake(this.config.mac, this.config.woladdress ?? \"255.255.255.255\");\n else await this.client.ircc.sendCode(IRCC_CODES.PowerOff);\n } else {\n await this.client.system.setPowerStatus({ status: on });\n }\n this.commitStatus({ power: on });\n }\n\n private async selectInput(identifier: number): Promise<void> {\n const input = [...this.inputs.values()].find((entry) => entry.identifier === identifier);\n if (!input || !this.services.has(identifier))\n throw new this.api.hap.HapStatusError(this.api.hap.HAPStatus.INVALID_VALUE_IN_REQUEST);\n if (!this.power) {\n this.boot ??= (async () => {\n await this.setPower(true);\n await delay(this.config.starttimeout ?? 5000, undefined, { signal: this.abort.signal });\n })().finally(() => {\n this.boot = undefined;\n });\n }\n if (this.boot) await this.boot;\n if (this.stopped) return;\n if (input.type === this.api.hap.Characteristic.InputSourceType.APPLICATION) {\n await this.client.appControl.setActiveApp({ uri: input.uri });\n } else {\n await this.client.avContent.setPlayContent({ uri: input.uri });\n }\n this.commitStatus({ uri: input.uri });\n }\n\n private async readAudio() {\n const values = (await this.client.audio.getVolumeInformation()).result[0];\n const output = values.find((value) => value.target === (this.config.soundoutput ?? \"speaker\"));\n if (!output) throw new Error(\"Configured audio output is unavailable\");\n return output;\n }\n\n private get activeIdentifier(): number {\n const identifier = this.currentUri ? (this.inputs.get(this.currentUri)?.identifier ?? 0) : 0;\n return this.services.has(identifier) ? identifier : 0;\n }\n\n private commitStatus(change: StatusChange, observedAt?: number): void {\n if (this.stopped) return;\n // Successful commands supersede observations already in flight, not future polls.\n if (observedAt === undefined) this.statusRevision++;\n else if (observedAt !== this.statusRevision) return;\n\n const { Characteristic: C, HapStatusError, HAPStatus } = this.api.hap;\n if (\"power\" in change) {\n this.power = change.power;\n if (!change.power) this.currentUri = undefined;\n this.tv.updateCharacteristic(C.Active, Number(change.power));\n if (!change.power) this.updateIdentifier();\n } else if (\"uri\" in change) {\n this.currentUri = change.uri;\n this.updateIdentifier();\n } else {\n this.tv.updateCharacteristic(\n C.Active,\n new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE),\n );\n }\n }\n\n private updateIdentifier(): void {\n this.tv.updateCharacteristic(\n this.api.hap.Characteristic.ActiveIdentifier,\n this.activeIdentifier,\n );\n }\n\n private async poll(): Promise<void> {\n const revision = this.statusRevision;\n try {\n if (!(await this.readPower(revision)) || this.stopped || revision !== this.statusRevision)\n return;\n try {\n const uri = (await this.client.avContent.getPlayingContentInfo()).result[0].uri;\n this.commitStatus({ uri }, revision);\n } catch (error) {\n // Sony may not identify app playback. Keep the last known input until a read\n // identifies different content or the TV reports standby.\n this.debug(`${this.config.name}: playing content unavailable`, error);\n }\n } catch (error) {\n this.commitStatus({ powerUnavailable: true }, revision);\n this.debug(`${this.config.name}: status unavailable`, error);\n } finally {\n if (!this.stopped) this.save();\n }\n }\n\n private scheduleStatus(): void {\n if (this.stopped) return;\n this.statusTimer = setTimeout(() => {\n void this.poll()\n .catch((error) =>\n this.log.error(`${this.config.name}: status refresh failed`, String(error)),\n )\n .finally(() => this.scheduleStatus());\n }, this.config.updaterate ?? 5000);\n this.statusTimer.unref();\n }\n\n private scheduleSources(): void {\n if (this.stopped || this.config.channelupdaterate === 0) return;\n this.sourceTimer = setTimeout(() => {\n void this.scan()\n .catch((error) =>\n this.log.error(`${this.config.name}: source refresh failed`, String(error)),\n )\n .finally(() => this.scheduleSources());\n }, this.config.channelupdaterate ?? 30000);\n this.sourceTimer.unref();\n }\n\n private sourceType(source: string): number {\n const T = this.api.hap.Characteristic.InputSourceType;\n if (source.includes(\"hdmi\")) return T.HDMI;\n if (source.includes(\"component\")) return T.COMPONENT_VIDEO;\n if (source.includes(\"scart\")) return T.S_VIDEO;\n if (source.includes(\"widi\")) return T.AIRPLAY;\n if (source.includes(\"tv:\") || source.includes(\"dvb\")) return T.TUNER;\n return T.OTHER;\n }\n\n private sourceGroups(): Set<string> {\n const groups = new Set(this.config.sources === undefined ? DEFAULT_SOURCES : undefined);\n if (this.config.sources) for (const entry of this.config.sources) groups.add(entry.source);\n if (this.config.tvsource) groups.add(this.config.tvsource);\n if (this.config.applications?.length) groups.add(\"applications\");\n return groups;\n }\n\n private async scan(): Promise<void> {\n if (this.stopped || !this.power) return;\n const groups = this.sourceGroups();\n for (const [uri, input] of this.inputs) if (!groups.has(input.group)) this.inputs.delete(uri);\n for (const group of groups) {\n if (this.stopped) return;\n try {\n const found: { title?: string | null; uri: string }[] = [];\n if (group === \"applications\") {\n const apps = (await this.client.appControl.getApplicationList()).result[0];\n const filters = this.config.applications ?? [];\n found.push(\n ...apps\n .filter((app) => filters.some((filter) => app.title.includes(filter.title)))\n .sort((a, b) => a.title.localeCompare(b.title)),\n );\n } else {\n let start = 0;\n while (!this.stopped) {\n const page = (\n await this.client.avContent.getContentList({ source: group, stIdx: start, cnt: 100 })\n ).result[0];\n found.push(...page);\n if (page.length < 100) break;\n start += page.length;\n }\n }\n if (this.stopped) return;\n const uris = new Set(found.map((input) => input.uri));\n // Only a successful complete scan is allowed to delete cached inputs.\n for (const [uri, input] of this.inputs)\n if (input.group === group && !uris.has(uri)) this.inputs.delete(uri);\n for (const item of found) {\n const previous = this.inputs.get(item.uri);\n const nextIdentifier = Number(this.accessory.context.nextInputIdentifier ?? 1);\n this.inputs.set(item.uri, {\n ...previous,\n uri: item.uri,\n title: item.title || item.uri,\n group,\n type:\n group === \"applications\"\n ? this.api.hap.Characteristic.InputSourceType.APPLICATION\n : this.sourceType(group),\n identifier: previous?.identifier ?? nextIdentifier,\n });\n if (!previous) this.accessory.context.nextInputIdentifier = nextIdentifier + 1;\n }\n } catch (error) {\n this.debug(`${this.config.name}: cannot scan ${group}`, error);\n }\n }\n if (!this.stopped) {\n this.syncInputs();\n this.save();\n }\n }\n\n private syncInputs(): void {\n const { Service: S, Characteristic: C } = this.api.hap;\n const exposed = [...this.inputs.values()].slice(0, MAX_INPUTS);\n if (this.inputs.size > MAX_INPUTS)\n this.log.warn(\n `${this.config.name}: exposing only ${MAX_INPUTS} inputs to respect HomeKit's service limit; narrow sources/applications.`,\n );\n const wanted = new Set(exposed.map((input) => this.subtype(input.uri)));\n for (let index = this.accessory.services.length - 1; index >= 0; index--) {\n const service = this.accessory.services[index]!;\n if (service.UUID === S.InputSource.UUID && !wanted.has(service.subtype ?? \"\")) {\n this.tv.removeLinkedService(service);\n this.accessory.removeService(service);\n }\n }\n this.services.clear();\n for (const input of exposed) {\n const service =\n this.accessory.getServiceById(S.InputSource, this.subtype(input.uri)) ??\n this.accessory.addService(S.InputSource, input.title, this.subtype(input.uri));\n service\n .updateCharacteristic(C.Identifier, input.identifier)\n .updateCharacteristic(C.ConfiguredName, input.configuredName ?? input.title)\n .updateCharacteristic(C.InputSourceType, input.type)\n .updateCharacteristic(C.IsConfigured, C.IsConfigured.CONFIGURED)\n .updateCharacteristic(\n C.CurrentVisibilityState,\n input.visibility ?? C.CurrentVisibilityState.SHOWN,\n )\n .updateCharacteristic(\n C.TargetVisibilityState,\n input.visibility ?? C.TargetVisibilityState.SHOWN,\n );\n service.getCharacteristic(C.ConfiguredName).onSet((value) => {\n input.configuredName = value as string;\n service.updateCharacteristic(C.ConfiguredName, input.configuredName);\n this.persistInputs();\n this.save();\n });\n service.getCharacteristic(C.TargetVisibilityState).onSet((value) => {\n input.visibility = Number(value);\n service.updateCharacteristic(C.CurrentVisibilityState, input.visibility);\n service.updateCharacteristic(C.TargetVisibilityState, input.visibility);\n this.persistInputs();\n this.save();\n });\n this.tv.addLinkedService(service);\n this.services.set(input.identifier, service);\n }\n this.updateIdentifier();\n this.persistInputs();\n }\n\n private persistInputs(): void {\n this.accessory.context.inputs = [...this.inputs.values()];\n }\n\n private debug(message: string, error: unknown): void {\n if (this.config.debug) this.log.info(message, String(error));\n else this.log.debug(message, String(error));\n }\n\n private subtype(uri: string): string {\n return createHash(\"sha256\").update(uri).digest(\"hex\");\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { BraviaError, type Bravia } from \"@hyjk2000/bravia-sdk\";\nimport type { DynamicPlatformPlugin, Logging, PlatformAccessory } from \"homebridge\";\nimport type { SerializedPlatformAccessory } from \"homebridge/lib/platformAccessory.js\";\nimport { Authentication } from \"./authentication.ts\";\nimport { parseConfig, type BraviaPlatformConfig, type TvConfig } from \"./config.ts\";\nimport type { RuntimeAPI } from \"./hap.ts\";\nimport { Television } from \"./television.ts\";\n\nexport const PLUGIN_NAME = \"@hyjk2000/homebridge-bravia\";\nexport const PLATFORM_NAME = \"BraviaPlatform\";\n\nconst STATE_DIRECTORY = \"hyjk2000-homebridge-bravia\";\nconst STATE_FILE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\.json$/i;\n\ninterface DeviceState {\n version: 1;\n plugin: typeof PLUGIN_NAME;\n uuid: string;\n clientId: string;\n cookie?: string;\n accessory?: SerializedPlatformAccessory;\n}\n\ninterface ConfiguredDevice {\n config: TvConfig;\n uuid: string;\n baseUrl: string;\n}\n\ninterface Device extends ConfiguredDevice {\n state: DeviceState;\n accessory: PlatformAccessory;\n authentication: Authentication;\n client?: Bravia;\n television?: Television;\n published: boolean;\n persistedJson?: string;\n bridgedAccessoryJson?: string;\n retryTimer?: NodeJS.Timeout;\n}\n\nfunction baseUrl(config: TvConfig): string {\n const host = config.ip.includes(\":\") ? `[${config.ip}]` : config.ip;\n return new URL(`http://${host}:${config.port ?? 80}`).origin;\n}\n\nfunction failureDescription(error: unknown): string {\n if (error instanceof BraviaError) {\n return `TV API code ${error.id}`;\n }\n if (typeof error === \"object\" && error !== null) {\n if (\"name\" in error && error.name === \"TimeoutError\") {\n return \"request timed out\";\n }\n if (\"code\" in error && typeof error.code === \"string\" && /^[A-Z_0-9]+$/.test(error.code)) {\n return error.code;\n }\n if (\n \"response\" in error &&\n typeof error.response === \"object\" &&\n error.response !== null &&\n \"status\" in error.response &&\n typeof error.response.status === \"number\"\n ) {\n return `HTTP status ${error.response.status}`;\n }\n }\n // Error objects may contain HTTP headers and credentials; never pass them to the logger.\n return \"connection or initialization error\";\n}\n\nfunction isDeviceState(value: unknown, uuid: string): value is DeviceState {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const state = value as Partial<DeviceState>;\n return (\n state.version === 1 &&\n state.plugin === PLUGIN_NAME &&\n state.uuid === uuid &&\n typeof state.clientId === \"string\" &&\n state.clientId.length > 0 &&\n (state.cookie === undefined || typeof state.cookie === \"string\")\n );\n}\n\nexport class BraviaPlatform implements DynamicPlatformPlugin {\n private readonly configured: ConfiguredDevice[];\n private readonly cached = new Map<string, PlatformAccessory>();\n private readonly devices: Device[] = [];\n private readonly stateDirectory: string;\n private readonly cleanupAllowed: boolean;\n private readonly blockedIdentities = new Set<string>();\n private stopped = false;\n private launched = false;\n private readonly log: Logging;\n private readonly api: RuntimeAPI;\n\n constructor(log: Logging, config: BraviaPlatformConfig | undefined, api: RuntimeAPI) {\n this.log = log;\n this.api = api;\n const tvs = parseConfig(config, log);\n const candidates: ConfiguredDevice[] = [];\n for (const tv of tvs) {\n try {\n const origin = baseUrl(tv);\n const identity = tv.mac\n ? `mac:${tv.mac.replace(/[:-]/g, \"\").toLowerCase()}`\n : `ip:${new URL(origin).hostname.toLowerCase()}`;\n candidates.push({\n config: tv,\n uuid: api.hap.uuid.generate(`${PLUGIN_NAME}:${identity}`),\n baseUrl: origin,\n });\n } catch {\n log.error(\"[%s] Could not construct the TV address; this TV is skipped.\", tv.name);\n }\n }\n const counts = new Map<string, number>();\n for (const device of candidates) {\n counts.set(device.uuid, (counts.get(device.uuid) ?? 0) + 1);\n }\n this.configured = candidates.filter((device) => {\n if (counts.get(device.uuid)! > 1) {\n log.error(\"[%s] Duplicate TV identity; this TV is skipped.\", device.config.name);\n return false;\n }\n return true;\n });\n // An invalid entry is not an intentional removal. Preserve all old state until config is valid.\n this.cleanupAllowed =\n config !== undefined &&\n config.compatibilitymode !== true &&\n Array.isArray(config.tvs) &&\n this.configured.length === config.tvs.length;\n this.stateDirectory = join(api.user.storagePath(), \"plugin-persist\", STATE_DIRECTORY);\n api.on(\"didFinishLaunching\", () => {\n void this.launch().catch((error: unknown) => {\n if (!this.stopped) {\n this.log.error(\"Could not initialize BraviaPlatform (%s).\", failureDescription(error));\n }\n });\n });\n api.on(\"shutdown\", () => this.shutdown());\n }\n\n configureAccessory(accessory: PlatformAccessory): void {\n this.cached.set(accessory.UUID, accessory);\n }\n\n private async launch(): Promise<void> {\n if (this.stopped || this.launched) {\n return;\n }\n this.launched = true;\n try {\n mkdirSync(this.stateDirectory, { recursive: true, mode: 0o700 });\n chmodSync(this.stateDirectory, 0o700);\n } catch {\n this.log.error(\n \"Could not create private BRAVIA storage; check Homebridge storage permissions.\",\n );\n }\n this.removeObsoleteAccessories();\n this.removeObsoleteState();\n // Each task catches its own failure, so one offline or unpaired TV cannot block another.\n await Promise.all(this.configured.map((configured) => this.startDevice(configured)));\n }\n\n private async startDevice(configured: ConfiguredDevice): Promise<void> {\n if (this.stopped || this.blockedIdentities.has(configured.uuid)) {\n return;\n }\n try {\n const state = this.loadState(configured.uuid);\n const cachedAccessory = this.cached.get(configured.uuid);\n let accessory = cachedAccessory;\n if (!accessory && state.accessory) {\n try {\n if (\n state.accessory.UUID !== configured.uuid ||\n state.accessory.plugin !== PLUGIN_NAME ||\n state.accessory.platform !== PLATFORM_NAME\n ) {\n throw new Error(\"Stored accessory identity does not match.\");\n }\n accessory = this.api.platformAccessory.deserialize(state.accessory);\n } catch {\n this.log.warn(\n \"[%s] Could not restore stored TV services; creating a new accessory.\",\n configured.config.name,\n );\n }\n }\n accessory ??= new this.api.platformAccessory(\n configured.config.name,\n configured.uuid,\n this.api.hap.Categories.TELEVISION,\n );\n accessory.displayName = configured.config.name;\n accessory.category = this.api.hap.Categories.TELEVISION;\n const authentication = new Authentication({\n config: configured.config,\n baseUrl: configured.baseUrl,\n cookie: state.cookie,\n clientId: state.clientId,\n log: this.log,\n });\n const device: Device = {\n ...configured,\n state,\n accessory,\n authentication,\n published: configured.config.externalaccessory === false && cachedAccessory !== undefined,\n };\n this.devices.push(device);\n this.markUnavailable(device);\n // Publish restored services before any network request, including while the TV is offline.\n this.publishDevice(device);\n this.saveDevice(device);\n await this.connectDevice(device);\n } catch (error) {\n if (!this.stopped) {\n this.log.error(\n \"[%s] Could not initialize TV (%s).\",\n configured.config.name,\n failureDescription(error),\n );\n }\n }\n }\n\n private async connectDevice(device: Device): Promise<void> {\n if (this.stopped) {\n return;\n }\n try {\n device.client = await device.authentication.authenticate();\n if (this.stopped) {\n return;\n }\n device.state.cookie = device.client.cookie;\n this.saveDevice(device);\n device.television = new Television(\n this.api,\n this.log,\n device.config,\n device.accessory,\n device.client,\n () => {\n if (!this.stopped) {\n this.saveDevice(device);\n }\n },\n );\n await device.television.start();\n if (this.stopped) {\n device.television.stop();\n return;\n }\n this.publishDevice(device);\n this.saveDevice(device);\n } catch (error) {\n if (this.stopped) {\n return;\n }\n this.log.error(\n \"[%s] Could not start TV (%s); initialization will be retried.\",\n device.config.name,\n failureDescription(error),\n );\n try {\n device.television?.stop();\n device.television = undefined;\n this.markUnavailable(device);\n this.publishDevice(device);\n this.saveDevice(device);\n } catch (publishError) {\n this.log.error(\n \"[%s] Could not restore unavailable TV (%s).\",\n device.config.name,\n failureDescription(publishError),\n );\n }\n this.scheduleRetry(device);\n }\n }\n\n private markUnavailable(device: Device): void {\n const service = device.accessory.getService(this.api.hap.Service.Television);\n if (!service) {\n return;\n }\n const unavailable = () => {\n throw new this.api.hap.HapStatusError(this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE);\n };\n service\n .getCharacteristic(this.api.hap.Characteristic.Active)\n .onGet(unavailable)\n .onSet(unavailable);\n }\n\n private scheduleRetry(device: Device): void {\n if (this.stopped || device.retryTimer) {\n return;\n }\n const delay = Math.max(1, Math.min(device.config.updaterate ?? 5000, 2_147_483_647));\n device.retryTimer = setTimeout(() => {\n device.retryTimer = undefined;\n if (!this.stopped) {\n void this.connectDevice(device).catch(() => {\n if (!this.stopped) {\n this.log.error(\"[%s] Could not retry TV initialization.\", device.config.name);\n this.scheduleRetry(device);\n }\n });\n }\n }, delay);\n }\n\n private publishDevice(device: Device): void {\n if (\n this.stopped ||\n device.published ||\n !device.accessory.getService(this.api.hap.Service.Television)\n ) {\n return;\n }\n if (device.config.externalaccessory === false) {\n this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [device.accessory]);\n } else {\n this.api.publishExternalAccessories(PLUGIN_NAME, [device.accessory]);\n }\n device.published = true;\n }\n\n private loadState(uuid: string): DeviceState {\n const path = join(this.stateDirectory, `${uuid}.json`);\n try {\n if (!lstatSync(path).isFile()) {\n throw new Error(\"Private state must be a regular file.\");\n }\n chmodSync(path, 0o600);\n const state: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n if (!isDeviceState(state, uuid)) {\n throw new Error(\"Invalid private device state.\");\n }\n return state;\n } catch (error) {\n if (\n !(typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\")\n ) {\n this.log.warn(\n \"Could not read private TV state for %s; creating a fresh controller session.\",\n uuid,\n );\n }\n }\n return { version: 1, plugin: PLUGIN_NAME, uuid, clientId: `Homebridge:${randomUUID()}` };\n }\n\n private saveDevice(device: Device): void {\n let temporaryPath: string | undefined;\n try {\n if (device.client) {\n device.state.cookie = device.client.cookie;\n }\n if (device.accessory.getService(this.api.hap.Service.Television)) {\n // Homebridge's serializer requires both identifiers, including for external accessories.\n device.accessory._associatedPlugin = PLUGIN_NAME;\n device.accessory._associatedPlatform = PLATFORM_NAME;\n const serialized = this.api.platformAccessory.serialize(device.accessory);\n if (device.config.externalaccessory !== false) {\n device.state.accessory = serialized;\n } else {\n delete device.state.accessory;\n if (!this.stopped && device.published) {\n const accessoryJson = JSON.stringify(serialized);\n if (accessoryJson !== device.bridgedAccessoryJson) {\n this.api.updatePlatformAccessories([device.accessory]);\n device.bridgedAccessoryJson = accessoryJson;\n }\n }\n }\n } else {\n delete device.state.accessory;\n }\n const stateJson = JSON.stringify(device.state);\n if (stateJson === device.persistedJson) {\n return;\n }\n const path = join(this.stateDirectory, `${device.uuid}.json`);\n temporaryPath = `${path}.${randomUUID()}.tmp`;\n writeFileSync(temporaryPath, stateJson, { flag: \"wx\", mode: 0o600 });\n renameSync(temporaryPath, path);\n temporaryPath = undefined;\n device.persistedJson = stateJson;\n } catch {\n this.log.error(\n \"[%s] Could not save private TV state; check Homebridge storage permissions.\",\n device.config.name,\n );\n } finally {\n if (temporaryPath) {\n try {\n unlinkSync(temporaryPath);\n } catch {\n // A failed write may not have created its temporary file.\n }\n }\n }\n }\n\n private removeObsoleteAccessories(): void {\n const configured = new Map(this.configured.map((device) => [device.uuid, device.config]));\n for (const [uuid, accessory] of this.cached) {\n const config = configured.get(uuid);\n if (config?.externalaccessory === false || (!config && !this.cleanupAllowed)) {\n continue;\n }\n try {\n this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);\n if (!config) {\n this.cached.delete(uuid);\n }\n } catch (error) {\n this.log.error(\"Could not remove an obsolete bridged TV (%s).\", failureDescription(error));\n if (config) {\n this.blockedIdentities.add(uuid);\n }\n }\n }\n }\n\n private removeObsoleteState(): void {\n if (!this.cleanupAllowed) {\n return;\n }\n const active = new Set(this.configured.map((device) => `${device.uuid}.json`));\n try {\n for (const entry of readdirSync(this.stateDirectory, { withFileTypes: true })) {\n if (!entry.isFile() || !STATE_FILE.test(entry.name) || active.has(entry.name)) {\n continue;\n }\n try {\n const path = join(this.stateDirectory, entry.name);\n const uuid = entry.name.slice(0, -5);\n const value: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n if (isDeviceState(value, uuid)) {\n unlinkSync(path);\n }\n } catch {\n this.log.warn(\"Could not inspect or remove an obsolete private TV state file.\");\n }\n }\n } catch (error) {\n if (\n !(typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\")\n ) {\n this.log.warn(\"Could not inspect private TV state for obsolete devices.\");\n }\n }\n }\n\n private shutdown(): void {\n if (this.stopped) {\n return;\n }\n this.stopped = true;\n for (const device of this.devices) {\n if (device.retryTimer) {\n clearTimeout(device.retryTimer);\n device.retryTimer = undefined;\n }\n try {\n device.authentication.stop();\n } catch {\n this.log.warn(\"[%s] Could not close the PIN server cleanly.\", device.config.name);\n }\n try {\n device.television?.stop();\n } catch {\n this.log.warn(\"[%s] Could not stop TV activity cleanly.\", device.config.name);\n }\n this.saveDevice(device);\n }\n }\n}\n","import type { API } from \"homebridge\";\nimport { BraviaPlatform, PLATFORM_NAME, PLUGIN_NAME } from \"./platform.ts\";\n\nexport default function initialize(api: API): void {\n api.registerPlatform(PLUGIN_NAME, PLATFORM_NAME, BraviaPlatform);\n}\n"],"mappings":";;;;;;;;;;AAQA,MAAM,iBAAiB;AAEvB,SAAS,uBAAuB,OAAyB;CACvD,IAAI,iBAAiB,aACnB,OAAO,MAAM,OAAO,OAAO,MAAM,OAAO;CAE1C,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,EAAE,cAAc,QACjE,OAAO;CAET,MAAM,WAAW,MAAM;CACvB,OACE,OAAO,aAAa,YACpB,aAAa,QACb,YAAY,aACX,SAAS,WAAW,OAAO,SAAS,WAAW;AAEpD;AAEA,SAAS,QAAQ,UAA0B,QAAgB,MAAc,OAAO,OAAa;CAC3F,IAAI,SAAS,aAAa,SAAS,eACjC;CAEF,SAAS,UAAU,QAAQ;EACzB,gBAAgB,OAAO,6BAA6B;EACpD,kBAAkB,OAAO,WAAW,IAAI;EACxC,iBAAiB;EACjB,2BACE;EACF,0BAA0B;EAC1B,mBAAmB;EACnB,YAAY;CACd,CAAC;CACD,SAAS,IAAI,IAAI;AACnB;AAEA,IAAM,YAAN,cAAwB,MAAM;CACnB;CAET,YAAY,QAAgB,SAAiB;EAC3C,MAAM,OAAO;EACb,KAAK,SAAS;CAChB;AACF;AAEA,SAAS,SAAS,SAAoD;CACpE,MAAM,EAA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  {
2
2
  "name": "@hyjk2000/homebridge-bravia",
3
3
  "displayName": "Sony BRAVIA",
4
- "version": "0.0.3",
4
+ "version": "0.0.5",
5
5
  "description": "Homebridge television platform for Sony BRAVIA TVs",
6
6
  "keywords": [
7
7
  "bravia",
@@ -32,7 +32,7 @@
32
32
  "access": "public"
33
33
  },
34
34
  "dependencies": {
35
- "@hyjk2000/bravia-sdk": "0.0.2"
35
+ "@hyjk2000/bravia-sdk": "0.1.0"
36
36
  },
37
37
  "devDependencies": {
38
38
  "homebridge": "^1.8.0"