]> git.basschouten.com Git - openhab-addons.git/blob
5a43d6f0ecf08a8be854c190203e7878ac88afca
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.yamahareceiver.internal.protocol.xml;
14
15 import static org.openhab.binding.yamahareceiver.internal.YamahaReceiverBindingConstants.*;
16 import static org.openhab.binding.yamahareceiver.internal.protocol.xml.XMLConstants.*;
17 import static org.openhab.binding.yamahareceiver.internal.protocol.xml.XMLConstants.Commands.*;
18 import static org.openhab.binding.yamahareceiver.internal.protocol.xml.XMLProtocolService.getZoneResponse;
19 import static org.openhab.binding.yamahareceiver.internal.protocol.xml.XMLUtils.*;
20
21 import java.io.IOException;
22 import java.lang.ref.WeakReference;
23 import java.util.function.Supplier;
24
25 import org.openhab.binding.yamahareceiver.internal.YamahaReceiverBindingConstants.Zone;
26 import org.openhab.binding.yamahareceiver.internal.config.YamahaZoneConfig;
27 import org.openhab.binding.yamahareceiver.internal.protocol.AbstractConnection;
28 import org.openhab.binding.yamahareceiver.internal.protocol.InputConverter;
29 import org.openhab.binding.yamahareceiver.internal.protocol.ReceivedMessageParseException;
30 import org.openhab.binding.yamahareceiver.internal.protocol.ZoneControl;
31 import org.openhab.binding.yamahareceiver.internal.state.DeviceInformationState;
32 import org.openhab.binding.yamahareceiver.internal.state.ZoneControlState;
33 import org.openhab.binding.yamahareceiver.internal.state.ZoneControlStateListener;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.w3c.dom.Node;
37
38 /**
39  * The zone protocol class is used to control one zone of a Yamaha receiver with HTTP/xml.
40  * No state will be saved in here, but in {@link ZoneControlState} instead.
41  *
42  * @author David Gräff - Refactored
43  * @author Eric Thill
44  * @author Ben Jones
45  * @author Tomasz Maruszak - Refactoring, input mapping fix, added Straight surround, volume DB fix and config
46  *         improvement.
47  */
48 public class ZoneControlXML implements ZoneControl {
49
50     protected Logger logger = LoggerFactory.getLogger(ZoneControlXML.class);
51
52     private static final String SURROUND_PROGRAM_STRAIGHT = "Straight";
53
54     private final ZoneControlStateListener observer;
55     private final Supplier<InputConverter> inputConverterSupplier;
56     private final WeakReference<AbstractConnection> comReference;
57     private final Zone zone;
58     private final YamahaZoneConfig zoneConfig;
59     private final DeviceDescriptorXML.ZoneDescriptor zoneDescriptor;
60
61     protected CommandTemplate power = new CommandTemplate("<Power_Control><Power>%s</Power></Power_Control>",
62             "Power_Control/Power");
63     protected CommandTemplate mute = new CommandTemplate("<Volume><Mute>%s</Mute></Volume>", "Volume/Mute");
64     protected CommandTemplate volume = new CommandTemplate(
65             "<Volume><Lvl><Val>%d</Val><Exp>1</Exp><Unit>dB</Unit></Lvl></Volume>", "Volume/Lvl/Val");
66     protected CommandTemplate inputSel = new CommandTemplate("<Input><Input_Sel>%s</Input_Sel></Input>",
67             "Input/Input_Sel");
68     protected String inputSelNamePath = "Input/Input_Sel_Item_Info/Title";
69     protected CommandTemplate surroundSelProgram = new CommandTemplate(
70             "<Surround><Program_Sel><Current><Sound_Program>%s</Sound_Program></Current></Program_Sel></Surround>",
71             "Surround/Program_Sel/Current/Sound_Program");
72     protected CommandTemplate surroundSelStraight = new CommandTemplate(
73             "<Surround><Program_Sel><Current><Straight>On</Straight></Current></Program_Sel></Surround>",
74             "Surround/Program_Sel/Current/Straight");
75     protected CommandTemplate sceneSel = new CommandTemplate("<Scene><Scene_Sel>%s</Scene_Sel></Scene>");
76     protected boolean sceneSelSupported = false;
77     protected CommandTemplate dialogueLevel = new CommandTemplate(
78             "<Sound_Video><Dialogue_Adjust><Dialogue_Lvl>%d</Dialogue_Lvl></Dialogue_Adjust></Sound_Video>",
79             "Sound_Video/Dialogue_Adjust/Dialogue_Lvl");
80     protected boolean dialogueLevelSupported = false;
81
82     public ZoneControlXML(AbstractConnection con, Zone zone, YamahaZoneConfig zoneSettings,
83             ZoneControlStateListener observer, DeviceInformationState deviceInformationState,
84             Supplier<InputConverter> inputConverterSupplier) {
85         this.comReference = new WeakReference<>(con);
86         this.zone = zone;
87         this.zoneConfig = zoneSettings;
88         this.zoneDescriptor = DeviceDescriptorXML.getAttached(deviceInformationState).zones.getOrDefault(zone, null);
89         this.observer = observer;
90         this.inputConverterSupplier = inputConverterSupplier;
91
92         this.applyModelVariations();
93     }
94
95     /**
96      * Apply command changes to ensure compatibility with all supported models
97      */
98     protected void applyModelVariations() {
99         if (zoneDescriptor == null) {
100             logger.trace("Zone {} - descriptor not available", getZone());
101             return;
102         }
103
104         logger.trace("Zone {} - compatibility detection", getZone());
105
106         // Note: Detection if scene is supported
107         sceneSelSupported = zoneDescriptor.hasCommandEnding("Scene,Scene_Sel", () -> logger
108                 .debug("Zone {} - the {} channel is not supported on your model", getZone(), CHANNEL_SCENE));
109
110         // Note: Detection if dialogue level is supported
111         dialogueLevelSupported = zoneDescriptor.hasAnyCommandEnding("Sound_Video,Dialogue_Adjust,Dialogue_Lvl",
112                 "Sound_Video,Dialogue_Adjust,Dialogue_Lift");
113         if (zoneDescriptor.hasCommandEnding("Sound_Video,Dialogue_Adjust,Dialogue_Lift")) {
114             dialogueLevel = dialogueLevel.replace("Dialogue_Lvl", "Dialogue_Lift");
115             logger.debug("Zone {} - adjusting command to: {}", getZone(), dialogueLevel);
116         }
117         if (!dialogueLevelSupported) {
118             logger.debug("Zone {} - the {} channel is not supported on your model", getZone(), CHANNEL_DIALOGUE_LEVEL);
119         }
120
121         // Note: Detection for RX-V3900, which uses <Vol> instead of <Volume>
122         if (zoneDescriptor.hasCommandEnding("Vol,Lvl")) {
123             volume = volume.replace("Volume", "Vol");
124             logger.debug("Zone {} - adjusting command to: {}", getZone(), volume);
125         }
126         if (zoneDescriptor.hasCommandEnding("Vol,Mute")) {
127             mute = mute.replace("Volume", "Vol");
128             logger.debug("Zone {} - adjusting command to: {}", getZone(), mute);
129         }
130
131         try {
132             // Note: Detection for RX-V3900, which has a different XML node for surround program
133             Node basicStatusNode = getZoneResponse(comReference.get(), getZone(), ZONE_BASIC_STATUS_CMD,
134                     ZONE_BASIC_STATUS_PATH);
135             String surroundProgram = getNodeContentOrEmpty(basicStatusNode, "Surr/Pgm_Sel/Pgm");
136
137             if (!surroundProgram.isEmpty()) {
138                 surroundSelProgram = new CommandTemplate(
139                         "<Surr><Pgm_Sel><Straight>Off</Straight><Pgm>%s</Pgm></Pgm_Sel></Surr>", "Surr/Pgm_Sel/Pgm");
140                 logger.debug("Zone {} - adjusting command to: {}", getZone(), surroundSelProgram);
141
142                 surroundSelStraight = new CommandTemplate("<Surr><Pgm_Sel><Straight>On</Straight></Pgm_Sel></Surr>",
143                         "Surr/Pgm_Sel/Straight");
144                 logger.debug("Zone {} - adjusting command to: {}", getZone(), surroundSelStraight);
145             }
146
147         } catch (ReceivedMessageParseException | IOException e) {
148             logger.debug("Could not perform feature detection for RX-V3900");
149         }
150     }
151
152     protected void sendCommand(String message) throws IOException {
153         comReference.get().send(XMLUtils.wrZone(zone, message));
154     }
155
156     /**
157      * Return the zone
158      */
159     public Zone getZone() {
160         return zone;
161     }
162
163     @Override
164     public void setPower(boolean on) throws IOException, ReceivedMessageParseException {
165         String cmd = power.apply(on ? ON : POWER_STANDBY);
166         sendCommand(cmd);
167         update();
168     }
169
170     @Override
171     public void setMute(boolean on) throws IOException, ReceivedMessageParseException {
172         String cmd = this.mute.apply(on ? ON : OFF);
173         sendCommand(cmd);
174         update();
175     }
176
177     /**
178      * Sets the absolute volume in decibel.
179      *
180      * @param volume Absolute value in decibel ([-80,+12]).
181      * @throws IOException
182      */
183     @Override
184     public void setVolumeDB(float volume) throws IOException, ReceivedMessageParseException {
185         if (volume < zoneConfig.getVolumeDbMin()) {
186             volume = zoneConfig.getVolumeDbMin();
187         }
188         if (volume > zoneConfig.getVolumeDbMax()) {
189             volume = zoneConfig.getVolumeDbMax();
190         }
191
192         // Yamaha accepts only integer values with .0 or .5 at the end only (-20.5dB, -20.0dB) - at least on RX-S601D.
193         // The order matters here. We want to cast to integer first and then scale by 10.
194         // Effectively we're only allowing dB values with .0 at the end.
195         int vol = (int) volume * 10;
196         sendCommand(this.volume.apply(vol));
197         update();
198     }
199
200     /**
201      * Sets the volume in percent
202      *
203      * @param volume
204      * @throws IOException
205      */
206     @Override
207     public void setVolume(float volume) throws IOException, ReceivedMessageParseException {
208         if (volume < 0) {
209             volume = 0;
210         }
211         if (volume > 100) {
212             volume = 100;
213         }
214         // Compute value in db
215         setVolumeDB(zoneConfig.getVolumeDb(volume));
216     }
217
218     /**
219      * Increase or decrease the volume by the given percentage.
220      *
221      * @param percent
222      * @throws IOException
223      */
224     @Override
225     public void setVolumeRelative(ZoneControlState state, float percent)
226             throws IOException, ReceivedMessageParseException {
227         setVolume(zoneConfig.getVolumePercentage(state.volumeDB) + percent);
228     }
229
230     @Override
231     public void setInput(String name) throws IOException, ReceivedMessageParseException {
232         name = inputConverterSupplier.get().toCommandName(name);
233         String cmd = inputSel.apply(name);
234         sendCommand(cmd);
235         update();
236     }
237
238     @Override
239     public void setSurroundProgram(String name) throws IOException, ReceivedMessageParseException {
240         String cmd = name.equalsIgnoreCase(SURROUND_PROGRAM_STRAIGHT) ? surroundSelStraight.apply()
241                 : surroundSelProgram.apply(name);
242
243         sendCommand(cmd);
244         update();
245     }
246
247     @Override
248     public void setDialogueLevel(int level) throws IOException, ReceivedMessageParseException {
249         if (!dialogueLevelSupported) {
250             return;
251         }
252         sendCommand(dialogueLevel.apply(level));
253         update();
254     }
255
256     @Override
257     public void setScene(String scene) throws IOException, ReceivedMessageParseException {
258         if (!sceneSelSupported) {
259             return;
260         }
261         sendCommand(sceneSel.apply(scene));
262         update();
263     }
264
265     @Override
266     public void update() throws IOException, ReceivedMessageParseException {
267         if (observer == null) {
268             return;
269         }
270
271         Node statusNode = getZoneResponse(comReference.get(), zone, ZONE_BASIC_STATUS_CMD, ZONE_BASIC_STATUS_PATH);
272
273         String value;
274
275         ZoneControlState state = new ZoneControlState();
276
277         value = getNodeContentOrEmpty(statusNode, power.getPath());
278         state.power = ON.equalsIgnoreCase(value);
279
280         value = getNodeContentOrEmpty(statusNode, mute.getPath());
281         state.mute = ON.equalsIgnoreCase(value);
282
283         // The value comes in dB x 10, on AVR it says -30.5dB, the values comes as -305
284         value = getNodeContentOrDefault(statusNode, volume.getPath(), String.valueOf(zoneConfig.getVolumeDbMin()));
285         state.volumeDB = Float.parseFloat(value) * .1f; // in dB
286
287         value = getNodeContentOrEmpty(statusNode, inputSel.getPath());
288         state.inputID = inputConverterSupplier.get().fromStateName(value);
289         if (state.inputID == null || state.inputID.isBlank()) {
290             throw new ReceivedMessageParseException("Expected inputID. Failed to read Input/Input_Sel");
291         }
292
293         // Some receivers may use Src_Name instead?
294         value = getNodeContentOrEmpty(statusNode, inputSelNamePath);
295         state.inputName = value;
296
297         value = getNodeContentOrEmpty(statusNode, surroundSelStraight.getPath());
298         boolean straightOn = ON.equalsIgnoreCase(value);
299
300         value = getNodeContentOrEmpty(statusNode, surroundSelProgram.getPath());
301         // Surround is either in straight mode or sound program
302         state.surroundProgram = straightOn ? SURROUND_PROGRAM_STRAIGHT : value;
303
304         value = getNodeContentOrDefault(statusNode, dialogueLevel.getPath(), "0");
305         state.dialogueLevel = Integer.parseInt(value);
306
307         logger.debug("Zone {} state - power: {}, mute: {}, volumeDB: {}, input: {}, surroundProgram: {}", getZone(),
308                 state.power, state.mute, state.volumeDB, state.inputID, state.surroundProgram);
309
310         observer.zoneStateChanged(state);
311     }
312 }