File: roonapi.py

package info (click to toggle)
pyroon 0.1.6-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 372 kB
  • sloc: python: 1,660; sh: 135; makefile: 4
file content (1113 lines) | stat: -rw-r--r-- 40,989 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
from __future__ import unicode_literals

import threading
import time
import csv

from .constants import (
    LOGGER,
    PAGE_SIZE,
    SERVICE_BROWSE,
    SERVICE_REGISTRY,
    SERVICE_TRANSPORT,
    CONTROL_VOLUME,
)
from .roonapisocket import RoonApiWebSocket


class RoonApiException(Exception):
    """An exception to raise when the roon api can't initialise or work.

    Can be called with a  string to get a default message, e.g.

        RoonApiException("There is a problem.")
    """

    def __init__(self, message=None):
        """Pass on the reason string."""
        if message is None:
            msg = "No exception mesage provided."
        else:
            msg = message
        super().__init__(msg)


def split_media_path(path):
    """Split a path (eg path/to/media) into a list for use by play_media."""

    return [*csv.reader([path], delimiter="/")][0]


class RoonApi:  # pylint: disable=too-many-instance-attributes, too-many-lines
    """Class to handle talking to the roon server."""

    _roonsocket = None
    _host = None
    _core_id = None
    _core_name = None

    _port = None
    _token = None
    _exit = False
    _zones = {}
    _outputs = {}
    _state_callbacks = []
    ready = False

    _volume_controls_request_id = None
    _volume_controls = {}

    @property
    def token(self):
        """Return the authentication key from the registration with Roon."""
        return self._token

    @property
    def host(self):
        """Return the roon host."""
        return self._host

    @property
    def core_id(self):
        """Return the roon host."""
        return self._core_id

    @property
    def core_name(self):
        """Return the roon core name."""
        return self._core_name

    @property
    def zones(self):
        """Return All zones as a dict."""
        return self._zones

    @property
    def outputs(self):
        """All outputs, returned as dict."""
        return self._outputs

    def zone_by_name(self, zone_name):
        """Get zone details by name."""
        for zone in self.zones.values():
            if zone["display_name"] == zone_name:
                return zone
        return None

    def output_by_name(self, output_name):
        """Get the output details from the name."""
        for output in self.outputs.values():
            if output["display_name"] == output_name:
                return output
        return None

    def zone_by_output_id(self, output_id):
        """Get the zone details by output id."""
        for zone in self.zones.values():
            for output in zone["outputs"]:
                if output["output_id"] == output_id:
                    return zone
        return None

    def zone_by_output_name(self, output_name):
        """
        Get the zone details by an output name.

        params:
            output_name: the name of the output
        returns: full zone details (dict)
        """

        for zone in self.zones.values():
            for output in zone["outputs"]:
                if output["display_name"] == output_name:
                    return zone
        return None

    def is_grouped(self, output_id):
        """
        Whether this output is part of a group.

        params:
            output_id: the id of the output
        returns: boolean whether this outout is grouped
        """

        try:
            output = self.outputs[output_id]
            zone_id = output["zone_id"]
            is_grouped = len(self.zones[zone_id]["outputs"]) > 1
        except KeyError:
            is_grouped = False
        return is_grouped

    def is_group_main(self, output_id):
        """
        Whether this output is the the main output of a group.

        params:
            output_id: the id of the output
        returns: boolean whether this output is the main output of a group
        """

        if not self.is_grouped(output_id):
            return False

        output = self.outputs[output_id]
        zone_id = output["zone_id"]
        is_group_main = self.zones[zone_id]["outputs"][0]["output_id"] == output_id
        return is_group_main

    def grouped_zone_names(self, output_id):
        """
        Get the names of the group players.

        params:
            output_id: the id of the output
        returns: The names of the grouped zones. The first is the main output.
        """

        if not self.is_grouped(output_id):
            return []
        output = self.outputs[output_id]
        zone_id = output["zone_id"]
        grouped_zone_names = [o["display_name"] for o in self.zones[zone_id]["outputs"]]
        return grouped_zone_names

    def get_image(self, image_key, scale="fit", width=500, height=500):
        """
        Get the image url for the specified image key.

        params:
            image_key: the key for the image as retrieved in other api calls
            scale: optional (value of fit, fill or stretch)
            width: the width of the image (required if scale is specified)
            height: the height of the image (required if scale is set)
        returns: string with the full url to the image
        """
        return "http://%s:%s/api/image/%s?scale=%s&width=%s&height=%s" % (
            self._host,
            self._port,
            image_key,
            scale,
            width,
            height,
        )

    def playback_control(self, zone_or_output_id, control="play"):
        """
        Send player command to the specified zone.

        params:
            zone_or_output_id: the id of the zone or output
            control:
                 * "play" - If paused or stopped, start playback
                 * "pause" - If playing or loading, pause playback
                 * "playpause" - If paused or stopped, start playback.
                                 If playing or loading, pause playback.
                 * "stop" - Stop playback and release the audio device immediately
                 * "previous" - Go to the start of the current track, or to the previous track
                 * "next" - Advance to the next track
        """
        data = {"zone_or_output_id": zone_or_output_id, "control": control}
        return self._request(SERVICE_TRANSPORT + "/control", data)

    def pause_all(self):
        """Pause all zones."""
        return self._request(SERVICE_TRANSPORT + "/pause_all")

    def standby(self, output_id, control_key=None):
        """
        Send standby command to the specified output.

        params:
            output_id: the id of the output to put in standby
            control_key: The control_key that identifies the source_control
                         that is to be put into standby. If omitted,
                         then all source controls on this output that support
                         standby will be put into standby.
        """
        data = {"output_id": output_id, "control_key": control_key}
        return self._request(SERVICE_TRANSPORT + "/standby", data)

    def convenience_switch(self, output_id, control_key=None):
        """
        Switch (convenience) an output, take it out of standby if needed.

        params:
            output_id: the id of the output that should be convenience-switched.
            control_key: The control_key that identifies the source_control that is to be switched.
                         If omitted, then all controls on this output will be convenience switched.
        """
        data = {"output_id": output_id, "control_key": control_key}
        return self._request(SERVICE_TRANSPORT + "/convenience_switch", data)

    def mute(self, output_id, mute=True):
        """
        Mute/unmute an output.

        params:
            output_id: the id of the output that should be muted/unmuted
            mute: bool if the output should be muted. Will unmute if set to False
        """
        how = "mute" if mute else "unmute"
        data = {"output_id": output_id, "how": how}
        return self._request(SERVICE_TRANSPORT + "/mute", data)

    def set_volume_percent(self, output_id, absolute_value):
        """
        Set the volume of an output to a 0-100 value.

        Roon endpoints have a few different volume scales - this method scales from 0-100
        to what the endpoint needs.

        params:
            output_id: the id of the output
        """
        volume_data = self._outputs[output_id].get("volume")

        if volume_data is None:
            LOGGER.info("This endpoint has fixed volume.")
            return None

        volume_max = volume_data["max"]
        volume_min = volume_data["min"]
        volume_step = volume_data["step"]
        volume_range = volume_max - volume_min
        volume_percentage_factor = volume_range / 100
        percentage_volume = volume_min + absolute_value * volume_percentage_factor

        # If the endpoint steps are integer - then round the scaled result
        if int(volume_step) == volume_step:
            percentage_volume = int(round(percentage_volume))

        return self.change_volume_raw(output_id, percentage_volume)

    def change_volume_percent(self, output_id, relative_value):
        """

        Change the volume of an output by a relative amount.

        Roon endpoints have a few different volume scales - this method scales from 0-100
        to what the endpoint needs.

        params:
            output_id: the id of the output
            relative_value: How much to increase or decrease the volume
        """
        volume_data = self._outputs[output_id].get("volume")

        if volume_data is None:
            LOGGER.info("This endpoint has fixed volume.")
            return None

        volume_max = volume_data["max"]
        volume_min = volume_data["min"]
        volume_range = volume_max - volume_min
        volume_percentage_factor = volume_range / 100

        volume_percentage_change = int(round(relative_value * volume_percentage_factor))
        return self.change_volume_raw(output_id, volume_percentage_change, "relative")

    def get_volume_percent(self, output_id):
        """

        Get the volume of an output.

        Roon endpoints have a few different volumee scales - this method scales from 0-100
        to what the endpoint needs.

        params:
            output_id: the id of the output
            relative_value: How much to increase or decrease the volume
        """

        volume_data = self._outputs[output_id].get("volume")

        if volume_data is None:
            LOGGER.info("This endpoint has fixed volume.")
            return None

        volume_max = volume_data["max"]
        volume_min = volume_data["min"]

        volume_range = volume_max - volume_min
        volume_percentage_factor = volume_range / 100

        raw_level = float(volume_data["value"])
        percent_level = (raw_level - volume_min) / volume_percentage_factor
        return int(round(percent_level))

    def change_volume_raw(self, output_id, value, method="absolute"):
        """
        Change the volume of an output.

        Roon endpoint have a few different scales - this endpoints just used the native scale.
        The percent calls may be easier to use

        params:
            output_id: the id of the output
            value: The new volume value, or the increment value or step
            method: How to interpret the volume ('absolute'|'relative'|'relative_step')
        """
        if "volume" not in self._outputs[output_id]:
            LOGGER.info("This endpoint has fixed volume.")
            return None
        # Home assistant was catching this - so catch here
        # to try and diagnose what needs to be checked.
        try:
            data = {"output_id": output_id, "how": method, "value": value}
            return self._request(SERVICE_TRANSPORT + "/change_volume", data)
        except Exception as exc:  # pylint: disable=broad-except
            LOGGER.error("set_volume_level failed for entity %s.", str(exc))
            return None

    def seek(self, zone_or_output_id, seconds, method="absolute"):
        """
        Seek to a time position within the now playing media.

        params:
            zone_or_output_id: the id of the zone or output
            seconds: The target seek position
            method: How to interpret the target seek position ('absolute'|'relative')
        """
        data = {
            "zone_or_output_id": zone_or_output_id,
            "how": method,
            "seconds": seconds,
        }
        return self._request(SERVICE_TRANSPORT + "/seek", data)

    def shuffle(self, zone_or_output_id, shuffle=True):
        """
        Enable or disable playing in random order.

        params:
            zone_or_output_id: the id of the output or zone
            shuffle: bool if shuffle should be enabled. False will disable shuffle
        """
        data = {"zone_or_output_id": zone_or_output_id, "shuffle": shuffle}
        return self._request(SERVICE_TRANSPORT + "/change_settings", data)

    def repeat(self, zone_or_output_id, repeat="loop"):
        """
        Enable/disable playing in a loop.

        params:
            zone_or_output_id: the id of the output or zone
            repeat: "loop", "loop_one", "disabled"

        For backward compatability repeat can also be boolean with true meaning "loop" and false "disabled"
        """
        if repeat in ("loop", "loop_one", "disabled"):
            loop = repeat
        else:
            loop = "loop" if repeat else "disabled"

        data = {"zone_or_output_id": zone_or_output_id, "loop": loop}
        return self._request(SERVICE_TRANSPORT + "/change_settings", data)

    def transfer_zone(self, from_zone_or_output_id, to_zone_or_output_id):
        """
        Transfer the current queue from one zone to another.

        params:
            from_zone_or_output_id - The source zone or output
            to_zone_or_output_id - The destination zone or output
        """
        data = {
            "from_zone_or_output_id": from_zone_or_output_id,
            "to_zone_or_output_id": to_zone_or_output_id,
        }
        return self._request(SERVICE_TRANSPORT + "/transfer_zone", data)

    def group_outputs(self, output_ids):
        """
        Create a group of synchronized audio outputs.

        params:
            output_ids - The outputs to group. The first output's zone's queue is preserved.
        """
        data = {"output_ids": output_ids}
        return self._request(SERVICE_TRANSPORT + "/group_outputs", data)

    def ungroup_outputs(self, output_ids):
        """
        Ungroup outputs previous grouped.

        params:
            output_ids - The outputs to ungroup.
        """
        data = {"output_ids": output_ids}
        return self._request(SERVICE_TRANSPORT + "/ungroup_outputs", data)

    def register_state_callback(self, callback, event_filter=None, id_filter=None):
        """
        Register a callback to be informed about changes to zones or outputs.

        params:
            callback: method to be called when state changes occur, it will be passed an event param as string and a list of changed objects
                      callback will be called with params:
                      - event: string with name of the event ("zones_changed", "zones_seek_changed", "outputs_changed")
                      - a list with the zone or output id's that changed
            event_filter: only callback if the event is in this list
            id_filter: one or more zone or output id's or names to filter on (list or string)
        """
        if not event_filter:
            event_filter = []
        elif not isinstance(event_filter, list):
            event_filter = [event_filter]
        if not id_filter:
            id_filter = []
        elif not isinstance(id_filter, list):
            id_filter = [id_filter]
        self._state_callbacks.append((callback, event_filter, id_filter))

    def register_queue_callback(self, callback, zone_or_output_id=""):
        """
        Subscribe to queue change events.

        callback: function which will be called with the updated data (provided as dict object
        zone_or_output_id: If provided, only listen for updates for this zone or output
        """
        if zone_or_output_id:
            opt_data = {"zone_or_output_id": zone_or_output_id}
        else:
            opt_data = None
        self._roonsocket.subscribe(SERVICE_TRANSPORT, "queue", callback, opt_data)

    def browse_browse(self, opts):
        """
        Complex browse call on the roon api.

        reference: https://github.com/RoonLabs/node-roon-api-browse/blob/master/lib.js
        """
        return self._request(SERVICE_BROWSE + "/browse", opts)

    def browse_load(self, opts):
        """
        Complex browse call on the roon api.

        reference: https://github.com/RoonLabs/node-roon-api-browse/blob/master/lib.js
        """
        return self._request(SERVICE_BROWSE + "/load", opts)

    def list_media(self, zone_or_output_id, path):
        """
        List the media specified.

        params:
            zone_or_output_id: where to play the media
            path: a list allowing roon to find the media
                  eg ["Library", "Artists", "Neil Young", "Harvest"] or ["My Live Radio", "BBC Radio 4"]
        """

        opts = {
            "zone_or_output_id": zone_or_output_id,
            "hierarchy": "browse",
            "count": PAGE_SIZE,
            "pop_all": True,
        }

        total_count = self.browse_browse(opts)["list"]["count"]
        del opts["pop_all"]

        load_opts = {
            "zone_or_output_id": zone_or_output_id,
            "hierarchy": "browse",
            "count": PAGE_SIZE,
            "offset": 0,
        }
        items = []
        searchterm = path[-1]
        path.pop()
        for element in path:
            load_opts["offset"] = 0
            found = None
            searched = 0

            LOGGER.debug("Looking for %s", element)
            while searched < total_count and found is None:
                items = self.browse_load(load_opts)["items"]

                for item in items:
                    searched += 1
                    if item["title"] == element:
                        found = item
                        break

                load_opts["offset"] += PAGE_SIZE
            if searched >= total_count and found is None:
                LOGGER.debug(
                    "Could not find media path element '%s' in %s",
                    element,
                    [item["title"] for item in items],
                )
                return None

            opts["item_key"] = found["item_key"]
            load_opts["item_key"] = found["item_key"]

            total_count = self.browse_browse(opts)["list"]["count"]

            load_opts["offset"] = 0
            items = self.browse_load(load_opts)["items"]

        LOGGER.debug("Searching for %s", searchterm)
        load_opts["offset"] = 0
        searched = 0
        matched = []
        while searched < total_count:
            items = self.browse_load(load_opts)["items"]

            if searchterm == "__all__":
                for item in items:
                    searched += 1
                    matched.append(item["title"])
            else:
                for item in items:
                    searched += 1
                    if searchterm in item["title"]:
                        matched.append(item["title"])

            load_opts["offset"] += PAGE_SIZE

        return matched

    def play_media(self, zone_or_output_id, path, action=None, report_error=True):
        # pylint: disable=too-many-locals,too-many-branches,too-many-return-statements,too-many-statements
        """
        Play the media specified.

        params:
            zone_or_output_id: where to play the media
            path: a list allowing roon to find the media
                  eg ["Library", "Artists", "Neil Young", "Harvest"] or ["My Live Radio", "BBC Radio 4"]
            action: the roon action to take to play the media - leave blank to choose the roon default
                    eg "Play Now", "Queue" or "Start Radio"
        """

        opts = {
            "zone_or_output_id": zone_or_output_id,
            "hierarchy": "browse",
            "count": PAGE_SIZE,
            "pop_all": True,
        }

        total_count = self.browse_browse(opts)["list"]["count"]
        del opts["pop_all"]

        load_opts = {
            "zone_or_output_id": zone_or_output_id,
            "hierarchy": "browse",
            "count": PAGE_SIZE,
            "offset": 0,
        }
        items = []
        for element in path:
            load_opts["offset"] = 0
            found = None
            searched = 0

            LOGGER.debug("Looking for %s", element)
            while searched < total_count and found is None:
                items = self.browse_load(load_opts)["items"]

                for item in items:
                    searched += 1
                    if item["title"] == element:
                        found = item
                        break

                load_opts["offset"] += PAGE_SIZE
            if searched >= total_count and found is None:
                if report_error:
                    LOGGER.error(
                        "Could not find media path element '%s' in %s",
                        element,
                        [item["title"] for item in items],
                    )
                return None

            opts["item_key"] = found["item_key"]
            load_opts["item_key"] = found["item_key"]

            try:
                total_count = self.browse_browse(opts)["list"]["count"]
            except TypeError:
                LOGGER.error("Exception trying to play media")
                return None

            load_opts["offset"] = 0
            items = self.browse_load(load_opts)["items"]

            if found["hint"] == "action":
                # Loading item we found already started playing
                return True

        # First item shoule be the action/action_list for playing this item (eg Play Genre, Play Artist, Play Album)
        if items[0].get("hint") not in ["action_list", "action"]:
            LOGGER.error(
                "Found media does not have playable action_list hint='%s' '%s'",
                items[0].get("hint"),
                [item["title"] for item in items],
            )
            return False

        play_header = items[0]["title"]
        if items[0].get("hint") == "action_list":
            opts["item_key"] = items[0]["item_key"]
            load_opts["item_key"] = items[0]["item_key"]
            self.browse_browse(opts)
            items = self.browse_load(load_opts)["items"]

        # We should now have play actions (eg Play Now, Add Next, Queue action, Start Radio)
        # So pick the one to use - the default is the first one
        if action is None:
            take_action = items[0]
        else:
            found_actions = [item for item in items if item["title"] == action]
            if len(found_actions) == 0:
                LOGGER.error(
                    "Could not find play action '%s' in %s",
                    action,
                    [item["title"] for item in items],
                )
                return False
            take_action = found_actions[0]

            try:
                if take_action["hint"] != "action":
                    LOGGER.error(
                        "Found media does not have playable action %s - %s",
                        take_action["title"],
                        take_action["hint"],
                    )
                    return False
            except KeyError:
                # I think this is a roon API error -
                # when playing a tag - there should be a hint here!
                # so for now just ignore - and hope it's OK
                pass

        opts["item_key"] = take_action["item_key"]
        load_opts["item_key"] = take_action["item_key"]
        LOGGER.info("Play action was '%s' / '%s'", play_header, take_action["title"])
        self.browse_browse(opts)
        return True

    # pylint: disable=too-many-return-statements
    def play_id(self, zone_or_output_id, media_id):
        """Play based on the media_id from the browse api."""
        opts = {
            "zone_or_output_id": zone_or_output_id,
            "item_key": media_id,
            "hierarchy": "browse",
        }
        header_result = self.browse_browse(opts)
        # For Radio the above load starts play - so catch this and return
        try:
            if header_result["list"]["level"] == 0:
                LOGGER.info("Initial load started playback")
                return True
        except (NameError, KeyError, TypeError):
            LOGGER.error("Could not play id:%s, result: %s", media_id, header_result)
            return False

        if header_result is None:
            LOGGER.error(
                "Playback requested of unsupported id: %s",
                media_id,
            )
            return False

        result = self.browse_load(opts)

        first_item = result["items"][0]
        hint = first_item["hint"]
        if not (hint in ["action", "action_list"]):
            LOGGER.error(
                "Playback requested but item is a list, not a playable action or action_list id: %s",
                media_id,
            )
            return False

        if hint == "action_list":
            opts["item_key"] = first_item["item_key"]
            result = self.browse_browse(opts)
            if result is None:
                LOGGER.error(
                    "Playback requested of unsupported id: %s",
                    media_id,
                )
                return False
            result = self.browse_load(opts)
            first_item = result["items"][0]
            hint = first_item["hint"]

        if hint != "action":
            LOGGER.error(
                "Playback requested but item does not have a playable action id: %s, %s",
                media_id,
                header_result,
            )
            return False

        play_action = result["items"][0]
        hint = play_action["hint"]
        LOGGER.info("'%s' for '%s')", play_action["title"], header_result)
        opts["item_key"] = play_action["item_key"]
        self.browse_browse(opts)
        if result is None:
            LOGGER.error(
                "Playback requested of unsupported id: %s",
                media_id,
            )
            return False

        return True

    # private methods
    # pylint: disable=too-many-arguments
    def __init__(
        self,
        appinfo,
        token,
        host,
        port,
        blocking_init=True,
    ):
        """
        Set up the connection with Roon.

        appinfo: a dict of the required information about the app that should be connected to the api
        token: used for presistant storage of the auth token, will be set to token attribute if retrieved. You should handle saving of the key yourself
        host: the ip or hostname of the Roon server,
        port: the http port of the Roon websockets api.
        blocking_init: By default the init will halt untill the socket is connected and the app is authenticated,
                       if you set bool to False the init will continue but you will only receive data once the connection is fully initialized.
                       The latter is preferred if you're (only) using the callbacks
        """
        self._appinfo = appinfo
        self._token = token

        if not appinfo or not isinstance(appinfo, dict):
            raise RoonApiException("Appinfo missing or in incorrect format")

        if not (host and port):
            raise RoonApiException("Host and port of the roon core must be specified!")

        self._server_setup(host, port)

        # block untill we're ready
        if blocking_init:
            while not self.ready and not self._exit:
                time.sleep(0.05)

        # fill zones and outputs dicts one time so the data is available right away
        # This might not be needed as the on change callback may have already done this
        if self.token:
            if not self._zones:
                self._zones = self._get_zones()
            if not self._outputs:
                self._outputs = self._get_outputs()

        # start socket watcher
        thread_id = threading.Thread(target=self._socket_watcher)
        thread_id.daemon = True
        thread_id.start()
        LOGGER.debug("Finished Roonapi Init")

    # pylint: disable=redefined-builtin
    def __exit__(self, type, value, exc_tb):
        """Stop socket on exit."""
        self.stop()

    def __enter__(self):
        """Just return self on entry."""
        return self

    def stop(self):
        """Stop socket."""
        self._exit = True
        if self._roonsocket:
            self._roonsocket.stop()

    def _server_setup(self, host, port):
        """Open the roon socket connection to the roon server on the network."""
        LOGGER.debug("Connecting to Roon server %s:%s" % (host, port))
        ws_address = "ws://%s:%s/api" % (host, port)
        self._host = host
        self._port = port
        self._roonsocket = RoonApiWebSocket(ws_address)

        self._roonsocket.register_connected_callback(self._socket_connected)
        self._roonsocket.register_registered_calback(self._server_registered)
        self._roonsocket.register_volume_controls_callback(
            self._on_volume_control_request
        )

        self._roonsocket.start()

    def _socket_connected(self):
        """Successfully connected the websocket."""
        LOGGER.debug("Connection with roon websockets (re)created.")
        self.ready = False
        self._volume_controls_request_id = None
        # authenticate / register
        # warning: at first launch the user has to approve the app in the Roon settings.
        appinfo = self._appinfo.copy()
        appinfo["required_services"] = [SERVICE_TRANSPORT, SERVICE_BROWSE]
        appinfo["provided_services"] = [CONTROL_VOLUME]
        if self._token:
            appinfo["token"] = self._token
        if not self._token:
            LOGGER.info("The application should be approved within Roon's settings.")
        else:
            LOGGER.debug("Confirming previous registration with Roon...")
        self._roonsocket.send_request(SERVICE_REGISTRY + "/register", appinfo)

    def _server_registered(self, reginfo):
        LOGGER.debug("Registered to Roon server %s", reginfo["display_name"])
        LOGGER.debug(reginfo)
        self._token = reginfo["token"]
        self._core_id = reginfo["core_id"]
        self._core_name = reginfo["display_name"]
        # subscribe to state change events

        self._roonsocket.subscribe(SERVICE_TRANSPORT, "zones", self._on_state_change)
        self._roonsocket.subscribe(SERVICE_TRANSPORT, "outputs", self._on_state_change)
        # set flag that we're fully initialized (used for blocking init)
        self.ready = True

    # pylint: disable=too-many-branches
    def _on_state_change(self, msg):
        """Process messages we receive from the roon websocket into a more usable format."""
        events = []
        if not msg or not isinstance(msg, dict):
            return
        for state_key, state_values in msg.items():
            LOGGER.debug("_on_state_change %s", state_key)
            changed_ids = []
            filter_keys = []
            if state_key in [
                "zones_seek_changed",
                "zones_changed",
                "zones_added",
                "zones",
            ]:
                for zone in state_values:
                    if zone["zone_id"] in self._zones:
                        self._zones[zone["zone_id"]].update(zone)
                    else:
                        self._zones[zone["zone_id"]] = zone
                    changed_ids.append(zone["zone_id"])
                    if "display_name" in zone:
                        filter_keys.append(zone["display_name"])
                    if "outputs" in zone:
                        for output in zone["outputs"]:
                            filter_keys.append(output["output_id"])
                            filter_keys.append(output["display_name"])
                event = (
                    "zones_seek_changed"
                    if state_key == "zones_seek_changed"
                    else "zones_changed"
                )
                events.append((event, changed_ids, filter_keys))
            elif state_key in ["outputs_changed", "outputs_added", "outputs"]:
                for output in state_values:
                    if output["output_id"] in self._outputs:
                        self._outputs[output["output_id"]].update(output)
                    else:
                        self._outputs[output["output_id"]] = output
                    changed_ids.append(output["output_id"])
                    filter_keys.append(output["display_name"])
                    filter_keys.append(output["zone_id"])
                event = "outputs_changed"
                events.append((event, changed_ids, filter_keys))
            elif state_key == "zones_removed":
                for item in state_values:
                    del self._zones[item]
            elif state_key == "outputs_removed":
                for item in state_values:
                    del self._outputs[item]
            else:
                LOGGER.warning("unknown state change: %s" % msg)
        for event, changed_ids, filter_keys in events:
            filter_keys.extend(changed_ids)
            for item in self._state_callbacks:
                callback = item[0]
                event_filter = item[1]
                id_filter = item[2]
                if event_filter and (event not in event_filter):
                    continue
                if id_filter and set(id_filter).isdisjoint(filter_keys):
                    continue
                try:
                    callback(event, changed_ids)
                # pylint: disable=broad-except
                except Exception:
                    LOGGER.exception("Error while executing callback!")

    def _get_outputs(self):
        outputs = {}
        data = self._request(SERVICE_TRANSPORT + "/get_outputs")
        if data and "outputs" in data:
            for output in data["outputs"]:
                outputs[output["output_id"]] = output
        return outputs

    def _get_zones(self):
        zones = {}
        data = self._request(SERVICE_TRANSPORT + "/get_zones")
        if data and "zones" in data:
            for zone in data["zones"]:
                zones[zone["zone_id"]] = zone
        return zones

    def _request(self, command, data=None):
        """Send command and wait for result."""
        LOGGER.debug("_request: command: %s", command)
        if not self._roonsocket:
            retries = 20
            while (not self.ready or not self._roonsocket) and retries:
                retries -= 1
                time.sleep(0.2)
            if not self.ready or not self._roonsocket:
                LOGGER.warning("socket is not yet ready")
                if not self._roonsocket:
                    return None
        LOGGER.debug("_request: sending")
        request_id = self._roonsocket.send_request(command, data)
        result = None
        retries = 50
        while retries:
            result = self._roonsocket.results.get(request_id)
            LOGGER.debug(
                "request: command: %s, retry: %d, success: %s",
                command,
                retries,
                result is not None,
            )
            if result:
                break
            retries -= 1

            time.sleep(0.05)
        try:
            del self._roonsocket.results[request_id]
        except KeyError:
            pass
        return result

    def _socket_watcher(self):
        """Monitor the connection state of the socket and reconnect if needed."""
        while not self._exit:
            if self._roonsocket and self._roonsocket.failed_state:
                LOGGER.warning("Socket connection lost! Will try to reconnect in 20s")
                count = 0
                while not self._exit and count < 21:
                    count += 1
                    time.sleep(1)
                if not self._exit:
                    self._server_setup(self._host, self._port)
            time.sleep(2)

    def register_volume_control(
        self,
        control_key,
        display_name,
        callback,
        initial_volume=0,
        volume_type="number",
        volume_step=2,
        volume_min=0,
        volume_max=100,
        is_muted=False,
    ):
        """Register a new volume control on the api."""
        if control_key in self._volume_controls:
            LOGGER.error("source_control %s is already registered!" % control_key)
            return
        control_data = {
            "display_name": display_name,
            "volume_type": volume_type,
            "volume_min": volume_min,
            "volume_max": volume_max,
            "volume_value": initial_volume,
            "volume_step": volume_step,
            "is_muted": is_muted,
            "control_key": control_key,
        }
        self._volume_controls[control_key] = (callback, control_data)
        if self._volume_controls_request_id:
            data = {"controls_added": [control_data]}
            self._roonsocket.send_continue(self._volume_controls_request_id, data)

    def unregister_volume_control(
        self,
        control_key,
    ):
        """Delete a new volume control on the api."""

        if control_key not in self._volume_controls:
            LOGGER.error("source_control %s is not registered!" % control_key)
            return
        control_data = {
            "control_key": control_key,
        }
        del self._volume_controls[control_key]

        if self._volume_controls_request_id:
            data = {"controls_removed": [control_data]}
            self._roonsocket.send_continue(self._volume_controls_request_id, data)

    def update_volume_control(self, control_key, volume=None, mute=None):
        """Update an existing volume control, report its state to Roon."""
        if control_key not in self._volume_controls:
            LOGGER.warning("volume_control %s is not (yet) registered!" % control_key)
            return False
        if not self._volume_controls_request_id:
            LOGGER.warning("Not yet registered, can not update volume control")
            return False
        if volume is not None:
            self._volume_controls[control_key][1]["volume_value"] = volume
        if mute is not None:
            self._volume_controls[control_key][1]["is_muted"] = mute
        data = {"controls_changed": [self._volume_controls[control_key][1]]}
        self._roonsocket.send_continue(self._volume_controls_request_id, data)
        return True

    def _on_volume_control_request(self, event, request_id, data):
        """Got request from roon server for a volume control registered on this endpoint."""
        if event == "subscribe_controls":
            LOGGER.debug("found subscription ID for volume controls: %s " % request_id)
            # send all volume controls already registered (handle connection loss)
            controls = []
            for _, control_data in self._volume_controls.values():
                controls.append(control_data)
            self._roonsocket.send_continue(request_id, {"controls_added": controls})
            self._volume_controls_request_id = request_id
        elif data and data.get("control_key"):
            control_key = data["control_key"]
            if event == "set_volume" and data["mode"] == "absolute":
                value = data["value"]
            elif event == "set_volume" and data["mode"] == "relative":
                value = (
                    self._volume_controls[control_key][1]["volume_value"]
                    + data["value"]
                )
            elif event == "set_volume" and data["mode"] == "relative_step":
                value = self._volume_controls[control_key][1]["volume_value"] + (
                    data["value"] * data["volume_step"]
                )
            elif event == "set_mute":
                value = data["mode"] == "on"
            else:
                return
            try:
                self._roonsocket.send_complete(request_id, "Success")
                self._volume_controls[control_key][0](control_key, event, value)
            except Exception:  # pylint: disable=broad-except
                LOGGER.exception("Error in volume_control callback")
                self._roonsocket.send_complete(request_id, "Error")