├── .gitignore ├── zp.png ├── homebridge-zp.png ├── jsdoc.json ├── cli └── zp.js ├── index.js ├── lib ├── ZpService │ ├── index.js │ ├── Alarm.js │ ├── Led.js │ ├── Speaker.js │ ├── Tv.js │ └── Sonos.js ├── ZpAccessory │ ├── Tv.js │ ├── Slave.js │ ├── Master.js │ └── index.js ├── ZpHousehold.js └── ZpPlatform.js ├── .github └── FUNDING.yml ├── ISSUE_TEMPLATE.md ├── package.json ├── config.schema.json ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | out 3 | npm-debug.log 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /zp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ebaauw/homebridge-zp/HEAD/zp.png -------------------------------------------------------------------------------- /homebridge-zp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ebaauw/homebridge-zp/HEAD/homebridge-zp.png -------------------------------------------------------------------------------- /jsdoc.json: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "plugins/markdown" 4 | ], 5 | "rescurseDepth": 10, 6 | "source": { 7 | "include": [ 8 | "README.md", 9 | "index.js", 10 | "lib", 11 | "node_modules/hb-lib-tools/lib/HttpClient.js" 12 | ] 13 | }, 14 | "templates": { 15 | "monospaceLinks": true 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /cli/zp.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // homebridge-zp/cli/zp.js 4 | // Copyright © 2019-2025 Erik Baauw. All rights reserved. 5 | // 6 | // Homebridge plugin for Sonos ZonePlayer. 7 | 8 | import { createRequire } from 'node:module' 9 | 10 | import { ZpTool } from 'hb-zp-tools/ZpTool' 11 | 12 | const require = createRequire(import.meta.url) 13 | const packageJson = require('../package.json') 14 | 15 | new ZpTool(packageJson).main() 16 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/index.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { createRequire } from 'node:module' 7 | 8 | import { ZpPlatform } from './lib/ZpPlatform.js' 9 | 10 | const require = createRequire(import.meta.url) 11 | const packageJson = require('./package.json') 12 | 13 | function main (homebridge) { 14 | ZpPlatform.loadPlatform(homebridge, packageJson, 'ZP', ZpPlatform) 15 | } 16 | 17 | export { main as default } 18 | -------------------------------------------------------------------------------- /lib/ZpService/index.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpService/index.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { ServiceDelegate } from 'homebridge-lib/ServiceDelegate' 7 | 8 | class ZpService extends ServiceDelegate { 9 | constructor (zpAccessory, params) { 10 | super(zpAccessory, params) 11 | this.zpAccessory = zpAccessory 12 | this.zpClient = this.zpAccessory.zpClient 13 | this.zpHousehold = this.zpAccessory.zpHousehold 14 | } 15 | } 16 | 17 | export { ZpService } 18 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [ebaauw] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: ["https://www.paypal.me/ebaauw/EUR"] 13 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 9 | #### Issue 10 | 11 | 12 | #### Log Messages 13 | 14 | ``` 15 | ``` 16 | 17 | #### Debug Files 18 | 19 | -------------------------------------------------------------------------------- /lib/ZpAccessory/Tv.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpAccessory/Tv.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { ZpAccessory } from './index.js' 7 | import { ZpService } from '../ZpService/index.js' 8 | 9 | class Tv extends ZpAccessory { 10 | constructor (platform, params) { 11 | params.id = platform.config.tvIdPrefix + params.id.slice(6) 12 | params.category = platform.Accessory.Categories.SPEAKER 13 | params.externalAccessory = true 14 | super(platform, params) 15 | this.inheritLogLevel(params.master) 16 | // params.master.context.tv = this._context 17 | this.debug('TV accessory') 18 | this.tvService = new ZpService.Tv(this, params) 19 | this.zpClient.on('lastSeenUpdated', () => { 20 | this.tvService.values.statusFault = 21 | this.Characteristics.hap.StatusFault.NO_FAULT 22 | }) 23 | setImmediate(() => { 24 | this.emit('initialised') 25 | }) 26 | } 27 | 28 | topologyUpdated () { 29 | this.tvService.updateGroupInputSource() 30 | } 31 | } 32 | 33 | ZpAccessory.Tv = Tv 34 | -------------------------------------------------------------------------------- /lib/ZpAccessory/Slave.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpAccessory/Slave.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { ZpAccessory } from './index.js' 7 | import { ZpService } from '../ZpService/index.js' 8 | 9 | class Slave extends ZpAccessory { 10 | constructor (platform, params) { 11 | params.category = platform.Accessory.Categories.SPEAKER 12 | super(platform, params) 13 | this.inheritLogLevel(params.master) 14 | this.debug('LED accessory') 15 | this.context.master = params.master.id 16 | this.ledService = new ZpService.Led(this, this.zpClient) 17 | this.attachZpClient() 18 | setImmediate(() => { 19 | this.emit('initialised') 20 | }) 21 | } 22 | 23 | updateLastSeen () { 24 | this.ledService.values.lastSeen = this.zpClient.lastSeen 25 | this.ledService.values.statusFault = 26 | this.Characteristics.hap.StatusFault.NO_FAULT 27 | } 28 | 29 | topologyUpdated () { 30 | if (this.zpClient.battery != null) { 31 | this.checkBattery(this.zpClient.battery) 32 | } 33 | } 34 | } 35 | 36 | ZpAccessory.Slave = Slave 37 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "homebridge-zp", 3 | "description": "Homebridge plugin for Sonos Zone Players", 4 | "displayName": "Homebridge ZP", 5 | "author": "Erik Baauw", 6 | "maintainers": [ 7 | "ebaauw" 8 | ], 9 | "license": "Apache-2.0", 10 | "version": "1.4.60", 11 | "keywords": [ 12 | "homebridge-plugin", 13 | "homekit", 14 | "sonos", 15 | "zoneplayer", 16 | "sonos-zp", 17 | "sonos-zoneplayer" 18 | ], 19 | "type": "module", 20 | "main": "index.js", 21 | "bin": { 22 | "zp": "cli/zp.js" 23 | }, 24 | "engines": { 25 | "homebridge": "^1.11.1||^2.0.0-beta", 26 | "node": "^24||^22||^20" 27 | }, 28 | "dependencies": { 29 | "hb-zp-tools": "~1.0.15", 30 | "he": "^1.2.0", 31 | "homebridge-lib": "~7.1.13" 32 | }, 33 | "scripts": { 34 | "prepare": "standard", 35 | "test": "standard && echo \"Error: no test specified\" && exit 1" 36 | }, 37 | "repository": { 38 | "type": "git", 39 | "url": "git+https://github.com/ebaauw/homebridge-zp.git" 40 | }, 41 | "bugs": { 42 | "url": "https://github.com/ebaauw/homebridge-zp/issues" 43 | }, 44 | "homepage": "https://github.com/ebaauw/homebridge-zp#readme", 45 | "funding": [ 46 | { 47 | "type": "github", 48 | "url": "https://github.com/sponsors/ebaauw" 49 | }, 50 | { 51 | "type": "paypal", 52 | "url": "https://www.paypal.me/ebaauw/EUR" 53 | } 54 | ] 55 | } 56 | -------------------------------------------------------------------------------- /lib/ZpService/Alarm.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpService/Alarm.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { ZpService } from './index.js' 7 | 8 | class Alarm extends ZpService { 9 | constructor (zpAccessory, alarm) { 10 | const params = { 11 | id: alarm.id, 12 | name: zpAccessory.zpClient.zoneName + ' Sonos Alarm ' + alarm.id, 13 | Service: zpAccessory.Services.hap.Switch, 14 | subtype: 'alarm' + alarm.id 15 | } 16 | super(zpAccessory, params) 17 | this.debug('Alarm service') 18 | this.addCharacteristicDelegate({ 19 | key: 'on', 20 | Characteristic: this.Characteristics.hap.On, 21 | setter: async (value) => { 22 | const alarm = Object.assign({}, this._alarm) 23 | alarm.enabled = value ? 1 : 0 24 | return this.zpClient.updateAlarm(alarm) 25 | } 26 | }) 27 | this.addCharacteristicDelegate({ 28 | key: 'currentTrack', 29 | Characteristic: this.Characteristics.my.CurrentTrack 30 | }) 31 | this.addCharacteristicDelegate({ 32 | key: 'time', 33 | Characteristic: this.Characteristics.my.Time 34 | }) 35 | this.emit('initialised') 36 | this._alarm = alarm 37 | } 38 | 39 | get alarm () { return this._alarm } 40 | 41 | set alarm (alarm) { 42 | this._alarm = alarm 43 | this.values.on = alarm.enabled === 1 44 | this.values.currentTrack = alarm.programUri === 'x-rincon-buzzer:0' 45 | ? 'Sonos Chime' 46 | : alarm.programMetaData != null && alarm.programMetaData.title != null 47 | ? alarm.programMetaData.title.slice(0, 64) 48 | : 'unknown' 49 | this.values.time = alarm.startTime 50 | } 51 | } 52 | 53 | ZpService.Alarm = Alarm 54 | -------------------------------------------------------------------------------- /lib/ZpService/Led.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpService/Led.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { ZpService } from './index.js' 7 | 8 | class Led extends ZpService { 9 | constructor (zpAccessory, zpClient) { 10 | const params = { 11 | name: zpClient.zoneName + ' Sonos LED', 12 | Service: zpAccessory.Services.hap.Lightbulb, 13 | subtype: 'led' + (zpClient.channel == null ? '' : zpClient.channel) 14 | } 15 | if (zpClient.role !== 'master' && zpClient.channel != null) { 16 | params.name = zpClient.zoneName + ' Sonos ' + zpClient.channel + ' LED' 17 | } 18 | super(zpAccessory, params) 19 | this.debug('LED service') 20 | const paramsOn = { 21 | key: 'on', 22 | Characteristic: this.Characteristics.hap.On, 23 | setter: this.zpClient.setLedState.bind(this.zpClient) 24 | } 25 | const paramsLocked = { 26 | key: 'locked', 27 | Characteristic: this.Characteristics.hap.LockPhysicalControls, 28 | props: { adminOnlyAccess: [this.Characteristic.Access.WRITE] }, 29 | setter: this.zpClient.setButtonLockState.bind(this.zpClient) 30 | } 31 | if (!(this.platform.config.heartrate > 0)) { 32 | paramsOn.getter = this.zpClient.getLedState.bind(this.zpClient) 33 | paramsLocked.getter = async (value) => { 34 | return (await this.zpClient.getButtonLockState()) 35 | ? this.Characteristics.hap.LockPhysicalControls.CONTROL_LOCK_ENABLED 36 | : this.Characteristics.hap.LockPhysicalControls.CONTROL_LOCK_DISABLED 37 | } 38 | } 39 | this.addCharacteristicDelegate(paramsOn) 40 | this.addCharacteristicDelegate(paramsLocked) 41 | if (zpClient.role !== 'master') { 42 | this.addCharacteristicDelegate({ 43 | key: 'lastSeen', 44 | Characteristic: this.Characteristics.my.LastSeen, 45 | value: 'n/a', 46 | silent: true 47 | }) 48 | this.addCharacteristicDelegate({ 49 | key: 'statusFault', 50 | Charactertistic: this.Characteristics.hap.StatusFault, 51 | value: this.Characteristics.hap.StatusFault.GENERAL_FAULT 52 | }) 53 | this.values.statusFault = 54 | this.Characteristics.hap.StatusFault.GENERAL_FAULT 55 | } 56 | 57 | if (this.platform.config.heartrate > 0) { 58 | this.zpAccessory.on('heartbeat', async (beat) => { 59 | try { 60 | if (beat % this.platform.config.heartrate === 0) { 61 | if (!this.zpAccessory.blinking) { 62 | this.values.on = await this.zpClient.getLedState() 63 | } 64 | this.values.locked = (await this.zpClient.getButtonLockState()) 65 | ? this.Characteristics.hap.LockPhysicalControls.CONTROL_LOCK_ENABLED 66 | : this.Characteristics.hap.LockPhysicalControls.CONTROL_LOCK_DISABLED 67 | } 68 | } catch (error) { 69 | this.error(error) 70 | } 71 | }) 72 | } 73 | this.emit('initialised') 74 | } 75 | } 76 | 77 | ZpService.Led = Led 78 | -------------------------------------------------------------------------------- /lib/ZpAccessory/Master.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpAccessory/Master.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { ZpAccessory } from './index.js' 7 | import { ZpService } from '../ZpService/index.js' 8 | 9 | class Master extends ZpAccessory { 10 | constructor (platform, params) { 11 | params.category = platform.Accessory.Categories.SPEAKER 12 | super(platform, params) 13 | this.debug('Sonos accessory') 14 | this.alarmServices = {} 15 | this.sonosService = new ZpService.Sonos(this) 16 | this.manageLogLevel(this.sonosService.characteristicDelegate('logLevel')) 17 | if (this.platform.config.speakers) { 18 | this.speakerService = new ZpService.Speaker(this) 19 | } 20 | if (this.platform.config.leds) { 21 | this.ledService = new ZpService.Led(this, this.zpClient) 22 | } 23 | this.attachZpClient() 24 | this.topologyUpdated() 25 | if (this.platform.config.alarms) { 26 | this.notYetInitialised = true 27 | this.zpHousehold.on('alarmListUpdated', this.alarmListUpdated.bind(this)) 28 | this.alarmListUpdated() 29 | return // 'initialised' will be emitted by alarmListUpdated() 30 | } 31 | setImmediate(() => { 32 | this.emit('initialised') 33 | }) 34 | } 35 | 36 | updateLastSeen () { 37 | this.sonosService.values.lastSeen = this.zpClient.lastSeen 38 | this.sonosService.values.statusFault = 39 | this.Characteristics.hap.StatusFault.NO_FAULT 40 | } 41 | 42 | topologyUpdated () { 43 | this.sonosService.values.sonosGroup = this.zpClient.zoneGroupShortName 44 | this.isCoordinator = this.zpClient.zoneGroup === this.zpClient.id 45 | if (this.isCoordinator) { 46 | this.coordinator = this 47 | if (this.speakerService != null) { 48 | this.speakerService.values.on = false 49 | } 50 | this.leaving = false 51 | } else { 52 | if (this.speakerService != null) { 53 | this.speakerService.values.on = true 54 | } 55 | this.coordinator = this.platform.groupCoordinator(this.zpClient.zoneGroup) 56 | this.copyCoordinator() 57 | } 58 | if (this.zpClient.battery != null) { 59 | this.checkBattery(this.zpClient.battery) 60 | } 61 | } 62 | 63 | alarmListUpdated () { 64 | const alarms = this.zpHousehold.alarmList 65 | if (alarms == null) { 66 | return 67 | } 68 | const keys = {} 69 | for (const alarm of alarms) { 70 | if (alarm.roomUuid === this.zpClient.id) { 71 | keys[alarm.id] = true 72 | const service = this.alarmServices[alarm.id] 73 | if (service == null) { 74 | this.alarmServices[alarm.id] = new ZpService.Alarm(this, alarm) 75 | } else { 76 | service.alarm = alarm 77 | } 78 | } 79 | } 80 | for (const key in this.alarmServices) { 81 | if (!keys[key]) { 82 | this.log('remove Alarm %s', key) 83 | this.alarmServices[key].destroy() 84 | delete this.alarmServices[key] 85 | } 86 | } 87 | if (this.notYetInitialised) { 88 | delete this.notYetInitialised 89 | this.emit('initialised') 90 | } 91 | } 92 | 93 | // Copy group characteristic values from group coordinator. 94 | copyCoordinator () { 95 | const coordinator = this.coordinator 96 | if (coordinator && coordinator !== this && !this.leaving) { 97 | this.debug( 98 | 'copy coordinator %s [%s]', this.coordinator.zpClient.id, 99 | this.coordinator.zpClient.zoneGroupName 100 | ) 101 | const src = coordinator.sonosService.values 102 | const dst = this.sonosService.values 103 | dst.sonosGroup = src.sonosGroup 104 | dst.on = src.on 105 | dst.volume = src.volume 106 | dst.mute = src.mute 107 | dst.currentTrack = src.currentTrack 108 | dst.currentTransportActions = src.currentTransportActions 109 | dst.uri = src.uri 110 | } 111 | } 112 | 113 | // Return array of members. 114 | members () { 115 | if (!this.isCoordinator) { 116 | return [] 117 | } 118 | return this.platform.groupMembers(this.zpClient.id) 119 | } 120 | } 121 | 122 | ZpAccessory.Master = Master 123 | -------------------------------------------------------------------------------- /config.schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "pluginAlias": "ZP", 3 | "pluginType": "platform", 4 | "singular": true, 5 | "headerDisplay": "Homebridge plugin for Sonos ZonePlayer", 6 | "footerDisplay": "", 7 | "schema": { 8 | "type": "object", 9 | "properties": { 10 | "name": { 11 | "description": "Plugin name as displayed in the Homebridge log.", 12 | "type": "string", 13 | "required": true, 14 | "default": "Sonos" 15 | }, 16 | "alarms": { 17 | "description": "Create an additional Switch service for each alarm.", 18 | "type": "boolean" 19 | }, 20 | "brightness": { 21 | "description": "Expose volume as Brightness.", 22 | "type": "boolean" 23 | }, 24 | "excludeAirPlay": { 25 | "title": "Exclude AirPlay 2", 26 | "description": "Exclude AirPlay 2 zone players that are already exposed to Apple's Home app.", 27 | "type": "boolean" 28 | }, 29 | "heartrate": { 30 | "description": "Interval (in seconds) to poll zone player. Default: disabled.", 31 | "type": "integer" 32 | }, 33 | "leds": { 34 | "title": "LEDs", 35 | "description": "Create an additional Lightbulb service for the LED. Also create an accessory for each slave zone player.", 36 | "type": "boolean" 37 | }, 38 | "maxFavourites": { 39 | "description": "Maximum number of favourites supported, between 16 and 96. Default: 96.", 40 | "type": "integer" 41 | }, 42 | "mdns": { 43 | "description": "Enable mDNS discovery of Sonos ZonePlayers. Default: true.", 44 | "type": "boolean", 45 | "default": true 46 | }, 47 | "port": { 48 | "description": "Port to use for webserver receiving zone player notifications. Default: random.", 49 | "type": "integer", 50 | "maximum": 65535 51 | }, 52 | "resetTimeout": { 53 | "description": "Timeout (in milliseconds) to reset input. Default: 500.", 54 | "type": "integer" 55 | }, 56 | "service": { 57 | "description": "HomeKit service type for Sonos and Switch services.", 58 | "type": "string", 59 | "required": true, 60 | "default": "switch", 61 | "oneOf": [ 62 | { 63 | "title": "Switch", 64 | "enum": [ 65 | "switch" 66 | ] 67 | }, 68 | { 69 | "title": "Lightbulb", 70 | "enum": [ 71 | "light" 72 | ] 73 | }, 74 | { 75 | "title": "Speaker", 76 | "enum": [ 77 | "speaker" 78 | ] 79 | }, 80 | { 81 | "title": "Fan", 82 | "enum": [ 83 | "fan" 84 | ] 85 | } 86 | ] 87 | }, 88 | "speakers": { 89 | "description": "Create an additional Speaker service for each zone.", 90 | "type": "boolean" 91 | }, 92 | "subscriptionTimeout": { 93 | "description": "Duration (in minutes) of subscriptions to ZonePlayer notifications. Default: 30.", 94 | "type": "integer" 95 | }, 96 | "timeout": { 97 | "description": "Timeout (in seconds) to wait for a response from a Sonos ZonePlayer. Default: 15.", 98 | "type": "integer" 99 | }, 100 | "tv": { 101 | "title": "TV", 102 | "description": "Create an additional, non-bridged TV accessory for each zone.", 103 | "type": "boolean" 104 | }, 105 | "tvIdPrefix": { 106 | "title": "TV ID Prefix", 107 | "description": "Prefix for serial number of TV accessories. Default: 'TV'", 108 | "type": "string" 109 | } 110 | } 111 | }, 112 | "form": [ 113 | "name", 114 | { 115 | "type": "fieldset", 116 | "expandable": true, 117 | "title": "What", 118 | "description": "Select what to expose to HomeKit for each zone.", 119 | "items": [ 120 | "speakers", 121 | "alarms", 122 | "leds", 123 | { 124 | "key": "heartrate", 125 | "condition": { 126 | "functionBody": "return model.leds" 127 | } 128 | }, 129 | "excludeAirPlay" 130 | ] 131 | }, 132 | { 133 | "type": "fieldset", 134 | "expandable": true, 135 | "title": "How", 136 | "description": "Select how to expose a zone to HomeKit.", 137 | "items": [ 138 | "service", 139 | { 140 | "key": "brightness", 141 | "condition": { 142 | "functionBody": "return model.service === 'switch' || model.service === 'speaker'" 143 | } 144 | }, 145 | "tv", 146 | { 147 | "key": "maxFavourites", 148 | "condition": { 149 | "functionBody": "return model.tv" 150 | } 151 | } 152 | ] 153 | }, 154 | { 155 | "type": "fieldset", 156 | "expandable": true, 157 | "title": "Advanced Settings", 158 | "description": "Don't change these, unless you understand what you're doing.", 159 | "items": [ 160 | "resetTimeout", 161 | "subscriptionTimeout", 162 | "timeout", 163 | "mdns", 164 | "port", 165 | "tvIdPrefix" 166 | ] 167 | } 168 | ] 169 | } 170 | -------------------------------------------------------------------------------- /lib/ZpHousehold.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpHousehold.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { once } from 'node:events' 7 | 8 | import { Delegate } from 'homebridge-lib/Delegate' 9 | 10 | const ZONEPLAYERS_PER_HOUSEHOLD = 32 11 | 12 | class ZpHousehold extends Delegate { 13 | constructor (platform, zpClient) { 14 | super(platform, zpClient.household) 15 | this.household = zpClient.household 16 | this.setMaxListeners(ZONEPLAYERS_PER_HOUSEHOLD) 17 | } 18 | 19 | error (format, ...args) { 20 | if (typeof format !== 'object' || format.request == null) { 21 | super.error(format, ...args) 22 | } 23 | } 24 | 25 | async setAssociated (zpClient) { 26 | if (zpClient.household !== this.household) { 27 | throw new SyntaxError(`${zpClient.id} not in ${this.household}`) 28 | } 29 | if (this.zpClient != null && zpClient.id !== this.zpClient.id) { 30 | try { 31 | await this.zpClient.unsubscribe('/ZoneGroupTopology/Event') 32 | } catch (error) { this.error(error) } 33 | if (this.platform.config.alarms) { 34 | try { 35 | await this.zpClient.unsubscribe('/AlarmClock/Event') 36 | } catch (error) { this.error(error) } 37 | } 38 | if (this.platform.config.tv) { 39 | try { 40 | await this.zpClient.unsubscribe('/MediaServer/ContentDirectory/Event') 41 | } catch (error) { this.error(error) } 42 | } 43 | } 44 | this.zpClient.removeListener('message', this.onMessage.bind(this)) 45 | this.log( 46 | '%s [%s]: associated %s zoneplayer', 47 | this.zpClient.id, this.zpClient.name, this.zpClient.sonosOs 48 | ) 49 | this.zpClient = zpClient 50 | this.zpClient.on('message', this.onMessage.bind(this)) 51 | const timeout = this.platform.config.timeout 52 | await this.zpClient.subscribe('/ZoneGroupTopology/Event') 53 | const timer = setTimeout(() => { 54 | this.warn( 55 | '%s [%s]: no ZoneGroupTopology event received in %ds', 56 | this.zpClient.id, this.zpClient.name, timeout 57 | ) 58 | this.emit('error', new Error('timeout')) 59 | }, timeout * 1000) 60 | try { 61 | await once(this, 'topologyUpdated') 62 | } catch (error) {} 63 | clearTimeout(timer) 64 | if (this.platform.config.alarms) { 65 | await this.zpClient.subscribe('/AlarmClock/Event') 66 | const timer = setTimeout(() => { 67 | this.warn( 68 | '%s [%s]: no AlarmClock event received in %ds', 69 | this.zpClient.id, this.zpClient.name, timeout 70 | ) 71 | this.emit('error', new Error('timeout')) 72 | }, timeout * 1000) 73 | try { 74 | await once(this, 'alarmListUpdated') 75 | } catch (error) { 76 | this.alarmList = [] 77 | } 78 | clearTimeout(timer) 79 | } 80 | if (this.platform.config.tv) { 81 | await this.zpClient.subscribe('/MediaServer/ContentDirectory/Event') 82 | const timer = setTimeout(() => { 83 | this.warn( 84 | '%s [%s]: no ContentDirectory event received in %ds', 85 | this.zpClient.id, this.zpClient.name, timeout 86 | ) 87 | this.emit('error', new Error('timeout')) 88 | }, timeout * 1000) 89 | try { 90 | await once(this, 'favouritesUpdated') 91 | } catch (error) {} 92 | clearTimeout(timer) 93 | } 94 | } 95 | 96 | async onMessage (message) { 97 | try { 98 | const f = `handle${message.device}${message.service}Event` 99 | if (this[f] != null) { 100 | await this[f](message.parsedBody) 101 | } 102 | } catch (error) { 103 | this.error(error) 104 | } 105 | } 106 | 107 | async handleZonePlayerZoneGroupTopologyEvent (body) { 108 | try { 109 | if (body.zoneGroups != null) { 110 | for (const group of body.zoneGroups) { 111 | const coordinator = this.platform.zpClients[group.coordinator] 112 | if (coordinator == null) { 113 | continue 114 | } 115 | if (coordinator.id !== this.zpClient.id) { 116 | try { 117 | await coordinator.initTopology(this.zpClient) 118 | } catch (error) { this.error(error) } 119 | } 120 | for (const member of group.zoneGroupMembers) { 121 | const zone = this.platform.zpClients[member.uuid] 122 | if (zone == null) { 123 | continue 124 | } 125 | if (zone.id !== coordinator.id && zone.id !== this.zpClient.id) { 126 | try { 127 | await zone.initTopology(this.zpClient) 128 | } catch (error) { this.error(error) } 129 | } 130 | } 131 | } 132 | } 133 | if (body.vanishedDevices != null) { 134 | for (const device of body.vanishedDevices) { 135 | this.platform.lostZonePlayer(device.uuid) 136 | } 137 | } 138 | this.emit('topologyUpdated') 139 | } catch (error) { this.error(error) } 140 | } 141 | 142 | async handleZonePlayerAlarmClockEvent (body) { 143 | try { 144 | this.alarmList = (await this.zpClient.listAlarms()).currentAlarmList 145 | this.emit('alarmListUpdated') 146 | } catch (error) { this.error(error) } 147 | } 148 | 149 | async handleMediaServerContentDirectoryEvent (body) { 150 | try { 151 | if ( 152 | body.favoritesUpdateId == null || 153 | body.favoritesUpdateId === this.favoritesUpdateId 154 | ) { 155 | return 156 | } 157 | this.favoritesUpdateId = body.favoritesUpdateId 158 | this.favourites = await this.zpClient.browse('FV:2') 159 | this.emit('favouritesUpdated') 160 | } catch (error) { this.error(error) } 161 | } 162 | } 163 | 164 | export { ZpHousehold } 165 | -------------------------------------------------------------------------------- /lib/ZpAccessory/index.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpAccessory/index.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { once } from 'node:events' 7 | 8 | import { AccessoryDelegate } from 'homebridge-lib/AccessoryDelegate' 9 | import { ServiceDelegate } from 'homebridge-lib/ServiceDelegate' 10 | import 'homebridge-lib/ServiceDelegate/Battery' // TODO: dynamic import 11 | 12 | class ZpAccessory extends AccessoryDelegate { 13 | constructor (platform, params) { 14 | super(platform, params) 15 | this.context.name = params.name 16 | this.context.id = params.id 17 | this.context.address = params.address 18 | this.context.household = params.household 19 | this.heartbeatEnabled = true 20 | this.zpClient = params.zpClient 21 | this.zpHousehold = params.zpHousehold 22 | 23 | this.on('identify', this.identify) 24 | this.zpHousehold.on('topologyUpdated', this.topologyUpdated.bind(this)) 25 | } 26 | 27 | // Adopt ownership of the ZpClient instance, taking over all event handling. 28 | // This implies that any 'message` handling by ZpHousehold or ZpAccessory.TV 29 | // needs to be setup after the ZpAccessory.Master has been created. 30 | attachZpClient () { 31 | // if (this.zpClient == null) { 32 | // this.zpClient = new ZpClient({ 33 | // host: this.context.address, 34 | // id: this.context.id, 35 | // household: this.context.household, 36 | // listener: this.platform.listener, 37 | // timeout: this.platform.config.timeout 38 | // }) 39 | // } 40 | this.zpClient 41 | .removeAllListeners('request') 42 | .removeAllListeners('response') 43 | .removeAllListeners('error') 44 | // .removeAllListeners('message') 45 | .removeAllListeners('rebooted') 46 | .removeAllListeners('addressChanged') 47 | // .removeAllListeners() 48 | .on('request', (request) => { 49 | this.debug( 50 | 'request %s: %s %s%s', 51 | request.id, request.method, request.resource, 52 | request.action == null ? '' : ' ' + request.action 53 | ) 54 | if (request.parsedBody != null) { 55 | this.vdebug( 56 | 'request %s: %s %s %j', 57 | request.id, request.method, request.url, request.parsedBody 58 | ) 59 | this.vvdebug( 60 | 'request %s: %s %s (headers: %j) %s', 61 | request.id, request.method, request.url, 62 | request.headers, request.body 63 | ) 64 | } else { 65 | this.vdebug( 66 | 'request %s: %s %s', 67 | request.id, request.method, request.url 68 | ) 69 | this.vvdebug( 70 | 'request %s: %s %s (headers: %j)', 71 | request.id, request.method, request.url, request.headers 72 | ) 73 | } 74 | }) 75 | .on('response', (response) => { 76 | if (response.parsedBody != null) { 77 | this.vvdebug( 78 | 'request %s: response (headers: %j): %j', response.request.id, 79 | response.headers, response.body 80 | ) 81 | this.vdebug( 82 | 'request %s: response: %j', response.request.id, response.parsedBody 83 | ) 84 | } 85 | this.debug( 86 | 'request %s: http status %d %s', 87 | response.request.id, response.statusCode, response.statusMessage 88 | ) 89 | }) 90 | .on('error', (error) => { 91 | if (error.request == null) { 92 | this.error(error) 93 | return 94 | } 95 | if (error.request.id !== this.requestId) { 96 | if (error.request.body == null) { 97 | this.log( 98 | 'request %d: %s %s', error.request.id, 99 | error.request.method, error.request.resource 100 | ) 101 | } else { 102 | this.log( 103 | 'request %d: %s %s', error.request.id, 104 | error.request.method, error.request.resource, error.request.action 105 | ) 106 | } 107 | this.requestId = error.request.id 108 | } 109 | this.warn( 110 | 'request %d: %s', error.request.id, error 111 | ) 112 | }) 113 | .on('message', (message) => { 114 | const notify = message.device === 'ZonePlayer' 115 | ? message.service 116 | : message.device + '/' + message.service 117 | this.vvdebug('notify %s/Event: %s', notify, message.body) 118 | this.vdebug('notify %s/Event: %j', notify, message.parsedBody) 119 | this.debug('notify %s/Event', notify) 120 | try { 121 | const f = `handle${message.device}${message.service}Event` 122 | if (this[f] != null) { 123 | this[f](message.parsedBody) 124 | } 125 | } catch (error) { 126 | this.error(error) 127 | } 128 | }) 129 | .on('rebooted', (oldBootSeq) => { 130 | this.warn('rebooted (%d -> %d)', oldBootSeq, this.zpClient.bootSeq) 131 | }) 132 | .on('addressChanged', (oldAddress) => { 133 | this.warn( 134 | 'address changed from %s to %s', oldAddress, this.zpClient.address 135 | ) 136 | }) 137 | .on('lastSeenUpdated', () => { 138 | this.updateLastSeen() 139 | }) 140 | } 141 | 142 | checkBattery () { 143 | try { 144 | const battery = this.zpClient.battery 145 | if (battery.percentage == null || battery.charging == null) { 146 | return 147 | } 148 | this.debug('battery: %j', battery) 149 | if (this.batteryService == null) { 150 | this.batteryService = new ServiceDelegate.Battery(this, { 151 | batteryLevel: battery.percentage, 152 | chargingState: battery.charging 153 | ? this.Characteristics.hap.ChargingState.CHARGING 154 | : this.Characteristics.hap.ChargingState.NOT_CHARGING, 155 | lowBatteryThreshold: 20 156 | }) 157 | } 158 | this.batteryService.values.batteryLevel = battery.percentage 159 | this.batteryService.values.chargingState = battery.charging 160 | ? this.Characteristics.hap.ChargingState.CHARGING 161 | : this.Characteristics.hap.ChargingState.NOT_CHARGING 162 | } catch (error) { 163 | this.error(error) 164 | } 165 | } 166 | 167 | async identify () { 168 | try { 169 | if (this.blinking) { 170 | return 171 | } 172 | this.blinking = true 173 | const on = await this.zpClient.getLedState() 174 | for (let n = 0; n < 10; n++) { 175 | this.zpClient.setLedState(n % 2 === 0) 176 | await once(this, 'heartbeat') 177 | } 178 | await this.zpClient.setLedState(on) 179 | this.blinking = false 180 | } catch (error) { 181 | this.error(error) 182 | } 183 | } 184 | } 185 | 186 | export { ZpAccessory } 187 | -------------------------------------------------------------------------------- /lib/ZpService/Speaker.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpService/Speaker.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { ZpService } from './index.js' 7 | 8 | class Speaker extends ZpService { 9 | constructor (zpAccessory, params = {}) { 10 | params.name = zpAccessory.zpClient.zoneName + ' Speakers' 11 | params.Service = zpAccessory.platform.config.SpeakerService 12 | params.subtype = 'zone' 13 | super(zpAccessory, params) 14 | this.debug('Speaker service') 15 | this.zpClient.on('message', (message) => { 16 | try { 17 | const f = `handle${message.device}${message.service}Event` 18 | if (this[f] != null) { 19 | this[f](message.parsedBody) 20 | } 21 | } catch (error) { 22 | this.error(error) 23 | } 24 | }) 25 | this.addCharacteristicDelegate({ 26 | key: 'on', 27 | Characteristic: this.Characteristics.hap.On, 28 | setter: async (value) => { 29 | try { 30 | if (value === this.values.on) { 31 | return 32 | } 33 | const platformCoordinator = this.platform.coordinators[this.zpClient.household] 34 | if (platformCoordinator === this.zpAccessory) { 35 | setTimeout(() => { 36 | this.values.on = false 37 | }, this.platform.config.resetTimeout) 38 | return 39 | } 40 | if (value) { 41 | const coordinator = platformCoordinator 42 | if (coordinator != null) { 43 | return this.zpClient.setAvTransportGroup(coordinator.zpClient.id) 44 | } else { 45 | // No coordinator yet. 46 | setTimeout(() => { 47 | this.values.on = false 48 | }, this.platform.config.resetTimeout) 49 | } 50 | } else { 51 | return this.zpClient.becomeCoordinatorOfStandaloneGroup() 52 | } 53 | } catch (error) { 54 | this.error(error) 55 | } 56 | }, 57 | timeout: 5000 58 | }) 59 | this.addCharacteristicDelegate({ 60 | key: 'volume', 61 | Characteristic: this.platform.config.VolumeCharacteristic, 62 | unit: '%', 63 | setter: this.zpClient.setVolume.bind(this.zpClient) 64 | }) 65 | this.addCharacteristicDelegate({ 66 | key: 'changeVolume', 67 | Characteristic: this.Characteristics.my.ChangeVolume, 68 | value: 0, 69 | setter: async (value) => { 70 | try { 71 | await this.zpClient.setRelativeVolume(value) 72 | } catch (error) { 73 | this.error(error) 74 | } 75 | setTimeout(() => { 76 | this.values.changeVolume = 0 77 | }, this.platform.config.resetTimeout) 78 | } 79 | }) 80 | this.addCharacteristicDelegate({ 81 | key: 'mute', 82 | Characteristic: this.Characteristics.hap.Mute, 83 | setter: this.zpClient.setMute.bind(this.zpClient) 84 | }) 85 | this.addCharacteristicDelegate({ 86 | key: 'loudness', 87 | Characteristic: this.Characteristics.my.Loudness, 88 | setter: this.zpClient.setLoudness.bind(this.zpClient) 89 | }) 90 | this.addCharacteristicDelegate({ 91 | key: 'bass', 92 | Characteristic: this.Characteristics.my.Bass, 93 | setter: this.zpClient.setBass.bind(this.zpClient) 94 | }) 95 | this.addCharacteristicDelegate({ 96 | key: 'treble', 97 | Characteristic: this.Characteristics.my.Treble, 98 | setter: this.zpClient.setTreble.bind(this.zpClient) 99 | }) 100 | if (this.zpClient.balance) { 101 | this.addCharacteristicDelegate({ 102 | key: 'balance', 103 | Characteristic: this.Characteristics.my.Balance, 104 | unit: '%', 105 | setter: this.zpClient.setBalance.bind(this.zpClient) 106 | }) 107 | } 108 | if (this.zpClient.tvIn) { 109 | this.addCharacteristicDelegate({ 110 | key: 'nightSound', 111 | Characteristic: this.Characteristics.my.NightSound, 112 | setter: this.zpClient.setNightSound.bind(this.zpClient) 113 | }) 114 | this.addCharacteristicDelegate({ 115 | key: 'speechEnhancement', 116 | Characteristic: this.Characteristics.my.SpeechEnhancement, 117 | setter: this.zpClient.setSpeechEnhancement.bind(this.zpClient) 118 | }) 119 | } 120 | if (/\(.*LS\+RS.*\)/.test(this.zpClient.zoneDisplayName)) { 121 | this.addCharacteristicDelegate({ 122 | key: 'surroundEnabled', 123 | Characteristic: this.Characteristics.my.SurroundEnabled, 124 | setter: this.zpClient.setSurroundEnable.bind(this.zpClient) 125 | }) 126 | this.addCharacteristicDelegate({ 127 | key: 'tvLevel', 128 | Characteristic: this.Characteristics.my.TvLevel, 129 | setter: this.zpClient.setTvLevel.bind(this.zpClient) 130 | }) 131 | this.addCharacteristicDelegate({ 132 | key: 'musicLevel', 133 | Characteristic: this.Characteristics.my.MusicLevel, 134 | setter: this.zpClient.setMusicLevel.bind(this.zpClient) 135 | }) 136 | this.addCharacteristicDelegate({ 137 | key: 'musicPlaybackFull', 138 | Characteristic: this.Characteristics.my.MusicPlaybackFull, 139 | setter: this.zpClient.setMusicPlaybackFull.bind(this.zpClient) 140 | }) 141 | this.addCharacteristicDelegate({ 142 | key: 'heightLevel', 143 | Characteristic: this.Characteristics.my.HeightLevel, 144 | setter: this.zpClient.setHeightLevel.bind(this.zpClient) 145 | }) 146 | } 147 | if (/\(.*Sub.*\)/.test(this.zpClient.zoneDisplayName)) { 148 | this.addCharacteristicDelegate({ 149 | key: 'subEnabled', 150 | Characteristic: this.Characteristics.my.SubEnabled, 151 | setter: this.zpClient.setSubEnable.bind(this.zpClient) 152 | }) 153 | this.addCharacteristicDelegate({ 154 | key: 'subLevel', 155 | Characteristic: this.Characteristics.my.SubLevel, 156 | setter: this.zpClient.setSubLevel.bind(this.zpClient) 157 | }) 158 | } 159 | 160 | this.emit('initialised') 161 | 162 | zpAccessory.once('initialised', async () => { 163 | try { 164 | await this.zpClient.subscribe('/MediaRenderer/RenderingControl/Event') 165 | } catch (error) { 166 | this.error(error) 167 | } 168 | }) 169 | } 170 | 171 | handleMediaRendererRenderingControlEvent (message) { 172 | if ( 173 | message.lastChange == null || 174 | !Array.isArray(message.lastChange) || 175 | message.lastChange[0] == null 176 | ) { 177 | return 178 | } 179 | const event = message.lastChange[0] 180 | if (event.volume != null && event.volume.master != null) { 181 | this.values.volume = event.volume.master 182 | if ( 183 | this.zpClient.balance && 184 | event.volume.lf != null && event.volume.rf != null 185 | ) { 186 | this.values.balance = event.volume.rf - event.volume.lf 187 | } 188 | } 189 | if (event.mute != null && event.mute.master != null) { 190 | this.values.mute = !!event.mute.master 191 | } 192 | if (event.loudness != null && event.loudness.master != null) { 193 | this.values.loudness = !!event.loudness.master 194 | } 195 | if (event.bass != null) { 196 | this.values.bass = event.bass 197 | } 198 | if (event.treble != null) { 199 | this.values.treble = event.treble 200 | } 201 | if (event.nightMode != null) { 202 | this.values.nightSound = !!event.nightMode 203 | } 204 | if (event.dialogLevel != null) { 205 | this.values.speechEnhancement = !!event.dialogLevel 206 | } 207 | if (event.surroundEnabled != null) { 208 | this.values.surroundEnabled = !!event.surroundEnabled 209 | } 210 | if (event.surroundLevel != null) { 211 | this.values.tvLevel = event.surroundLevel 212 | } 213 | if (event.musicSurroundLevel != null) { 214 | this.values.musicLevel = event.musicSurroundLevel 215 | } 216 | if (event.surroundMode != null) { 217 | this.values.musicPlaybackFull = !!event.surroundMode 218 | } 219 | if (event.heightChannelLevel != null) { 220 | this.values.heightLevel = event.heightChannelLevel 221 | } 222 | if (event.subEnabled != null) { 223 | this.values.subEnabled = !!event.subEnabled 224 | } 225 | if (event.subGain != null) { 226 | this.values.subLevel = event.subGain 227 | } 228 | } 229 | } 230 | 231 | ZpService.Speaker = Speaker 232 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /lib/ZpService/Tv.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpService/Tv.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { ZpService } from './index.js' 7 | 8 | const remoteKeys = {} 9 | const volumeSelectors = {} 10 | 11 | function initRemoteKeys (characteristicHap) { 12 | if (Object.keys(remoteKeys).length > 0) { 13 | return 14 | } 15 | remoteKeys[characteristicHap.RemoteKey.REWIND] = 'Rewind' 16 | remoteKeys[characteristicHap.RemoteKey.FAST_FORWARD] = 'Fast Forward' 17 | remoteKeys[characteristicHap.RemoteKey.NEXT_TRACK] = 'Next Track' 18 | remoteKeys[characteristicHap.RemoteKey.PREVIOUS_TRACK] = 'Previous Track' 19 | remoteKeys[characteristicHap.RemoteKey.ARROW_UP] = 'Up' 20 | remoteKeys[characteristicHap.RemoteKey.ARROW_DOWN] = 'Down' 21 | remoteKeys[characteristicHap.RemoteKey.ARROW_LEFT] = 'Left' 22 | remoteKeys[characteristicHap.RemoteKey.ARROW_RIGHT] = 'Right' 23 | remoteKeys[characteristicHap.RemoteKey.SELECT] = 'Select' 24 | remoteKeys[characteristicHap.RemoteKey.BACK] = 'Back' 25 | remoteKeys[characteristicHap.RemoteKey.EXIT] = 'Exit' 26 | remoteKeys[characteristicHap.RemoteKey.PLAY_PAUSE] = 'Play/Pause' 27 | remoteKeys[characteristicHap.RemoteKey.INFORMATION] = 'Info' 28 | volumeSelectors[characteristicHap.VolumeSelector.INCREMENT] = 'Up' 29 | volumeSelectors[characteristicHap.VolumeSelector.DECREMENT] = 'Down' 30 | } 31 | 32 | class Tv extends ZpService { 33 | static get Speaker () { return TvSpeaker } 34 | static get InputSource () { return TvInputSource } 35 | 36 | constructor (zpAccessory, params = {}) { 37 | params.name = params.master.sonosService.values.configuredName 38 | params.Service = zpAccessory.Services.hap.Television 39 | params.subtype = 'tv' 40 | params.primaryService = true 41 | super(zpAccessory, params) 42 | this.debug('TV service') 43 | initRemoteKeys(this.Characteristics.hap) 44 | 45 | this.zpMaster = params.master 46 | this.sonosService = this.zpMaster.sonosService 47 | this.sonosValues = this.sonosService.values 48 | this.sonosService.characteristicDelegate('configuredName') 49 | .on('didSet', (value) => { 50 | this.values.configuredName = value 51 | }) 52 | this.characteristicDelegate('configuredName') 53 | .on('didSet', (value) => { 54 | this.sonosService.values.configuredName = value 55 | }) 56 | 57 | this.speaker = new ZpService.Tv.Speaker(this.zpAccessory, { 58 | master: params.master 59 | }) 60 | 61 | // HomeKit doesn't like changes to service or characteristic properties, 62 | // so we create a static set of (disabled, hidden) InputSource services 63 | // to be configured later. 64 | this.sources = [] 65 | this.inputSources = [] 66 | this.displayOrder = [] 67 | for ( 68 | let identifier = 1; 69 | identifier <= this.platform.config.maxFavourites; 70 | identifier++ 71 | ) { 72 | const inputSource = new ZpService.Tv.InputSource(this.zpAccessory, { 73 | configuredName: 'Input ' + identifier, 74 | identifier, 75 | tvService: this 76 | }) 77 | this.inputSources.push(inputSource) 78 | this.displayOrder.push(0x01, 0x04, identifier & 0xff, 0x00, 0x00, 0x00) 79 | } 80 | this.displayOrder.push(0x00, 0x00) 81 | this.once('initialised', () => { 82 | this.sonosService.characteristicDelegate('platformCoordinatorId') 83 | .on('didSet', (value) => { 84 | this.updateGroupInputSource() 85 | }) 86 | }) 87 | 88 | this.addCharacteristicDelegate({ 89 | key: 'active', 90 | Characteristic: this.Characteristics.hap.Active, 91 | value: this.sonosValues.on 92 | ? this.Characteristics.hap.Active.ACTIVE 93 | : this.Characteristics.hap.Active.INACTIVE 94 | }).on('didSet', (value) => { 95 | this.sonosService.characteristicDelegate('on').setValue(value) 96 | }) 97 | this.sonosService.characteristicDelegate('on').on('didSet', (value) => { 98 | this.values.active = value ? 1 : 0 99 | }) 100 | const activeIdentifier = this.addCharacteristicDelegate({ 101 | key: 'activeIdentifier', 102 | Characteristic: this.Characteristics.hap.ActiveIdentifier, 103 | props: { maxValue: this.platform.config.maxFavourites }, 104 | silent: true, 105 | setter: async (value) => { 106 | try { 107 | if (value < 1 || value > this.platform.config.maxFavourites) { 108 | return 109 | } 110 | const source = this.sources[value - 1] 111 | this.log( 112 | 'set %s to %j', activeIdentifier.displayName, source.configuredName 113 | ) 114 | if (value === 1 && source.uri == null) { 115 | await this.zpClient.becomeCoordinatorOfStandaloneGroup() 116 | } else if (source.uri != null) { 117 | const zp = value <= 4 ? this.zpMaster : this.zpMaster.coordinator 118 | if (source.container) { 119 | await zp.zpClient.setAvTransportQueue( 120 | source.uri, source.meta 121 | ) 122 | } else { 123 | await zp.zpClient.setAvTransportUri( 124 | source.uri, source.meta 125 | ) 126 | } 127 | zp.zpClient.play().catch((error) => { this.error(error) }) 128 | if (value === 1) { 129 | // Joined a group 130 | setTimeout(() => { 131 | this.values.activeIdentifier = 132 | zp.sonosService.values.activeIdentifier 133 | }, this.platform.config.resetTimeout) 134 | } 135 | } 136 | } catch (error) { 137 | this.error(error) 138 | } 139 | this.ignoreDidSet = true 140 | } 141 | }).on('didSet', (value) => { 142 | this.sonosValues.activeIdentifier = value 143 | if (this.ignoreDidSet) { 144 | delete this.ignoreDidSet 145 | return 146 | } 147 | if (value > 0) { 148 | const source = this.sources[value - 1] 149 | this.log('set %s to %j', activeIdentifier.displayName, source.configuredName) 150 | } 151 | }) 152 | this.sonosService.characteristicDelegate('changeInput') 153 | .on('didSet', (value) => { 154 | if (value !== 0) { 155 | activeIdentifier.setValue(this.nextIdentifier(value)) 156 | } 157 | }) 158 | this.sonosService.characteristicDelegate('uri') 159 | .on('didSet', (value) => { 160 | const identifier = this.activeIdentifier(this.sonosValues.uri) 161 | this.values.activeIdentifier = identifier 162 | }) 163 | this.addCharacteristicDelegate({ 164 | key: 'sleepDiscoveryMode', 165 | Characteristic: this.Characteristics.hap.SleepDiscoveryMode, 166 | silent: true, 167 | value: this.Characteristics.hap.SleepDiscoveryMode.ALWAYS_DISCOVERABLE 168 | }) 169 | this.addCharacteristicDelegate({ 170 | key: 'displayOrder', 171 | Characteristic: this.Characteristics.hap.DisplayOrder, 172 | silent: true, 173 | value: Buffer.from(this.displayOrder).toString('base64') 174 | }) 175 | const remoteKey = this.addCharacteristicDelegate({ 176 | key: 'remoteKey', 177 | Characteristic: this.Characteristics.hap.RemoteKey, 178 | silent: true 179 | }).on('didSet', (value) => { 180 | this.log('%s: %s', remoteKey.displayName, remoteKeys[value]) 181 | switch (value) { 182 | case this.Characteristics.hap.RemoteKey.PLAY_PAUSE: 183 | { 184 | const value = 1 - this.values.active 185 | this.sonosService.characteristicDelegate('on').setValue(value) 186 | } 187 | break 188 | case this.Characteristics.hap.RemoteKey.ARROW_LEFT: 189 | this.sonosService.characteristicDelegate('changeTrack').setValue(-1) 190 | break 191 | case this.Characteristics.hap.RemoteKey.ARROW_RIGHT: 192 | this.sonosService.characteristicDelegate('changeTrack').setValue(1) 193 | break 194 | case this.Characteristics.hap.RemoteKey.ARROW_UP: 195 | activeIdentifier.setValue(this.nextIdentifier(-1)) 196 | break 197 | case this.Characteristics.hap.RemoteKey.ARROW_DOWN: 198 | activeIdentifier.setValue(this.nextIdentifier(1)) 199 | break 200 | default: 201 | break 202 | } 203 | }) 204 | this.addCharacteristicDelegate({ 205 | key: 'powerModeSelection', 206 | Characteristic: this.Characteristics.hap.PowerModeSelection 207 | }).on('didSet', (value) => { 208 | this.sonosService.characteristicDelegate('sonosCoordinator') 209 | .setValue(true) 210 | }) 211 | this.addCharacteristicDelegate({ 212 | key: 'statusFault', 213 | Characteristic: this.Characteristics.hap.StatusFault, 214 | value: this.Characteristics.hap.StatusFault.GENERAL_FAULT 215 | }) 216 | 217 | this.values.statusFault = this.Characteristics.hap.StatusFault.GENERAL_FAULT 218 | 219 | this.notYetInitialised = true 220 | this.favouritesUpdated() 221 | this.zpHousehold.on('favouritesUpdated', this.favouritesUpdated.bind(this)) 222 | } 223 | 224 | activeIdentifier (uri) { 225 | for (let i = 0; i < this.sources.length; i++) { 226 | if (this.sources[i].uri === uri) { 227 | return i + 1 228 | } 229 | } 230 | return 0 231 | } 232 | 233 | nextIdentifier (value) { 234 | let identifier = this.values.activeIdentifier 235 | const oldIdentifier = identifier 236 | do { 237 | identifier += value 238 | if (identifier < 2) { 239 | identifier = this.platform.config.maxFavourites - 1 240 | } 241 | if (identifier > this.platform.config.maxFavourites - 1) { 242 | identifier = 2 243 | } 244 | } while ( 245 | this.inputSources[identifier - 1].values.currentVisibilityState !== 246 | this.Characteristics.hap.CurrentVisibilityState.SHOWN && 247 | identifier !== oldIdentifier 248 | ) 249 | return identifier 250 | } 251 | 252 | favouritesUpdated () { 253 | const favs = this.zpHousehold.favourites 254 | if (favs == null) { 255 | return 256 | } 257 | this.sources = [] 258 | this.configureInputSource('none', null, false) 259 | this.updateGroupInputSource(true) 260 | this.configureInputSource( 261 | 'AirPlay', 'x-sonos-vli:' + this.zpClient.id + ':1', false 262 | ) 263 | this.configureInputSource( 264 | 'Audio In', 'x-rincon-stream:' + this.zpClient.id, this.zpClient.audioIn 265 | ) 266 | this.configureInputSource( 267 | 'TV', 'x-sonos-htastream:' + this.zpClient.id + ':spdif', 268 | this.zpClient.tvIn 269 | ) 270 | for (const key in favs) { 271 | const fav = favs[key] 272 | this.configureInputSource( 273 | key.slice(0, 64), fav.uri, true, fav.container, fav.meta 274 | ) 275 | } 276 | for ( 277 | let index = this.sources.length; 278 | index < this.platform.config.maxFavourites - 1; 279 | index++ 280 | ) { 281 | this.configureInputSource(`Input ${index + 1}`, null, false) 282 | } 283 | this.configureInputSource('Sonos Chime', 'x-rincon-buzzer:0', true) 284 | this.log( 285 | 'input sources: %j', 286 | this.sources.filter((source) => { 287 | return source.visible 288 | }).map((source) => { 289 | return source.configuredName 290 | }) 291 | ) 292 | if (this.notYetInitialised) { 293 | delete this.notYetInitialised 294 | this.emit('initialised') 295 | } 296 | this.values.activeIdentifier = this.activeIdentifier(this.sonosValues.uri) 297 | } 298 | 299 | updateGroupInputSource (silent = false) { 300 | const index = 0 301 | const source = this.sources[index] 302 | const inputSource = this.inputSources[index] 303 | if (source == null || inputSource == null) { 304 | return 305 | } 306 | 307 | const platformCoordinatorId = this.sonosValues.platformCoordinatorId 308 | const zpClient = this.platform.zpClients[platformCoordinatorId] 309 | let configuredName = 'none' 310 | let uri 311 | let visible = false 312 | if ( 313 | this.sonosValues.sonosGroup != null && 314 | this.sonosValues.sonosGroup !== this.zpClient.zoneName 315 | ) { 316 | configuredName = 'Leave ' + this.sonosValues.sonosGroup 317 | visible = true 318 | } else if ( 319 | platformCoordinatorId != null && 320 | platformCoordinatorId !== this.zpClient.id && 321 | zpClient != null 322 | ) { 323 | configuredName = 'Join ' + zpClient.zoneGroupShortName 324 | uri = 'x-rincon:' + platformCoordinatorId 325 | visible = true 326 | } 327 | source.configuredName = configuredName 328 | source.uri = uri 329 | source.visible = visible 330 | inputSource.values.configuredName = configuredName 331 | inputSource.values.isConfigured = visible 332 | ? this.Characteristics.hap.IsConfigured.CONFIGURED 333 | : this.Characteristics.hap.IsConfigured.NOT_CONFIGURED 334 | inputSource.values.targetVisibilityState = visible 335 | ? this.Characteristics.hap.TargetVisibilityState.SHOWN 336 | : this.Characteristics.hap.TargetVisibilityState.HIDDEN 337 | if (!silent) { 338 | this.log( 339 | 'Input Sources: %j', 340 | this.sources.filter((source) => { 341 | return source.visible 342 | }).map((source) => { 343 | return source.configuredName 344 | }) 345 | ) 346 | } 347 | } 348 | 349 | configureInputSource (configuredName, uri, visible, container, meta) { 350 | this.sources.push({ configuredName, uri, visible, container, meta }) 351 | const identifier = this.sources.length 352 | if (identifier <= this.platform.config.maxFavourites) { 353 | const inputSource = this.inputSources[identifier - 1] 354 | inputSource.values.configuredName = configuredName 355 | inputSource.values.isConfigured = visible 356 | ? this.Characteristics.hap.IsConfigured.CONFIGURED 357 | : this.Characteristics.hap.IsConfigured.NOT_CONFIGURED 358 | if (configuredName === 'Sonos Chime') { 359 | visible = false 360 | } 361 | inputSource.values.targetVisibilityState = visible 362 | ? this.Characteristics.hap.TargetVisibilityState.SHOWN 363 | : this.Characteristics.hap.TargetVisibilityState.HIDDEN 364 | if (configuredName === 'AirPlay') { 365 | inputSource.values.inputSourceType = 366 | this.Characteristics.hap.InputSourceType.OTHER 367 | } else if (configuredName === 'TV') { 368 | inputSource.values.inputSourceType = 369 | this.Characteristics.hap.InputSourceType.HDMI 370 | } else if (uri != null && uri.startsWith('x-sonosapi-stream:')) { 371 | inputSource.values.inputSourceType = 372 | this.Characteristics.hap.InputSourceType.TUNER 373 | } 374 | } 375 | } 376 | } 377 | 378 | class TvSpeaker extends ZpService { 379 | constructor (zpAccessory, params = {}) { 380 | params.name = zpAccessory.zpClient.zoneName + ' TV Speaker' 381 | params.Service = zpAccessory.Services.hap.TelevisionSpeaker 382 | params.subtype = 'tvSpeaker' 383 | super(zpAccessory, params) 384 | const service = params.master.speakerService == null 385 | ? params.master.sonosService 386 | : params.master.speakerService 387 | this.addCharacteristicDelegate({ 388 | key: 'volumeControlType', 389 | Characteristic: this.Characteristics.hap.VolumeControlType, 390 | silent: true, 391 | value: this.Characteristics.hap.VolumeControlType.ABSOLUTE 392 | }) 393 | const volumeSelector = this.addCharacteristicDelegate({ 394 | key: 'volumeSelector', 395 | Characteristic: this.Characteristics.hap.VolumeSelector, 396 | silent: true 397 | }).on('didSet', (value) => { 398 | this.log('%s: %s', volumeSelector.displayName, volumeSelectors[value]) 399 | service.characteristicDelegate('changeVolume').setValue( 400 | value === this.Characteristics.hap.VolumeSelector.INCREMENT ? 1 : -1 401 | ) 402 | }) 403 | this.addCharacteristicDelegate({ 404 | key: 'mute', 405 | Characteristic: this.Characteristics.hap.Mute 406 | }).on('didSet', (value) => { 407 | service.characteristicDelegate('mute').setValue(value) 408 | }) 409 | this.emit('initialised') 410 | } 411 | } 412 | 413 | class TvInputSource extends ZpService { 414 | constructor (zpAccessory, params = {}) { 415 | params.name = params.configuredName 416 | params.Service = zpAccessory.Services.hap.InputSource 417 | params.subtype = 'tvInput' + params.identifier 418 | params.linkedServiceDelegate = params.tvService 419 | super(zpAccessory, params) 420 | this.tvService = params.tvService 421 | this.values.configuredName = params.configuredName 422 | this.addCharacteristicDelegate({ 423 | key: 'identifier', 424 | Characteristic: this.Characteristics.hap.Identifier, 425 | silent: true, 426 | value: params.identifier 427 | }) 428 | this.addCharacteristicDelegate({ 429 | key: 'inputSourceType', 430 | Characteristic: this.Characteristics.hap.InputSourceType, 431 | silent: true, 432 | value: this.Characteristics.hap.InputSourceType.OTHER 433 | }) 434 | this.addCharacteristicDelegate({ 435 | key: 'inputDeviceType', 436 | Characteristic: this.Characteristics.hap.InputDeviceType, 437 | silent: true, 438 | value: this.Characteristics.hap.InputDeviceType.AUDIO_SYSTEM 439 | }) 440 | this.addCharacteristicDelegate({ 441 | key: 'isConfigured', 442 | Characteristic: this.Characteristics.hap.IsConfigured, 443 | silent: true, 444 | value: this.Characteristics.hap.IsConfigured.NOT_CONFIGURED 445 | }) 446 | this.addCharacteristicDelegate({ 447 | key: 'currentVisibilityState', 448 | Characteristic: this.Characteristics.hap.CurrentVisibilityState, 449 | silent: true, 450 | value: this.Characteristics.hap.CurrentVisibilityState.HIDDEN 451 | }) 452 | this.addCharacteristicDelegate({ 453 | key: 'targetVisibilityState', 454 | Characteristic: this.Characteristics.hap.TargetVisibilityState, 455 | silent: true, 456 | value: this.Characteristics.hap.TargetVisibilityState.HIDDEN 457 | }).on('didSet', (value) => { 458 | this.values.currentVisibilityState = 459 | value === this.Characteristics.hap.TargetVisibilityState.SHOWN 460 | ? this.Characteristics.hap.CurrentVisibilityState.SHOWN 461 | : this.Characteristics.hap.CurrentVisibilityState.HIDDEN 462 | }) 463 | this.emit('initialised') 464 | } 465 | } 466 | 467 | ZpService.Tv = Tv 468 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Homebridge ZP Logo 3 |

4 | 5 | 6 | # Homebridge ZP 7 | [![Downloads](https://img.shields.io/npm/dt/homebridge-zp.svg)](https://www.npmjs.com/package/homebridge-zp) 8 | [![Version](https://img.shields.io/npm/v/homebridge-zp.svg)](https://www.npmjs.com/package/homebridge-zp) 9 | [![Homebridge Discord](https://img.shields.io/discord/432663330281226270?color=728ED5&logo=discord&label=discord)](https://discord.gg/3qFgFMk) 10 | [![verified-by-homebridge](https://badgen.net/badge/homebridge/verified/purple)](https://github.com/homebridge/homebridge/wiki/Verified-Plugins) 11 | 12 | [![GitHub issues](https://img.shields.io/github/issues/ebaauw/homebridge-zp)](https://github.com/ebaauw/homebridge-zp/issues) 13 | [![GitHub pull requests](https://img.shields.io/github/issues-pr/ebaauw/homebridge-zp)](https://github.com/ebaauw/homebridge-zp/pulls) 14 | [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen)](https://standardjs.com) 15 | 16 | 17 | 18 | ## Homebridge plugin for Sonos Zone Players 19 | Copyright © 2016-2025 Erik Baauw. All rights reserved. 20 | 21 | This [Homebridge](https://github.com/homebridge/homebridge) plugin exposes [Sonos](http://www.sonos.com) zone players to Apple's [HomeKit](http://www.apple.com/ios/home/). 22 | It provides the following features: 23 | - Automatic discovery of [Sonos zones](#zones), taking into account stereo pairs and home theatre setup; 24 | - Support for [Sonos groups](#groups), created through the Sonos app; 25 | - Control from HomeKit of play/pause, sleep timer, next/previous track, volume, and mute per Sonos group; 26 | - Control from HomeKit of input selection per group, from Sonos favourites and local sources, like Airplay, Line-In, TV; 27 | - Optional control from HomeKit of volume, mute, balance, bass, treble, loudness, and home theatre audio settings per Sonos zone; 28 | - Optional control from HomeKit for Sonos zones leaving Sonos groups, and for Sonos zones creating/joining one Sonos group; 29 | - Optional control from HomeKit to enable/disable Sonos alarms; 30 | - Real-time monitoring from HomeKit of state per Sonos group and, optionally, per Sonos zone. 31 | Like the Sonos app, Homebridge ZP subscribes to zone player events to receive notifications; 32 | - Optional control from HomeKit for the status LED and child lock per zone player. 33 | Note that Sonos doesn't support events for these, so Homebridge ZP cannot provide real-time monitoring for this; 34 | - Includes a [command-line tool](#command-line-tool), for controlling Sonos zone players and for troubleshooting. 35 | 36 | ## Contents 37 | 38 | * [Prerequisites](#prerequisites) 39 | * [Zones](#zones) 40 | * [Groups](#groups) 41 | * [Speakers](#speakers) 42 | * [Command-Line Tool](#command-line-tool) 43 | * [Installation](#installation) 44 | * [Configuration](#configuration) 45 | * [Troubleshooting](#troubleshooting) 46 | * [Caveats](#caveats) 47 | 48 | ### Prerequisites 49 | You need a server to run Homebridge. 50 | This can be anything running [Node.js](https://nodejs.org): from a Raspberry Pi, a NAS system, or an always-on PC running Linux, macOS, or Windows. 51 | See the [Homebridge Wiki](https://github.com/homebridge/homebridge/wiki) for details. 52 | I run Homebridge ZP on a Raspberry Pi 3B+. 53 | 54 | To interact with HomeKit, you need Siri or a HomeKit app on an iPhone, Apple Watch, iPad, iPod Touch, or Apple TV (4th generation or later). 55 | I recommend to use the latest released versions of iOS, watchOS, and tvOS. 56 | Please note that Siri and even Apple's [Home](https://support.apple.com/en-us/HT204893) app still provide only limited HomeKit support. 57 | To use the full features of Homebridge Zp, you might want to check out some other HomeKit apps, like the [Eve](https://www.evehome.com/en/eve-app) app (free) or Matthias Hochgatterer's [Home+](https://hochgatterer.me/home/) app (paid). 58 | 59 | As Sonos uses UPnP to discover the zone players, the server running Homebridge must be on the same subnet as your Sonos zone players. 60 | As HomeKit uses Bonjour to discover Homebridge, the server running Homebridge must be on the same subnet as your iDevices running HomeKit. 61 | For remote access and for HomeKit automations, you need to setup an Apple TV (4th generation or later), HomePod, or iPad as [home hub](https://support.apple.com/en-us/HT207057). 62 | 63 | ### Zones 64 | Homebridge ZP creates an accessory per Sonos zone, named after the zone, e.g. *Living Room Sonos* for the *Living Room* zone. 65 | By default, this accessory contains a single `Switch` service, with the same name as the accessory. The standard `On` characteristic is used for play/pause control. 66 | Additional characteristics control volume, select input, change track, etc. 67 | However, neither Apple's Home app nor Siri support these. 68 | 69 | To control the volume from Apple's Home app and/or Siri, the type of the service, as well as the type of characteristic used for volume can be changed from `config.json`, see [**Configuration**](#configuration) and [issue #10](https://github.com/ebaauw/homebridge-zp/issues/10). 70 | Note that speaker support in Apple's Home app is based on the AirPlay2 protocol. 71 | Despite the "HomeKit" branding, technically, this has nothing to do with HomeKit. 72 | No Homebridge plugin can expose speakers that look like AirPlay2 speakers in the Home app. 73 | Also note that these Airplay2 speakers cannot be accessed by other HomeKit apps. 74 | 75 | When `"tv": true` is set in `config.json`, Homebridge ZP creates an additional *Television* accessory per zone, allowing input selection from Apple's Home app and control from the *Remote* widget. 76 | Note that Apple has imposed some technical restrictions on *Television* accessories: 77 | - They cannot be bridged; they need to be paired to HomeKit individually; 78 | - They cannot be accessed by HomeKit apps; only from Apple's Home app. 79 | 80 | ### Groups 81 | When you combine multiple Sonos zones into one Sonos group, e.g. *Living Room* and *Kitchen*, the Sonos app shows them as a single room, like *Living Room + 1*, with shared control for play/pause, music source, and (group) volume and mute. 82 | When this group is broken, each zone forms a separate standalone group, containing only that zone. 83 | The Sonos app shows each standalone group as a separate room, with separate control per room for play/pause, music source, and (zone) volume and mute. 84 | 85 | If Homebridge ZP would mimic this behaviour, dynamically creating and deleting accessories for groups, HomeKit would lose the assignment to HomeKit rooms, groups, scenes, and automations, every time an accessory is deleted. 86 | Consequently, you would have to reconfigure HomeKit each time you group or ungroup Sonos zones. 87 | 88 | To overcome this, Homebridge ZP creates an accessory and corresponding service for each Sonos zone. This service actually controls the Sonos *group* the zone is in rather than the zone. 89 | When separated, the *Living Room Sonos* service controls the standalone *Living Room* group, consisting of only the *Living Room* zone; and the *Kitchen Sonos* service controls the standalone *Kitchen* group, consisting of only the *Kitchen* zone. 90 | When grouped, both the *Living Room Sonos* service and the *Kitchen Sonos* service control the multi-zone *Living Room + 1* group, containing both the *Living Room* and *Kitchen* zones. 91 | The `Sonos Group` characteristic indicates which group the zone belongs to, by showing the name of the group coordinator zone, like: *Living Room*. 92 | 93 | So, when grouped, adjusting the volume of the *Living Room Sonos* service changes the volume on both the *Living Room* and *Kitchen* zones. The same happens if you adjust the volume of the *Kitchen Sonos* service. 94 | When ungrouped, changing the volume of the *Living Room Sonos* accessory only affects the *Living Room* zone, and changing the volume of the *Kitchen Sonos* service only affects the the *Kitchen* zone. 95 | 96 | ### Speakers 97 | To change the volume of an individual zone in a multi-zone group, an additional `Volume` characteristic is needed for the zone, next to the `Volume` characteristic for the group. 98 | As HomeKit doesn't support multiple characteristics of the same type per service, it actually requires an additional service. 99 | By specifying `"speakers": true` in `config.json`, Homebridge ZP creates an additional *Speakers* service for each zone accessory, to control the individual zone. This service is named after the zone as well, in our example: *Living Room Speakers*. 100 | 101 | The *Speakers* service `On` characteristic is used to join, or leave a Sonos group. 102 | `On` is set, when the zone is a member of other zone's group. 103 | It is cleared, when the zone is the coordinator of it's own group (either standalone or with other zones as member). 104 | By setting `On`, the zone will join groups with the target coordinator. 105 | The target coordinator is set using the `Sonos Coordinator` characteristic in the *Sonos* service. 106 | By clearing `On`, the zone will leave the group and become coordinator of a standalone group. 107 | 108 | Additional characteristics for `Volume`, `Mute`, `Bass`, `Treble`, `Loudness`, and home theatre audio control the corresponding zone attributes. 109 | Note that these are custom characteristics, except for `Volume`. They might not be supported by all HomeKit apps, see [Caveats](#caveats). 110 | 111 | Like the *Sonos* service, the type of the *Speakers* service can be changed in `config.json` from the default `Switch`, as well as the type of characteristic used for volume, see [Configuration](#configuration). 112 | 113 | ### Command-Line Tool 114 | Homebridge ZP includes a command-line tool, `zp`, to interact with your Sonos Zone Players from the command line. 115 | It takes a `-h` or `--help` argument to provide a brief overview of its functionality and command-line arguments. 116 | 117 | ### Installation 118 | To install Homebridge ZP: 119 | - Follow the instructions on the [Homebridge Wiki](https://github.com/homebridge/homebridge/wiki) to install Node.js and Homebridge; 120 | - Install the Homebridge ZP plugin through Homebridge Config UI X or manually by: 121 | ``` 122 | $ sudo npm -g i homebridge-zp 123 | ``` 124 | - Edit `config.json` and add the `ZP` platform provided by Homebridge ZP, see [**Configuration**](#configuration). 125 | 126 | ### Configuration 127 | In Homebridge's `config.json` you need to specify Homebridge ZP as a platform plugin: 128 | ```json 129 | "platforms": [ 130 | { 131 | "platform": "ZP" 132 | } 133 | ] 134 | ``` 135 | The following optional parameters can be added to modify Homebridge ZP's behaviour: 136 | 137 | Key | Default | Description 138 | --- | ------- | ----------- 139 | `alarms` | `false` | Flag whether to expose an additional service per Sonos alarm. 140 | `brightness` | `false` | Flag whether to expose volume as `Brightness` when `service` is `"switch"` or `"speaker"`. Setting this flag enables volume control from Siri, but not from Apple's Home app. 141 | `excludeAirPlay` | `false` | Flag whether not to expose zone players that support Airplay, since they natively show up in Apple's Home app.
Note that if you only have newer zome players that support Airplay, enabling this option will essentially disable the plugin, as all zones will be hidden from Homekit. 142 | `heartrate` | (disabled) | Interval (in seconds) to poll zone players when `leds` is set. 143 | `leds` | `false` | Flag whether to expose an additional *Lightbulb* service per zone for the status LED. This also supports locking the physical controls. 144 | `maxFavourites` | 96 | The number of preconfigured stations for a TV accessory, to be mapped to Sonos favourites. 145 | `mdns` | `true` | Enable zone player discovery through mDNS. 146 | `port` | `0` _(random)_ | The port for the web server Homebridge ZP creates to receive notifications from Sonos zone players. 147 | `resetTimeout` | `500` | Timeout (in milliseconds) to reset input (e.g. _Change Volume_). 148 | `service` | `"switch"` | Defines what type of service and volume characteristic Homebridge ZP uses. Possible values are: `"switch"` for `Switch` and `Volume`; `"speaker"` for `Speaker` and `Volume`; `"light"` for `LightBulb` and `Brightness`; and `"fan"` for `Fan` and `Rotation Speed`. Selecting `"light"` or `"fan"` enables changing the Sonos volume from Siri and from Apple's Home app. Selecting `"speaker"` results in a *not supported* accessory in Apple's Home app. 149 | `speakers` | `false` | Flag whether to expose a second *Speakers* service per zone, in addition to the standard *Sonos* service, see [Speakers](#speakers). You might want to set this if you're using Sonos groups in a configuration of multiple Sonos zones. 150 | `subscriptionTimeout` | `30` | The duration (in minutes) of the subscriptions Homebridge ZP creates with each zone player. 151 | `timeout` | `15` | The timeout (in seconds) to wait for a response from a Sonos zone player. 152 | `tv` | `false` | Create an additional, non-bridged TV accessory for each zone.
Note that each TV accessory needs to be paired with HomeKit separately, using the same pin as for Homebridge, as specified in `config.json`. 153 | `tvIdPrefix` | `TV` | Prefix for serial number of TV accessories, to enable multiple instances of Homebridge ZP on the same network. 154 | 155 | Below is an example `config.json` that exposes the *Sonos* and *Speakers* service as a HomeKit `Speaker` and volume as `Brightness`, so it can be controlled from Siri: 156 | ```json 157 | "platforms": [ 158 | { 159 | "platform": "ZP", 160 | "service": "speaker", 161 | "brightness": true, 162 | "speakers": true 163 | } 164 | ] 165 | ``` 166 | 167 | #### Split Sonos System 168 | If you have a split Sonos system, Homebridge ZP will expose both the S2 and the S1 zone players. 169 | Of course you can only group S2 zone players with other S2 zone players; and S1 zone players with other S1 zone players. 170 | The same restriction applies when you have multiple Sonos households on your network: you can only group zone players with other zone players in the same household. 171 | 172 | ### Troubleshooting 173 | 174 | #### Check Dependencies 175 | If you run into Homebridge startup issues, please double-check what versions of Node.js and of Homebridge have been installed. 176 | Homebridge ZP has been developed and tested using the [latest LTS](https://nodejs.org/en/about/releases/) version of Node.js and the [latest](https://www.npmjs.com/package/homebridge) version of Homebridge. 177 | Other versions might or might not work - I simply don't have the bandwidth to test these. 178 | 179 | #### Run Homebridge ZP Solo 180 | If you run into Homebridge startup issues, please run a separate instance of Homebridge with only Homebridge ZP (and Homebridge Config UI X) enabled in `config.json`. 181 | This way, you can determine whether the issue is related to Homebridge ZP itself, or to the interaction of multiple Homebridge plugins in your setup. 182 | You can start this separate instance of Homebridge on a different system, as a different user, or from a different user directory (specified by the `-U` flag). 183 | Make sure to use a different Homebridge `name`, `username`, and (if running on the same system) `port` in the `config.json` for each instance. 184 | 185 | #### Debug Log File 186 | Homebridge ZP outputs an info message for each HomeKit characteristic value it sets and for each HomeKit characteristic value change notification it receives. 187 | When Homebridge is started with `-D`, Homebridge ZP outputs a debug message for each request it makes to a Sonos zone player and for each zone player notification event it receives. 188 | 189 | To capture these messages into a log file do the following: 190 | - If you're running Homebridge as a service, stop that service; 191 | - Run Homebridge manually, capturing the output into a file, by issuing: 192 | ``` 193 | $ homebridge -CD 2>&1 | tee homebridge.log 194 | ``` 195 | - Interact with your devices, through their native app and or through HomeKit to trigger the issue; 196 | - Hit interrupt (ctrl-C) to stop Homebridge; 197 | - If you're running Homebridge as a service, restart the service; 198 | - Compress the log file by issuing: 199 | ``` 200 | $ gzip homebridge.log 201 | ``` 202 | 203 | #### Web Server 204 | Like the Sonos app, Homebridge ZP subscribes to the zone player events to be notified in real-time of changes. It creates a web server to receive these notifications. The IP address and port number for this listener are logged in a debug message, e.g. 205 | ``` 206 | [1/1/2020, 11:58:35 AM] [Sonos] listening on http://192.168.x.x:58004/notify 207 | ``` 208 | To check whether the listener is reachable from the network, open this URL in your web browser. You should see an overview of the active subscriptions per zone player. 209 | 210 | #### Getting Help 211 | If you have a question, please post a message to the **#zp** channel of the Homebridge community on [Discord](https://discord.gg/3qFgFMk). 212 | 213 | If you encounter a problem, please open an issue on [GitHub](https://github.com/ebaauw/homebridge-zp/issues). 214 | Please **attach** a copy of `homebridge.log.gz` to the issue, see [**Debug Log File**](#debug-log-file). 215 | Please do **not** copy/paste large amounts of log output. 216 | 217 | ### Caveats 218 | Homebridge ZP is a hobby project of mine, provided as-is, with no warranty whatsoever. I've been running it successfully at my home for years, but your mileage might vary. 219 | 220 | The HomeKit terminology needs some getting used to. 221 | An _accessory_ more or less corresponds to a physical device, accessible from your iOS device over WiFi or Bluetooth. 222 | A _bridge_ (like Homebridge) is an accessory that provides access to other, bridged, accessories. 223 | An accessory might provide multiple _services_. 224 | Each service corresponds to a virtual device (like a lightbulb, switch, motion sensor, ..., but also: a programmable switch button, accessory information, battery status). 225 | Siri interacts with services, not with accessories. 226 | A service contains one or more _characteristics_. 227 | A characteristic is like a service attribute, which might be read or written by HomeKit apps. 228 | You might want to checkout Apple's [HomeKit Accessory Simulator](https://developer.apple.com/documentation/homekit/testing_your_app_with_the_homekit_accessory_simulator), which is distributed as an additional tool for `Xcode`. 229 | 230 | The Sonos terminology needs some getting used to. 231 | A _zone_ corresponds to a physical room. 232 | It consists of a single zone player, two zone players configured as a stereo pair, or a home theatre setup (e.g. a PlayBar with separate surround speakers). 233 | Typically, zone setup is static; you would only change it when physically re-arranging your zone players between rooms. 234 | A _zone group_ is a collection of one or more zones, playing the same music in sync. 235 | A zone group is controlled by its _coordinator_ zone. 236 | Typically, groups are dynamic, you add and/or remove zones to/from a group when listening to your music. 237 | Controls for play/pause and music source act on a zone group. 238 | Controls for volume and mute act on a zone group or on a single zone. 239 | Controls for bass, treble, and loudness act on a single zone. 240 | Note that Sonos uses the term _room_ ambiguously: on the Sonos app main screen it corresponds to a zone group, but in the Room Settings it corresponds to a zone. 241 | -------------------------------------------------------------------------------- /lib/ZpService/Sonos.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpService/Sonos.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import he from 'he' 7 | 8 | import { ZpService } from './index.js' 9 | 10 | class Sonos extends ZpService { 11 | constructor (zpAccessory, params = {}) { 12 | params.name = zpAccessory.zpClient.zoneName + ' Sonos' 13 | params.Service = zpAccessory.platform.config.SpeakerService 14 | params.subtype = 'group' 15 | super(zpAccessory, params) 16 | this.debug('Sonos service') 17 | this.zpClient.on('message', (message) => { 18 | try { 19 | const f = `handle${message.device}${message.service}Event` 20 | if (this[f] != null) { 21 | this[f](message.parsedBody) 22 | } 23 | } catch (error) { 24 | this.error(error) 25 | } 26 | }) 27 | this.addCharacteristicDelegate({ 28 | key: 'on', 29 | Characteristic: this.Characteristics.hap.On, 30 | setter: async (value) => { 31 | try { 32 | if (value === this.values.on) { 33 | return 34 | } 35 | const coordinatorValues = this.zpAccessory.coordinator.sonosService.values 36 | if ( 37 | value && 38 | coordinatorValues.currentTransportActions.includes('Play') && 39 | coordinatorValues.currentTrack !== 'TV' 40 | ) { 41 | await this.zpAccessory.coordinator.zpClient.play() 42 | const duration = this.values.setDuration <= 10 43 | ? '' 44 | : new Date(this.values.setDuration * 1000) 45 | .toISOString().slice(11, 19) 46 | await this.zpAccessory.coordinator.zpClient.setSleepTimer(duration) 47 | } else if ( 48 | !value && 49 | coordinatorValues.currentTransportActions.includes('Pause') 50 | ) { 51 | await this.zpAccessory.coordinator.zpClient.pause() 52 | } else if ( 53 | !value && 54 | coordinatorValues.currentTransportActions.includes('Stop') 55 | ) { 56 | await this.zpAccessory.coordinator.zpClient.stop() 57 | } else { 58 | setTimeout(() => { 59 | this.values.on = !value 60 | }, this.platform.config.resetTimeout) 61 | } 62 | } catch (error) { 63 | this.error(error) 64 | } 65 | }, 66 | timeout: 5000 67 | }) 68 | this.addCharacteristicDelegate({ 69 | key: 'setDuration', 70 | Characteristic: this.Characteristics.hap.SetDuration, 71 | silent: true, 72 | unit: 's', 73 | props: { maxValue: 86399 }, // 23:59:59 74 | value: 0 75 | }).on('didSet', (value) => { 76 | if (value <= 10) { 77 | setTimeout(() => { 78 | this.values.setDuration = 0 79 | }, this.platform.config.resetTimeout) 80 | } 81 | }) 82 | this.addCharacteristicDelegate({ 83 | key: 'remainingDuration', 84 | Characteristic: this.Characteristics.hap.RemainingDuration, 85 | unit: 's', 86 | props: { maxValue: 86399 }, // 23:59:59 87 | getter: async (value) => { 88 | try { 89 | if (this.zpAccessory.coordinator == null) { 90 | return 0 91 | } 92 | const timer = await this.zpAccessory.coordinator.zpClient.getSleepTimer() 93 | if (timer === '') { 94 | return 0 95 | } 96 | return timer.split(':').reduce((value, time) => { 97 | return 60 * value + +time 98 | }) 99 | } catch (error) { 100 | this.error(error) 101 | return 0 102 | } 103 | }, 104 | timeout: 2000 105 | }) 106 | this.addCharacteristicDelegate({ 107 | key: 'volume', 108 | Characteristic: this.platform.config.VolumeCharacteristic, 109 | unit: '%', 110 | setter: async (value) => { 111 | try { 112 | await this.zpAccessory.coordinator.zpClient.setGroupVolume(value) 113 | } catch (error) { 114 | this.error(error) 115 | } 116 | } 117 | }) 118 | this.addCharacteristicDelegate({ 119 | key: 'changeVolume', 120 | Characteristic: this.Characteristics.my.ChangeVolume, 121 | value: 0, 122 | setter: async (value) => { 123 | try { 124 | await this.zpAccessory.coordinator.zpClient.setRelativeGroupVolume(value) 125 | } catch (error) { 126 | this.error(error) 127 | } 128 | setTimeout(() => { 129 | this.values.changeVolume = 0 130 | }, this.platform.config.resetTimeout) 131 | } 132 | }) 133 | this.addCharacteristicDelegate({ 134 | key: 'mute', 135 | Characteristic: this.Characteristics.hap.Mute, 136 | setter: async (value) => { 137 | try { 138 | await this.zpAccessory.coordinator.zpClient.setGroupMute(value) 139 | } catch (error) { 140 | this.error(error) 141 | } 142 | } 143 | }) 144 | this.addCharacteristicDelegate({ 145 | key: 'currentValidPlayModes', 146 | silent: true, 147 | value: [] 148 | }) 149 | this.addCharacteristicDelegate({ 150 | key: 'repeat', 151 | Characteristic: this.Characteristics.my.Repeat, 152 | setter: async (value) => { 153 | try { 154 | const coordinatorValues = this.zpAccessory.coordinator.sonosService.values 155 | if ( 156 | value === 0 || coordinatorValues.currentValidPlayModes.includes( 157 | value === 1 ? 'REPEATONE' : 'REPEAT' 158 | ) 159 | ) { 160 | await this.zpAccessory.coordinator.zpClient.setRepeat( 161 | ['off', '1', 'on'][value] 162 | ) 163 | } else { 164 | setTimeout(() => { 165 | this.values.repeat = 0 166 | }, this.platform.config.resetTimeout) 167 | } 168 | } catch (error) { 169 | this.error(error) 170 | } 171 | } 172 | }) 173 | this.addCharacteristicDelegate({ 174 | key: 'shuffle', 175 | Characteristic: this.Characteristics.my.Shuffle, 176 | setter: async (value) => { 177 | try { 178 | const coordinatorValues = this.zpAccessory.coordinator.sonosService.values 179 | if (!value || coordinatorValues.currentValidPlayModes.includes('SHUFFLE')) { 180 | await this.zpAccessory.coordinator.zpClient.setShuffle(value) 181 | } else { 182 | setTimeout(() => { 183 | this.values.shuffle = false 184 | }, this.platform.config.resetTimeout) 185 | } 186 | } catch (error) { 187 | this.error(error) 188 | } 189 | } 190 | }) 191 | this.addCharacteristicDelegate({ 192 | key: 'crossfade', 193 | Characteristic: this.Characteristics.my.Crossfade, 194 | setter: async (value) => { 195 | try { 196 | const coordinatorValues = this.zpAccessory.coordinator.sonosService.values 197 | if (!value || coordinatorValues.currentValidPlayModes.includes('CROSSFADE')) { 198 | await this.zpAccessory.coordinator.zpClient.setCrossfadeMode(value) 199 | } else { 200 | setTimeout(() => { 201 | this.values.crossfade = false 202 | }, this.platform.config.resetTimeout) 203 | } 204 | } catch (error) { 205 | this.error(error) 206 | } 207 | } 208 | }) 209 | this.addCharacteristicDelegate({ 210 | key: 'currentTrack', 211 | Characteristic: this.Characteristics.my.CurrentTrack 212 | }) 213 | this.addCharacteristicDelegate({ 214 | key: 'uri', 215 | silent: true 216 | }) 217 | this.addCharacteristicDelegate({ 218 | key: 'currentTransportActions', 219 | silent: true, 220 | value: [] 221 | }) 222 | this.addCharacteristicDelegate({ 223 | key: 'changeTrack', 224 | Characteristic: this.Characteristics.my.ChangeTrack, 225 | value: 0, 226 | setter: async (value) => { 227 | try { 228 | const coordinatorValues = this.zpAccessory.coordinator.sonosService.values 229 | if ( 230 | value > 0 && 231 | coordinatorValues.currentTransportActions.includes('Next') 232 | ) { 233 | await this.zpAccessory.coordinator.zpClient.next() 234 | } else if ( 235 | value < 0 && 236 | coordinatorValues.currentTransportActions.includes('Previous') 237 | ) { 238 | await this.zpAccessory.coordinator.zpClient.previous() 239 | } 240 | } catch (error) { 241 | this.error(error) 242 | } 243 | setTimeout(() => { 244 | this.values.changeTrack = 0 245 | }, this.platform.config.resetTimeout) 246 | } 247 | }) 248 | if (this.platform.config.tv) { 249 | this.addCharacteristicDelegate({ 250 | key: 'activeIdentifier', 251 | Characteristic: this.Characteristics.hap.ActiveIdentifier, 252 | props: { maxValue: this.platform.config.maxFavourites }, 253 | setter: async (value) => { 254 | this.platform.zpTvs[this.zpClient.id].tvService 255 | .characteristicDelegate('activeIdentifier').setValue(value) 256 | } 257 | }) 258 | this.addCharacteristicDelegate({ 259 | key: 'changeInput', 260 | Characteristic: this.Characteristics.my.ChangeInput, 261 | value: 0, 262 | setter: async (value) => { 263 | setTimeout(() => { 264 | this.values.changeInput = 0 265 | }, this.platform.config.resetTimeout) 266 | } 267 | }) 268 | } 269 | if (this.zpClient.tvIn) { 270 | this.addCharacteristicDelegate({ 271 | key: 'tv', 272 | Characteristic: this.Characteristics.my.Tv 273 | }) 274 | } 275 | this.addCharacteristicDelegate({ 276 | key: 'sonosGroup', 277 | Characteristic: this.Characteristics.my.SonosGroup, 278 | value: '' 279 | }) 280 | this.addCharacteristicDelegate({ 281 | key: 'sonosCoordinator', 282 | Characteristic: this.Characteristics.my.SonosCoordinator, 283 | value: false, 284 | setter: async (value) => { 285 | try { 286 | if (value) { 287 | this.platform.setPlatformCoordinator(this.zpAccessory) 288 | if (this.zpAccessory.coordinator !== this.zpAccessory) { 289 | this.zpAccessory.coordinator.zpClient.delegateGroupCoordinationTo( 290 | this.zpClient.id 291 | ) 292 | } 293 | } else { 294 | setTimeout(() => { 295 | this.values.sonosCoordinator = true 296 | }, this.platform.config.resetTimeout) 297 | } 298 | } catch (error) { 299 | this.error(error) 300 | } 301 | } 302 | }) 303 | this.addCharacteristicDelegate({ 304 | key: 'platformCoordinatorId', 305 | silent: true 306 | }) 307 | if (this.values.sonosCoordinator) { 308 | this.platform.setPlatformCoordinator(this.zpAccessory) 309 | } 310 | this.addCharacteristicDelegate({ 311 | key: 'logLevel', 312 | Characteristic: this.Characteristics.my.LogLevel, 313 | props: { maxValue: 4 }, 314 | value: this.accessoryDelegate.logLevel 315 | }) 316 | this.addCharacteristicDelegate({ 317 | key: 'lastSeen', 318 | Characteristic: this.Characteristics.my.LastSeen, 319 | value: 'n/a', 320 | silent: true 321 | }) 322 | this.addCharacteristicDelegate({ 323 | key: 'statusFault', 324 | Characteristic: this.Characteristics.hap.StatusFault, 325 | value: this.Characteristics.hap.StatusFault.GENERAL_FAULT 326 | }) 327 | 328 | this.values.statusFault = this.Characteristics.hap.StatusFault.GENERAL_FAULT 329 | this.emit('initialised') 330 | 331 | zpAccessory.once('initialised', async () => { 332 | try { 333 | await this.zpClient.subscribe('/MediaRenderer/AVTransport/Event') 334 | await this.zpClient.subscribe('/MediaRenderer/GroupRenderingControl/Event') 335 | } catch (error) { 336 | this.error(error) 337 | } 338 | }) 339 | } 340 | 341 | handleMediaRendererAVTransportEvent (message) { 342 | if ( 343 | message.lastChange == null || 344 | !Array.isArray(message.lastChange) || 345 | message.lastChange[0] == null 346 | ) { 347 | return 348 | } 349 | if (this.zpAccessory.isCoordinator === false) { 350 | this.zpAccessory.leaving = true 351 | } 352 | const event = message.lastChange[0] 353 | let on 354 | let tv = false 355 | let track 356 | let currentTransportActions 357 | let repeat 358 | let shuffle 359 | let crossfade 360 | let currentValidPlayModes 361 | let uri 362 | const state = event.transportState 363 | if (state != null) { 364 | on = state === 'PLAYING' || state === 'TRANSITIONING' 365 | } 366 | const meta = event.currentTrackMetaData 367 | // this.debug('currentTrackMetaData: %j', meta) 368 | if (event.currentTrackUri != null && event.currentTrackUri !== '') { 369 | switch (event.currentTrackUri.split(':')[0]) { 370 | case 'x-rincon-buzzer': // Sonos Chime 371 | track = 'Sonos Chime' 372 | uri = event.currentTrackUri 373 | break 374 | case 'x-sonos-vli': // AirPlay 375 | case 'x-sonosapi-vli': // Airplay ??? 376 | track = meta.title 377 | uri = event.currentTrackUri.split(',')[0] 378 | break 379 | case 'x-rincon-stream': // Line in input. 380 | track = meta.title 381 | uri = event.currentTrackUri 382 | break 383 | case 'x-sonos-htastream': // SPDIF TV input. 384 | track = 'TV' 385 | tv = meta.streamInfo !== 0 // 0: no input; 2: stereo; 18: Dolby 5.1; 22: ? 386 | uri = event.currentTrackUri 387 | break 388 | case 'aac': // Radio stream (e.g. DI.fm) 389 | case 'x-sonosapi-stream': // Radio stream. 390 | case 'x-rincon-mp3radio': // AirTunes (by homebridge-zp). 391 | track = meta.streamContent // info 392 | if (track === '') { 393 | if (event.enqueuedTransportUriMetaData != null) { 394 | track = event.enqueuedTransportUriMetaData.title // station 395 | } 396 | } 397 | break 398 | case 'hls-radio': { // Radio stream, see #125. 399 | const a = /^TYPE=SNG\|TITLE (.*)\|ARTIST (.*)\|ALBUM/.exec(meta.streamContent) 400 | if (a != null) { 401 | track = a[2] === '' ? a[1] : a[2] + ' - ' + a[1] 402 | } else if (event.enqueuedTransportUriMetaData != null) { 403 | track = event.enqueuedTransportUriMetaData.title // station 404 | } 405 | } 406 | break 407 | case 'x-file-cifs': // Library song. 408 | case 'x-sonos-http': // See issue #44. 409 | case 'http': // Song on iDevice. 410 | case 'https': // Apple Music, see issue #68 411 | case 'x-sonos-spotify': // Spotify song. 412 | case 'x-sonosprog-http': // Apple Music, see issue #125 413 | case 'x-sonosapi-rtrecent': // ?? 414 | if (meta.title != null) { 415 | track = meta.title // song 416 | } 417 | break 418 | case 'x-sonosapi-hls': // ?? 419 | case 'x-sonosapi-hls-static': // e.g. Amazon Music 420 | // Skip! update will arrive in subsequent CurrentTrackMetaData events 421 | // and will be handled by default case 422 | break 423 | case 'x-rincon': // zone group 424 | // skip - handled by coordinator 425 | break 426 | default: 427 | this.warn('unknown uri: %j', event.currentTrackUri) 428 | if (meta.title != null) { 429 | track = meta.title // song 430 | } else { 431 | track = '' 432 | } 433 | break 434 | } 435 | } 436 | if ( 437 | event.enqueuedTransportUri != null && event.enqueuedTransportUri !== '' 438 | ) { 439 | uri = event.enqueuedTransportUri // playlist 440 | } 441 | if (event.currentTransportActions != null) { 442 | currentTransportActions = event.currentTransportActions.split(', ') 443 | if (currentTransportActions.length === 1) { 444 | track = '' 445 | } 446 | } 447 | if ( 448 | event.sleepTimerGeneration != null && 449 | this.zpAccessory.coordinator === this.zpAccessory 450 | ) { 451 | this.zpClient.getSleepTimer().then((timer) => { 452 | const value = timer === '' 453 | ? 0 454 | : timer.split(':').reduce((value, time) => { 455 | return 60 * value + +time 456 | }) 457 | this.values.remainingDuration = value 458 | for (const member of this.zpAccessory.members()) { 459 | member.sonosService.values.remainingDuration = 460 | this.values.remainingDuration 461 | } 462 | }).catch((error) => { this.error(error) }) 463 | } 464 | if (on != null) { 465 | this.values.on = on 466 | for (const member of this.zpAccessory.members()) { 467 | member.sonosService.values.on = this.values.on 468 | } 469 | } 470 | if ( 471 | track != null && 472 | track !== 'ZPSTR_CONNECTING' && track !== 'ZPSTR_BUFFERING' 473 | ) { 474 | this.values.currentTrack = track.slice(0, 64) 475 | for (const member of this.zpAccessory.members()) { 476 | member.sonosService.values.currentTrack = this.values.currentTrack 477 | } 478 | } 479 | if (event.currentValidPlayModes != null) { 480 | currentValidPlayModes = event.currentValidPlayModes.split(',') 481 | } 482 | if (event.currentPlayMode != null) { 483 | if (event.currentPlayMode === 'NORMAL') { 484 | repeat = 0 485 | shuffle = false 486 | } else if (event.currentPlayMode === 'REPEAT_ONE') { 487 | repeat = 1 488 | shuffle = false 489 | } else if (event.currentPlayMode === 'REPEAT_ALL') { 490 | repeat = 2 491 | shuffle = false 492 | } else if (event.currentPlayMode === 'SHUFFLE_NOREPEAT') { 493 | repeat = 0 494 | shuffle = true 495 | } else if (event.currentPlayMode === 'SHUFFLE_REPEAT_ONE') { 496 | repeat = 1 497 | shuffle = true 498 | } else if (event.currentPlayMode === 'SHUFFLE') { 499 | repeat = 2 500 | shuffle = true 501 | } 502 | } 503 | if (event.currentCrossfadeMode != null) { 504 | crossfade = event.currentCrossfadeMode === 1 505 | } 506 | if (tv != null) { 507 | if (tv !== this.values.tv) { 508 | if (tv || this.values.tv == null || track !== 'TV') { 509 | this.values.tv = tv 510 | } else { 511 | this.tvTimer = setTimeout(() => { 512 | this.tvTimer = null 513 | this.values.tv = tv 514 | }, 10000) 515 | } 516 | } else if (this.tvTimer != null) { 517 | clearTimeout(this.tvTimer) 518 | this.tvTimer = null 519 | } 520 | } 521 | if (currentTransportActions != null) { 522 | this.values.currentTransportActions = currentTransportActions 523 | for (const member of this.zpAccessory.members()) { 524 | member.sonosService.values.currentTransportActions = 525 | this.values.currentTransportActions 526 | } 527 | } 528 | if (currentValidPlayModes != null) { 529 | this.values.currentValidPlayModes = currentValidPlayModes 530 | for (const member of this.zpAccessory.members()) { 531 | member.sonosService.values.currentValidPlayModes = 532 | this.values.currentValidPlayModes 533 | } 534 | } 535 | if (repeat != null) { 536 | this.values.repeat = repeat 537 | this.values.shuffle = shuffle 538 | for (const member of this.zpAccessory.members()) { 539 | member.sonosService.values.repeat = this.values.repeat 540 | member.sonosService.values.shuffle = this.values.shuffle 541 | } 542 | } 543 | if (crossfade != null) { 544 | this.values.crossfade = crossfade 545 | for (const member of this.zpAccessory.members()) { 546 | member.sonosService.values.crossfade = this.values.crossfade 547 | } 548 | } 549 | if (uri != null) { 550 | this.values.uri = he.escape(uri) 551 | for (const member of this.zpAccessory.members()) { 552 | member.sonosService.values.uri = this.values.uri 553 | } 554 | } 555 | } 556 | 557 | handleMediaRendererGroupRenderingControlEvent (message) { 558 | if (message.groupVolume != null) { 559 | this.values.volume = message.groupVolume 560 | for (const member of this.zpAccessory.members()) { 561 | member.sonosService.values.volume = this.values.volume 562 | } 563 | } 564 | if (message.groupMute != null) { 565 | this.values.mute = !!message.groupMute 566 | for (const member of this.zpAccessory.members()) { 567 | member.sonosService.values.mute = this.values.mute 568 | } 569 | } 570 | } 571 | } 572 | 573 | ZpService.Sonos = Sonos 574 | -------------------------------------------------------------------------------- /lib/ZpPlatform.js: -------------------------------------------------------------------------------- 1 | // homebridge-zp/lib/ZpPlatform.js 2 | // Copyright © 2016-2025 Erik Baauw. All rights reserved. 3 | // 4 | // Homebridge plugin for Sonos ZonePlayer. 5 | 6 | import { once } from 'node:events' 7 | 8 | import { Bonjour } from 'homebridge-lib/Bonjour' 9 | import { OptionParser } from 'homebridge-lib/OptionParser' 10 | import { Platform } from 'homebridge-lib/Platform' 11 | import { ZpClient } from 'hb-zp-tools/ZpClient' 12 | import { ZpListener } from 'hb-zp-tools/ZpListener' 13 | 14 | import { ZpAccessory } from './ZpAccessory/index.js' 15 | import './ZpAccessory/Master.js' 16 | import { ZpHousehold } from './ZpHousehold.js' 17 | import { ZpService } from './ZpService/index.js' 18 | import './ZpService/Sonos.js' 19 | 20 | // Constructor for ZpPlatform. Called by homebridge on load time. 21 | class ZpPlatform extends Platform { 22 | constructor (log, configJson, homebridge) { 23 | super(log, configJson, homebridge) 24 | this.parseConfigJson(configJson) 25 | this.unInitialisedZpClients = 0 26 | this.households = {} // Households by household id. 27 | this.zpClients = {} // ZpClient by zoneplayer id. 28 | this.zpMasters = {} // ZpAccessory.Master delegates by zoneplayer id. 29 | this.zpSlaves = {} // ZpAccessory.Slave delegates by zonePlayer id. 30 | this.zpTvs = {} // ZpAccessory.Tv delegates by zonePlayer id. 31 | this.coordinators = {} // ZpAccessory.Master coordinator per household id. 32 | this.staleAccessories = {} 33 | 34 | this 35 | .on('accessoryRestored', this.accessoryRestored) 36 | .on('heartbeat', this.heartbeat) 37 | .on('shutdown', async () => { 38 | for (const id in this.zpClients) { 39 | try { 40 | await this.zpClients[id].close() 41 | } catch (error) { this.error(error) } 42 | } 43 | }) 44 | 45 | // Setup listener for mDNS announcements. 46 | if (this.config.mdns) { 47 | this.bonjour = new Bonjour() 48 | this.browser = this.bonjour.find({ type: 'sonos' }) 49 | this.browser.on('up', (message) => { this.handleMdnsMessage(message) }) 50 | } 51 | 52 | // Setup listener for UPnP announcements. 53 | this.upnpConfig({ class: 'urn:schemas-upnp-org:device:ZonePlayer:1' }) 54 | this 55 | .on('upnpDeviceAlive', this.handleUpnpMessage) 56 | .on('upnpDeviceFound', this.handleUpnpMessage) 57 | 58 | // Setup listener for zoneplayer events. 59 | this.listener = new ZpListener(this.config.port) 60 | this.listener 61 | .on('listening', (url) => { this.log('listening on %s', url) }) 62 | .on('close', (url) => { this.log('closed %s', url) }) 63 | .on('error', (error) => { this.warn(error) }) 64 | 65 | this.debug('config: %j', this.config) 66 | this.debug('SpeakerService: %j', this.config.SpeakerService.UUID) 67 | this.debug('VolumeCharacteristic: %j', this.config.VolumeCharacteristic.UUID) 68 | } 69 | 70 | // Parse config.json into this.config. 71 | parseConfigJson (configJson) { 72 | this.config = { 73 | maxFavourites: 96, 74 | mdns: true, 75 | port: 0, 76 | resetTimeout: 500, // milliseconds 77 | subscriptionTimeout: 30, // minutes 78 | timeout: 15, // seconds 79 | tvIdPrefix: 'TV', 80 | SpeakerService: this.Services.hap.Switch, 81 | VolumeCharacteristic: this.Characteristics.hap.Volume 82 | } 83 | const optionParser = new OptionParser(this.config, true) 84 | optionParser 85 | .on('userInputError', (message) => { 86 | this.warn('config.json: %s', message) 87 | }) 88 | .stringKey('platform') 89 | .stringKey('name') 90 | .boolKey('alarms') 91 | .boolKey('brightness') 92 | .boolKey('excludeAirPlay') 93 | .intKey('heartrate', 1, 60) 94 | .boolKey('leds') 95 | .intKey('maxFavourites', 16, 96) 96 | .boolKey('mdns') 97 | .intKey('port', 0, 65535) 98 | .intKey('resetTimeout', 1, 60) 99 | .enumKey('service') 100 | .enumKeyValue('service', 'fan', () => { 101 | this.config.SpeakerService = this.Services.hap.Fan 102 | this.config.VolumeCharacteristic = this.Characteristics.hap.RotationSpeed 103 | }) 104 | .enumKeyValue('service', 'light', () => { 105 | this.config.SpeakerService = this.Services.hap.Lightbulb 106 | this.config.VolumeCharacteristic = this.Characteristics.hap.Brightness 107 | }) 108 | .enumKeyValue('service', 'speaker', () => { 109 | this.config.SpeakerService = this.Services.hap.Speaker 110 | this.config.VolumeCharacteristic = this.Characteristics.hap.Volume 111 | }) 112 | .enumKeyValue('service', 'switch', () => { 113 | this.config.SpeakerService = this.Services.hap.Switch 114 | this.config.VolumeCharacteristic = this.Characteristics.hap.Volume 115 | }) 116 | .boolKey('speakers') 117 | .intKey('subscriptionTimeout', 1, 1440) // minutes 118 | .intKey('timeout', 1, 60) // seconds 119 | .boolKey('tv') 120 | .stringKey('tvIdPrefix', true) 121 | try { 122 | optionParser.parse(configJson) 123 | if (this.config.port <= 1024) { 124 | this.config.port = 0 125 | } 126 | if (this.config.brightness) { 127 | if (this.config.service === 'speaker' || this.config.service === 'switch') { 128 | this.config.VolumeCharacteristic = this.Characteristics.hap.Brightness 129 | } else { 130 | this.warn( 131 | 'config.json: ignoring "brightness" for "service": "%s"', 132 | this.config.service 133 | ) 134 | } 135 | } 136 | this.config.subscriptionTimeout *= 60 // minutes -> seconds 137 | } catch (error) { this.fatal(error) } 138 | } 139 | 140 | async import () { 141 | if (this.importDone) { 142 | return 143 | } 144 | this.importDone = true 145 | if (this.config.speakers && ZpService.Speaker == null) { 146 | await import('./ZpService/Speaker.js') 147 | } 148 | if (this.config.leds && ZpAccessory.Slave == null) { 149 | await import('./ZpAccessory/Slave.js') 150 | await import('./ZpService/Led.js') 151 | } 152 | if (this.config.alarms && ZpService.Alarm == null) { 153 | await import('./ZpService/Alarm.js') 154 | } 155 | if (this.config.tv && ZpAccessory.Tv == null) { 156 | await import('./ZpAccessory/Tv.js') 157 | await import('./ZpService/Tv.js') 158 | } 159 | } 160 | 161 | heartbeat (beat) { 162 | if (beat % 300 === 30) { 163 | if (Object.keys(this.households).length === 0) { 164 | this.warn('no zone players found') 165 | return 166 | } 167 | const now = new Date() 168 | for (const householdId in this.households) { 169 | const associatedZpClient = this.households[householdId].zpClient 170 | for (const id in associatedZpClient.zonePlayers) { 171 | try { 172 | const zpClient = this.zpClients[id] 173 | if (zpClient == null || zpClient.lastSeen === 'n/a') { 174 | continue 175 | } 176 | const delta = Math.round((now - new Date(zpClient.lastSeen)) / 1000) 177 | const log = (delta >= 600 ? this.log : this.debug).bind(this) 178 | log( 179 | '%s [%s]: lastSeen: %s, %js ago at %s, bootSeq: %j', zpClient.id, 180 | zpClient.zonePlayerName, zpClient.lastSeen, delta, 181 | zpClient.address, zpClient.bootSeq 182 | ) 183 | if (zpClient.delta >= 600) { 184 | this.lostZonePlayer(zpClient.id) 185 | } 186 | } catch (error) { 187 | this.error('%s: [%s]: %s', id, this.zpClients[id].address, error) 188 | } 189 | } 190 | } 191 | } 192 | } 193 | 194 | async accessoryRestored (className, version, id, name, context) { 195 | // this.log( 196 | // '%s [%s]: restoring %s v%s context: %j', 197 | // id, name, className, version, context 198 | // ) 199 | try { 200 | this.staleAccessories[id] = {} 201 | await this.createZpClient(id, context.address, context.household) 202 | } catch (error) { 203 | this.error(error) 204 | } 205 | // this.log( 206 | // '%s [%s]: %s v%s restore done', id, name, className, version 207 | // ) 208 | } 209 | 210 | async handleMdnsMessage (message) { 211 | try { 212 | const id = message.txt?.uuid 213 | const address = message.referer?.address 214 | const household = message.txt?.hhid 215 | const bootseq = parseInt(message.txt?.bootseq) 216 | if (id == null || address == null || household == null || bootseq == null) { 217 | this.debug('mdns: ignore message %j', message) 218 | return 219 | } 220 | this.debug('mdns: found %s at %s', id, address) 221 | const zpClient = await this.createZpClient(id, address, household) 222 | await zpClient.handleAliveMessage({ id, address, household, bootseq }) 223 | } catch (error) { this.warn('mdns: message %j: %s', message, error) } 224 | } 225 | 226 | async handleUpnpMessage (address, message) { 227 | try { 228 | const id = message.usn.split(':')[1] 229 | if (message.st != null) { 230 | this.debug('upnp: found %s at %s', id, address) 231 | } else { 232 | this.debug('upnp: %s is alive at %s', id, address) 233 | } 234 | const household = message['x-rincon-household'] 235 | const bootseq = parseInt(message['x-rincon-bootseq']) 236 | const zpClient = await this.createZpClient(id, address, household) 237 | await zpClient.handleAliveMessage({ id, address, household, bootseq }) 238 | } catch (error) { this.warn('upnp: message %j: %s', message, error) } 239 | } 240 | 241 | // Create new zpClient. 242 | async createZpClient (id, address, household) { 243 | await this.import() 244 | let zpClient = this.zpClients[id] 245 | if (zpClient != null && zpClient.address === address) { 246 | return zpClient 247 | } 248 | this.zpClients[id] = new ZpClient({ 249 | host: address, 250 | id, 251 | household, 252 | listener: this.listener, 253 | timeout: this.config.timeout 254 | }) 255 | zpClient = this.zpClients[id] 256 | zpClient 257 | .on('request', (request) => { 258 | this.debug( 259 | '%s [%s]: request %s: %s %s%s', zpClient.id, 260 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 261 | request.id, request.method, request.resource, 262 | request.action == null ? '' : ' ' + request.action 263 | ) 264 | }) 265 | .on('response', (response) => { 266 | this.debug( 267 | '%s [%s]: request %s: status %d %s', zpClient.id, 268 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 269 | response.request.id, response.statusCode, response.statusMessage 270 | ) 271 | }) 272 | .on('error', (error) => { 273 | if (error.request == null) { 274 | this.warn( 275 | '%s [%s]: %s', zpClient.id, 276 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 277 | error 278 | ) 279 | return 280 | } 281 | if (error.request.body == null) { 282 | this.log( 283 | '%s [%s]: request %d: %s %s', zpClient.id, 284 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 285 | error.request.id, error.request.method, error.request.resource 286 | ) 287 | } else { 288 | this.log( 289 | '%s [%s]: request %d: %s %s', zpClient.id, 290 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 291 | error.request.id, error.request.method, error.request.resource, 292 | error.request.action 293 | ) 294 | } 295 | this.warn( 296 | '%s [%s]: request %s: %s', zpClient.id, 297 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 298 | error.request.id, error 299 | ) 300 | }) 301 | .on('message', (message) => { 302 | const notify = message.device === 'ZonePlayer' 303 | ? message.service 304 | : message.device + '/' + message.service 305 | this.debug( 306 | '%s [%s]: notify %s/Event', zpClient.id, 307 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 308 | notify 309 | ) 310 | this.vdebug( 311 | '%s [%s]: notify %s/Event: %j', zpClient.id, 312 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 313 | notify, message.parsedBody 314 | ) 315 | this.vvdebug( 316 | '%s [%s]: notify %s/Event: ', zpClient.id, 317 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 318 | notify, message.body 319 | ) 320 | }) 321 | .on('rebooted', (oldBootSeq) => { 322 | this.warn( 323 | '%s [%s]: rebooted (%j -> %j)', zpClient.id, 324 | zpClient.zonePlayerName == null ? zpClient.address : zpClient.zonePlayerName, 325 | oldBootSeq, zpClient.bootSeq 326 | ) 327 | }) 328 | .on('addressChanged', (oldAddress) => { 329 | this.warn( 330 | '%s [%s]: now at %s', zpClient.id, 331 | zpClient.zonePlayerName == null ? oldAddress : zpClient.zonePlayerName, 332 | zpClient.address 333 | ) 334 | }) 335 | try { 336 | this.unInitialisedZpClients++ 337 | this.debug( 338 | '%s [%s]: probing (%d jobs)...', 339 | id, address, this.unInitialisedZpClients 340 | ) 341 | await zpClient.init() 342 | this.debug( 343 | '%s [%s]: %s: %s (%s) v%s, reached over local address %s', 344 | id, address, zpClient.zoneName, 345 | zpClient.modelName, zpClient.modelNumber, zpClient.version, 346 | zpClient.localAddress 347 | ) 348 | this.topologyChanged = true 349 | await zpClient.initTopology() 350 | await this.parseZones(zpClient) 351 | if (!zpClient.invisible) { 352 | let zpHousehold = this.households[zpClient.household] 353 | if (zpHousehold == null) { 354 | zpHousehold = new ZpHousehold(this, zpClient) 355 | this.households[zpClient.household] = zpHousehold 356 | } 357 | if ( 358 | zpHousehold.zpClient == null || ( 359 | zpClient.battery == null && 360 | zpHousehold.zpClient.battery != null 361 | ) 362 | ) { 363 | zpHousehold.zpClient = zpClient 364 | } 365 | } 366 | delete this.staleAccessories[id] 367 | } catch (error) { this.error(error) } 368 | this.unInitialisedZpClients-- 369 | this.debug( 370 | '%s [%s]: probing done (%d jobs remaining)', 371 | id, address, this.unInitialisedZpClients 372 | ) 373 | if (this.unInitialisedZpClients === 0 && this.topologyChanged) { 374 | this.topologyChanged = false 375 | this.logTopology() 376 | } 377 | return zpClient 378 | } 379 | 380 | async parseZones (zpClient) { 381 | const jobs = [] 382 | for (const id in zpClient.zonePlayers) { 383 | if (this.zpClients[id] == null) { 384 | const zonePlayer = zpClient.zonePlayers[id] 385 | if (zonePlayer == null) { 386 | continue 387 | } 388 | jobs.push( 389 | this.createZpClient( 390 | zonePlayer.id, zonePlayer.address, zpClient.household 391 | ).catch((error) => { this.error(error) }) 392 | ) 393 | } 394 | } 395 | for (const job of jobs) { 396 | await job 397 | } 398 | } 399 | 400 | lostZonePlayer (id, zoneName) { 401 | const master = this.zpMasters[id] 402 | if (master != null) { 403 | master.sonosService.values.on = false 404 | master.sonosService.values.statusFault = 405 | this.Characteristics.hap.StatusFault.GENERAL_FAULT 406 | if (this.config.speakers) { 407 | master.speakerService.values.on = false 408 | } 409 | } 410 | const slave = this.zpSlaves[id] 411 | if (slave != null) { 412 | slave.ledService.values.statusFault = 413 | this.Characteristics.hap.StatusFault.GENERAL_FAULT 414 | } 415 | } 416 | 417 | async logTopology () { 418 | for (const id in this.staleAccessories) { 419 | if (this.zpClients[id] != null) { 420 | this.zpClients[id].removeAllListeners() 421 | delete this.zpClients[id] 422 | } 423 | } 424 | if (Object.keys(this.households).length === 0) { 425 | this.warn('no zone players found') 426 | if (Object.keys(this.staleAccessories).length === 0) { 427 | this.debug('initialised') 428 | this.emit('initialised') 429 | } 430 | return 431 | } 432 | const jobs = [] 433 | this.log('found %d households', Object.keys(this.households).length) 434 | for (const householdId in this.households) { 435 | const zpHousehold = this.households[householdId] 436 | const associatedZpClient = zpHousehold.zpClient 437 | try { 438 | await zpHousehold.setAssociated(associatedZpClient) 439 | } catch (error) { this.error(error) } 440 | const zonePlayers = associatedZpClient.zonePlayers 441 | const zones = associatedZpClient.zones 442 | const nZones = Object.keys(zones).length 443 | this.log( 444 | '%s: found %d %s zone players in %d zones', householdId, 445 | Object.keys(zonePlayers).length, associatedZpClient.sonosOs, nZones 446 | ) 447 | let i = 0 448 | let j = 0 449 | let nZonePlayers 450 | for (const id in zonePlayers) { 451 | try { 452 | const zpClient = this.zpClients[id] 453 | if (zpClient == null) { 454 | this.warn('%s: zone player not found', id) 455 | continue 456 | } 457 | if (zpClient.role === 'master') { 458 | i++ 459 | j = 0 460 | let caps = '' 461 | if (zpClient.invisible) { 462 | // Sonos Boost or Sonos Bridge 463 | caps = ' (invisible)' 464 | } 465 | this.log( 466 | '%s %s%s', i < nZones ? '├─' : '└─', 467 | zpClient.zoneDisplayName, caps 468 | ) 469 | nZonePlayers = 1 470 | nZonePlayers += zpClient.slaves != null ? zpClient.slaves.length : 0 471 | // Fixme: handle missing satellites 472 | nZonePlayers += zpClient.satellites != null 473 | ? zpClient.satellites.length 474 | : 0 475 | } 476 | j++ 477 | let caps = zpClient.role 478 | caps += zpClient.airPlay ? ', airPlay' : '' 479 | caps += zpClient.audioIn ? ', audioIn' : '' 480 | caps += zpClient.tvIn ? ', tvIn' : '' 481 | this.log( 482 | '%s %s %s [%s]: %s (%s) (%s)', i < nZones ? '│ ' : ' ', 483 | j < nZonePlayers ? '├─' : '└─', zpClient.id, 484 | zpClient.zonePlayerName, zpClient.modelName, zpClient.modelNumber, caps 485 | ) 486 | } catch (error) { 487 | this.error('%s: [%s]: %s', id, this.zpClients[id].address, error) 488 | } 489 | } 490 | for (const id in zonePlayers) { 491 | try { 492 | const zpClient = this.zpClients[id] 493 | if (zpClient == null) { 494 | this.warn('%s: cannot expose - zone player not found', id) 495 | continue 496 | } 497 | const a = zpClient.modelName.split(' ') 498 | const params = { 499 | name: zpClient.zoneName, 500 | id: zpClient.id, 501 | zpClient, 502 | zpHousehold, 503 | address: zpClient.address, 504 | household: zpClient.household, 505 | manufacturer: a[0], 506 | model: a[1] + ' (' + zpClient.modelNumber + ')', 507 | firmware: zpClient.version, 508 | battery: zpClient.battery 509 | } 510 | if (zpClient.channel != null && zpClient.channel !== '') { 511 | params.name += ' ' + zpClient.channel 512 | } 513 | const expose = !(this.config.excludeAirPlay && zpClient.airPlay) && 514 | !zpClient.invisible 515 | if (zpClient.role === 'master') { 516 | if (expose && this.zpMasters[zpClient.id] == null) { 517 | this.zpMasters[zpClient.id] = new ZpAccessory.Master(this, params) 518 | jobs.push(once(this.zpMasters[zpClient.id], 'initialised')) 519 | } 520 | if (expose && this.config.tv && this.zpTvs[zpClient.id] == null) { 521 | const tvParams = Object.assign({ 522 | master: this.zpMasters[zpClient.id] 523 | }, params) 524 | delete tvParams.battery 525 | this.zpTvs[zpClient.id] = new ZpAccessory.Tv(this, tvParams) 526 | jobs.push(once(this.zpTvs[zpClient.id], 'initialised')) 527 | } 528 | } else { // zonePlayer.role !== 'master' 529 | if (this.config.leds && this.zpSlaves[zpClient.id] == null) { 530 | const slaveParams = Object.assign({ 531 | master: this.zpMasters[zpClient.zone] 532 | }, params) 533 | this.zpSlaves[zpClient.id] = new ZpAccessory.Slave(this, slaveParams) 534 | jobs.push(once(this.zpSlaves[zpClient.id], 'initialised')) 535 | } 536 | } 537 | } catch (error) { 538 | this.error('%s: [%s]: %s', id, this.zpClients[id].address, error) 539 | } 540 | } 541 | } 542 | for (const job of jobs) { 543 | await job 544 | } 545 | if (Object.keys(this.staleAccessories).length === 0) { 546 | this.debug('initialised') 547 | this.emit('initialised') 548 | } 549 | } 550 | 551 | // Return coordinator for group. 552 | groupCoordinator (groupId) { 553 | return this.zpMasters[groupId] 554 | } 555 | 556 | // Return array of members for group. 557 | groupMembers (groupId) { 558 | const members = [] 559 | for (const id in this.zpMasters) { 560 | const accessory = this.zpMasters[id] 561 | if (!accessory.isCoordinator && accessory.zpClient.zoneGroup === groupId) { 562 | members.push(accessory) 563 | } 564 | } 565 | return members 566 | } 567 | 568 | // Set coordinator zpAccessory as default coordinator 569 | setPlatformCoordinator (coordinator) { 570 | const household = coordinator.zpClient.household 571 | this.coordinators[household] = coordinator 572 | for (const id in this.zpMasters) { 573 | const accessory = this.zpMasters[id] 574 | const service = accessory.sonosService 575 | if (service != null && accessory.zpClient.household === household) { 576 | service.values.sonosCoordinator = accessory === coordinator 577 | service.values.platformCoordinatorId = coordinator.zpClient.id 578 | } 579 | } 580 | } 581 | } 582 | 583 | export { ZpPlatform } 584 | --------------------------------------------------------------------------------