Skip to content

wg_utilities.devices

Modules/classes for physical devices.

dht22

DHT22 sensor.

DHT22Sensor

Class for DHT22 sensor, I can't remember where I got this from.

Parameters:

Name Type Description Default
pi_obj pi

a PI instance from pigpio

required
gpio int

the DHT22's data pin(?)

required
led int

an optional LED pin?

None
power int

an optional power pin, not sure what for though

None
Source code in wg_utilities/devices/dht22/dht22_lib.py
 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
class DHT22Sensor:
    """Class for DHT22 sensor, I can't remember where I got this from.

    Args:
        pi_obj (pi): a PI instance from pigpio
        gpio (int): the DHT22's data pin(?)
        led (int): an optional LED pin?
        power (int): an optional power pin, not sure what for though
    """

    MAX_NO_RESPONSE = 2

    DEFAULT_RHUM_VALUE: Final[Literal[-999]] = -999
    DEFAULT_TEMP_VALUE: Final[Literal[-999]] = -999

    def __init__(
        self,
        pi_obj: pi,
        gpio: int,
        led: int | None = None,
        power: int | None = None,
    ):
        self.pi = pi_obj
        self.gpio = gpio
        self.led = led
        self.power = power

        if self.power is not None:
            self.pi.write(self.power, 1)  # Switch Sensor on.
            sleep(2)

        self.powered = True

        self.callback = None

        self.bad_cs = 0  # Bad checksum count.
        self.bad_sm = 0  # Short message count.
        self.bad_mm = 0  # Missing message count.
        self.bad_sr = 0  # Sensor reset count.

        # Power cycle if timeout > MAX_TIMEOUTS.
        self.no_response = 0

        self.humidity: float = self.DEFAULT_RHUM_VALUE
        self.temperature: float = self.DEFAULT_TEMP_VALUE

        self.high_tick = 0
        self.bit = 40

        self.pi.set_pull_up_down(self.gpio, PUD_OFF)

        self.pi.set_watchdog(self.gpio, 0)  # Kill any watchdogs.

        self.callback = self.pi.callback(self.gpio, EITHER_EDGE, self._cb)

        self.hum_high: int  # humidity high byte
        self.hum_low: int  # humidity low byte
        self.temp_high: int  # temp high byte
        self.temp_low: int  # temp low byte
        self.checksum: int  # checksum

    def _cb(self, _: int, level: int, tick: int) -> None:
        """Callback function for DHT22 Sensor.

        Accumulate the 40 data bits.  Format into 5 bytes, humidity high,
        humidity low, temperature high, temperature low, checksum.

        Args:
            _ (int):        0-31    The GPIO which has changed state
            level (int):    0-2     0 = change to low (a falling edge)
                                    1 = change to high (a rising edge)
                                    2 = no level change (a watchdog timeout)
            tick (int):    32 bit   The number of microseconds since boot
                                    WARNING: this wraps around from
                                    4294967295 to 0 roughly every 72 minutes
        """

        diff = tickDiff(self.high_tick, tick)

        if level == 0:
            # Edge length determines if bit is 1 or 0.
            if diff >= 50:
                val = 1
                if diff >= 200:  # Bad bit?
                    self.checksum = 256  # Force bad checksum.
            else:
                val = 0

            if self.bit >= 40:  # Message complete.
                self.bit = 40

            elif self.bit >= 32:  # In checksum byte.
                self.checksum = (self.checksum << 1) + val

                if self.bit == 39:
                    # 40th bit received.

                    self.pi.set_watchdog(self.gpio, 0)

                    self.no_response = 0

                    total = self.hum_high + self.hum_low + self.temp_high + self.temp_low

                    if (total & 255) == self.checksum:  # Is checksum ok?
                        self.humidity = ((self.hum_high << 8) + self.hum_low) * 0.1

                        if self.temp_high & 128:  # Negative temperature.
                            mult = -0.1
                            self.temp_high &= 127
                        else:
                            mult = 0.1

                        self.temperature = ((self.temp_high << 8) + self.temp_low) * mult

                        if self.led is not None:
                            self.pi.write(self.led, 0)

                    else:
                        self.bad_cs += 1

            elif self.bit >= 24:  # in temp low byte
                self.temp_low = (self.temp_low << 1) + val

            elif self.bit >= 16:  # in temp high byte
                self.temp_high = (self.temp_high << 1) + val

            elif self.bit >= 8:  # in humidity low byte
                self.hum_low = (self.hum_low << 1) + val

            elif self.bit >= 0:  # in humidity high byte
                self.hum_high = (self.hum_high << 1) + val

            else:  # header bits
                pass

            self.bit += 1

        elif level == 1:
            self.high_tick = tick
            if diff > 250000:
                self.bit = -2
                self.hum_high = 0
                self.hum_low = 0
                self.temp_high = 0
                self.temp_low = 0
                self.checksum = 0

        else:  # level == pigpio.TIMEOUT:
            self.pi.set_watchdog(self.gpio, 0)
            if self.bit < 8:  # Too few data bits received.
                self.bad_mm += 1  # Bump missing message count.
                self.no_response += 1
                if self.no_response > self.MAX_NO_RESPONSE:
                    self.no_response = 0
                    self.bad_sr += 1  # Bump Sensor reset count.
                    if self.power is not None:
                        self.powered = False
                        self.pi.write(self.power, 0)
                        sleep(2)
                        self.pi.write(self.power, 1)
                        sleep(2)
                        self.powered = True
            elif self.bit < 39:  # Short message received.
                self.bad_sm += 1  # Bump short message count.
                self.no_response = 0

            else:  # Full message received.
                self.no_response = 0

    def trigger(self) -> None:
        """Trigger a new relative humidity and temperature reading."""
        if self.powered:
            if self.led is not None:
                self.pi.write(self.led, 1)

            self.pi.write(self.gpio, LOW)
            sleep(0.017)  # 17 ms
            self.pi.set_mode(self.gpio, INPUT)
            self.pi.set_watchdog(self.gpio, 200)

    def cancel(self) -> None:
        """Cancel the DHT22 Sensor."""
        self.pi.set_watchdog(self.gpio, 0)

        if self.callback is not None:
            self.callback.cancel()
            self.callback = None

cancel()

Cancel the DHT22 Sensor.

Source code in wg_utilities/devices/dht22/dht22_lib.py
199
200
201
202
203
204
205
def cancel(self) -> None:
    """Cancel the DHT22 Sensor."""
    self.pi.set_watchdog(self.gpio, 0)

    if self.callback is not None:
        self.callback.cancel()
        self.callback = None

trigger()

Trigger a new relative humidity and temperature reading.

Source code in wg_utilities/devices/dht22/dht22_lib.py
188
189
190
191
192
193
194
195
196
197
def trigger(self) -> None:
    """Trigger a new relative humidity and temperature reading."""
    if self.powered:
        if self.led is not None:
            self.pi.write(self.led, 1)

        self.pi.write(self.gpio, LOW)
        sleep(0.017)  # 17 ms
        self.pi.set_mode(self.gpio, INPUT)
        self.pi.set_watchdog(self.gpio, 200)

dht22_lib

A class I found a long time ago for DHT22, I can't remember where :(.

DHT22Sensor

Class for DHT22 sensor, I can't remember where I got this from.

Parameters:

Name Type Description Default
pi_obj pi

a PI instance from pigpio

required
gpio int

the DHT22's data pin(?)

required
led int

an optional LED pin?

None
power int

an optional power pin, not sure what for though

None
Source code in wg_utilities/devices/dht22/dht22_lib.py
 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
class DHT22Sensor:
    """Class for DHT22 sensor, I can't remember where I got this from.

    Args:
        pi_obj (pi): a PI instance from pigpio
        gpio (int): the DHT22's data pin(?)
        led (int): an optional LED pin?
        power (int): an optional power pin, not sure what for though
    """

    MAX_NO_RESPONSE = 2

    DEFAULT_RHUM_VALUE: Final[Literal[-999]] = -999
    DEFAULT_TEMP_VALUE: Final[Literal[-999]] = -999

    def __init__(
        self,
        pi_obj: pi,
        gpio: int,
        led: int | None = None,
        power: int | None = None,
    ):
        self.pi = pi_obj
        self.gpio = gpio
        self.led = led
        self.power = power

        if self.power is not None:
            self.pi.write(self.power, 1)  # Switch Sensor on.
            sleep(2)

        self.powered = True

        self.callback = None

        self.bad_cs = 0  # Bad checksum count.
        self.bad_sm = 0  # Short message count.
        self.bad_mm = 0  # Missing message count.
        self.bad_sr = 0  # Sensor reset count.

        # Power cycle if timeout > MAX_TIMEOUTS.
        self.no_response = 0

        self.humidity: float = self.DEFAULT_RHUM_VALUE
        self.temperature: float = self.DEFAULT_TEMP_VALUE

        self.high_tick = 0
        self.bit = 40

        self.pi.set_pull_up_down(self.gpio, PUD_OFF)

        self.pi.set_watchdog(self.gpio, 0)  # Kill any watchdogs.

        self.callback = self.pi.callback(self.gpio, EITHER_EDGE, self._cb)

        self.hum_high: int  # humidity high byte
        self.hum_low: int  # humidity low byte
        self.temp_high: int  # temp high byte
        self.temp_low: int  # temp low byte
        self.checksum: int  # checksum

    def _cb(self, _: int, level: int, tick: int) -> None:
        """Callback function for DHT22 Sensor.

        Accumulate the 40 data bits.  Format into 5 bytes, humidity high,
        humidity low, temperature high, temperature low, checksum.

        Args:
            _ (int):        0-31    The GPIO which has changed state
            level (int):    0-2     0 = change to low (a falling edge)
                                    1 = change to high (a rising edge)
                                    2 = no level change (a watchdog timeout)
            tick (int):    32 bit   The number of microseconds since boot
                                    WARNING: this wraps around from
                                    4294967295 to 0 roughly every 72 minutes
        """

        diff = tickDiff(self.high_tick, tick)

        if level == 0:
            # Edge length determines if bit is 1 or 0.
            if diff >= 50:
                val = 1
                if diff >= 200:  # Bad bit?
                    self.checksum = 256  # Force bad checksum.
            else:
                val = 0

            if self.bit >= 40:  # Message complete.
                self.bit = 40

            elif self.bit >= 32:  # In checksum byte.
                self.checksum = (self.checksum << 1) + val

                if self.bit == 39:
                    # 40th bit received.

                    self.pi.set_watchdog(self.gpio, 0)

                    self.no_response = 0

                    total = self.hum_high + self.hum_low + self.temp_high + self.temp_low

                    if (total & 255) == self.checksum:  # Is checksum ok?
                        self.humidity = ((self.hum_high << 8) + self.hum_low) * 0.1

                        if self.temp_high & 128:  # Negative temperature.
                            mult = -0.1
                            self.temp_high &= 127
                        else:
                            mult = 0.1

                        self.temperature = ((self.temp_high << 8) + self.temp_low) * mult

                        if self.led is not None:
                            self.pi.write(self.led, 0)

                    else:
                        self.bad_cs += 1

            elif self.bit >= 24:  # in temp low byte
                self.temp_low = (self.temp_low << 1) + val

            elif self.bit >= 16:  # in temp high byte
                self.temp_high = (self.temp_high << 1) + val

            elif self.bit >= 8:  # in humidity low byte
                self.hum_low = (self.hum_low << 1) + val

            elif self.bit >= 0:  # in humidity high byte
                self.hum_high = (self.hum_high << 1) + val

            else:  # header bits
                pass

            self.bit += 1

        elif level == 1:
            self.high_tick = tick
            if diff > 250000:
                self.bit = -2
                self.hum_high = 0
                self.hum_low = 0
                self.temp_high = 0
                self.temp_low = 0
                self.checksum = 0

        else:  # level == pigpio.TIMEOUT:
            self.pi.set_watchdog(self.gpio, 0)
            if self.bit < 8:  # Too few data bits received.
                self.bad_mm += 1  # Bump missing message count.
                self.no_response += 1
                if self.no_response > self.MAX_NO_RESPONSE:
                    self.no_response = 0
                    self.bad_sr += 1  # Bump Sensor reset count.
                    if self.power is not None:
                        self.powered = False
                        self.pi.write(self.power, 0)
                        sleep(2)
                        self.pi.write(self.power, 1)
                        sleep(2)
                        self.powered = True
            elif self.bit < 39:  # Short message received.
                self.bad_sm += 1  # Bump short message count.
                self.no_response = 0

            else:  # Full message received.
                self.no_response = 0

    def trigger(self) -> None:
        """Trigger a new relative humidity and temperature reading."""
        if self.powered:
            if self.led is not None:
                self.pi.write(self.led, 1)

            self.pi.write(self.gpio, LOW)
            sleep(0.017)  # 17 ms
            self.pi.set_mode(self.gpio, INPUT)
            self.pi.set_watchdog(self.gpio, 200)

    def cancel(self) -> None:
        """Cancel the DHT22 Sensor."""
        self.pi.set_watchdog(self.gpio, 0)

        if self.callback is not None:
            self.callback.cancel()
            self.callback = None
cancel()

Cancel the DHT22 Sensor.

Source code in wg_utilities/devices/dht22/dht22_lib.py
199
200
201
202
203
204
205
def cancel(self) -> None:
    """Cancel the DHT22 Sensor."""
    self.pi.set_watchdog(self.gpio, 0)

    if self.callback is not None:
        self.callback.cancel()
        self.callback = None
trigger()

Trigger a new relative humidity and temperature reading.

Source code in wg_utilities/devices/dht22/dht22_lib.py
188
189
190
191
192
193
194
195
196
197
def trigger(self) -> None:
    """Trigger a new relative humidity and temperature reading."""
    if self.powered:
        if self.led is not None:
            self.pi.write(self.led, 1)

        self.pi.write(self.gpio, LOW)
        sleep(0.017)  # 17 ms
        self.pi.set_mode(self.gpio, INPUT)
        self.pi.set_watchdog(self.gpio, 200)

epd

Drivers obtained from https://github.com/waveshare/e-Paper/.

EPD

Mirror the functionality of the EPD on devices which don't support it.

Source code in wg_utilities/devices/epd/__init__.py
33
34
class EPD:  # type: ignore[no-redef]
    """Mirror the functionality of the EPD on devices which don't support it."""

epd7in5_v2

EPD class.

  • | File : epd7in5.py
  • | Author : Waveshare team
  • | Function : Electronic paper driver
  • | Info : *----------------
  • | This version: V4.0
  • | Date : 2019-06-20

| Info : python demo


Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS OR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

epdconfig

Config for the EPD.

  • | File : epdconfig.py
  • | Author : Waveshare team
  • | Function : Hardware underlying interface
  • | Info : *----------------
  • | This version: V1.0
  • | Date : 2019-06-21
  • | Info :

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS OR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

FakeImplementation

Class to cover functionality of implementations on non-supporting devices.

Source code in wg_utilities/devices/epd/epdconfig.py
111
112
class FakeImplementation:
    """Class to cover functionality of implementations on non-supporting devices."""

yamaha_yas_209

Yamaha YAS-209 Soundbar.

YamahaYas209

Class for consuming information from a YAS-209 in real time.

Callback functions can be provided, as well as the option to start the listener immediately.

Parameters:

Name Type Description Default
ip str

the IP address of the YAS-209

required
on_event Callable[[YamahaYas209, Event], None]

a callback function to be called when an event is received. Defaults to None.

None
start_listener bool

whether to start the listener

False
on_volume_update Callable[[YamahaYas209, int], None]

a callback function to be called when the volume is updated. Defaults to None.

None
on_track_update Callable[[YamahaYas209, Track], None]

a callback function to be called when the track is updated. Defaults to None.

None
on_state_update Callable[[YamahaYas209, State], None]

a callback function to be called when the state is updated. Defaults to None.

None
logging bool

whether to log events. Defaults to False.

True
listen_ip str

the IP address to listen on. Defaults to None.

None
listen_port int

the port to listen on. Defaults to None.

None
source_port int

the port to use for the source. Defaults to None.

None
resubscribe_seconds int

the number of seconds between each resubscription. Defaults to 2 minutes.

120
Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
 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
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
class YamahaYas209:
    """Class for consuming information from a YAS-209 in real time.

    Callback functions can be provided, as well as the option to start the
    listener immediately.

    Args:
        ip (str): the IP address of the YAS-209
        on_event (Callable[[YamahaYas209, Event], None], optional): a callback
            function to be called when an event is received. Defaults to None.
        start_listener (bool, optional): whether to start the listener
        on_volume_update (Callable[[YamahaYas209, int], None], optional): a
            callback function to be called when the volume is updated. Defaults
            to None.
        on_track_update (Callable[[YamahaYas209, Track], None], optional): a
            callback function to be called when the track is updated. Defaults
            to None.
        on_state_update (Callable[[YamahaYas209, State], None], optional): a
            callback function to be called when the state is updated. Defaults
            to None.
        logging (bool, optional): whether to log events. Defaults to False.
        listen_ip (str, optional): the IP address to listen on. Defaults to
            None.
        listen_port (int, optional): the port to listen on. Defaults to None.
        source_port (int, optional): the port to use for the source. Defaults
            to None.
        resubscribe_seconds (int, optional): the number of seconds between each
            resubscription. Defaults to 2 minutes.
    """

    SUBSCRIPTION_SERVICES = (
        Yas209Service.AVT.service_id,
        Yas209Service.RC.service_id,
    )

    LAST_CHANGE_PAYLOAD_PARSERS: ClassVar[
        dict[str, Callable[[dict[Literal["Event"], object]], LastChange]]
    ] = {
        Yas209Service.AVT.service_id: LastChangeAVTransport.parse,
        Yas209Service.RC.service_id: LastChangeRenderingControl.parse,
    }

    class EventPayloadInfo(TypedDict):
        """Info for the payload sent to the `on_event` callback."""

        timestamp: datetime
        service_id: str
        service_type: str
        last_change: LastChange
        other_xml_payloads: dict[str, Any]

    def __init__(  # noqa: PLR0913
        self,
        ip: str,
        *,
        on_event: Callable[[EventPayloadInfo], None] | None = None,
        start_listener: bool = False,
        on_volume_update: Callable[[float], None] | None = None,
        on_track_update: Callable[[CurrentTrack.Info], None] | None = None,
        on_state_update: Callable[[str], None] | None = None,
        logging: bool = True,
        listen_ip: str | None = None,
        listen_port: int | None = None,
        source_port: int | None = None,
        resubscribe_seconds: int = 120,
    ):
        self.ip = ip
        self.on_event = on_event

        # noinspection HttpUrlsUsage
        self.description_url = f"http://{ip}:49152/description.xml"

        self.on_volume_update = on_volume_update
        self.on_track_update = on_track_update
        self.on_state_update = on_state_update

        self._current_track: CurrentTrack
        self._state: Yas209State
        self._volume_level: float

        self._listening = False

        self.device: UpnpDevice

        self._logging = logging
        self._listen_ip = listen_ip
        self._listen_port = listen_port
        self._source_port = source_port or 0

        self.resubscribe_seconds = resubscribe_seconds

        self._active_service_ids: list[str] = []

        if self._listen_ip is not None and self._listen_port is None:
            raise ValueError(
                "Argument `listen_port` cannot be None when `listen_ip` is not None:"
                f" {self._listen_ip!r}",
            )

        if start_listener:
            self.listen()

    def listen(self) -> None:
        """Start the listener."""
        if self._logging:
            LOGGER.info("Starting listener")

        if self._listening:
            if self._logging:
                LOGGER.debug(
                    "Already listening to '%s', returning immediately",
                    "', '".join(self._active_service_ids),
                )
            return

        worker_exception: BaseException | None = None

        def _worker() -> None:
            nonlocal worker_exception
            try:
                new_event_loop().run_until_complete(self._subscribe())
            except Exception as exc:
                worker_exception = exc

        listener_thread = Thread(target=_worker)
        listener_thread.start()

        while not self._listening and worker_exception is None:
            sleep(0.01)

        if isinstance(worker_exception, BaseException):
            raise worker_exception

        if self._logging:
            LOGGER.debug(
                "Listen action complete, now subscribed to '%s'",
                "', '".join(self._active_service_ids),
            )

    def on_event_wrapper(
        self,
        service: UpnpService,
        service_variables: Sequence[UpnpStateVariable[str]],
    ) -> None:
        """Wrap the `on_event` callback to process the XML payload(s) first.

        Args:
            service (UpnpService): the service which has sent an update
            service_variables (list): a list of state variables that have updated
        """

        xml_payloads: dict[str, object] = {sv.name: sv.value for sv in service_variables}

        # Convert any nested XML into JSON
        self._parse_xml_dict(xml_payloads)

        last_change = self.LAST_CHANGE_PAYLOAD_PARSERS[service.service_id](
            xml_payloads.pop("LastChange"),  # type: ignore[arg-type]
        )

        event_payload: YamahaYas209.EventPayloadInfo = {
            "timestamp": datetime.now(UTC),
            "service_id": service.service_id,
            "service_type": service.service_type,
            "last_change": last_change,
            "other_xml_payloads": xml_payloads,
        }

        if service.service_id == "urn:upnp-org:serviceId:AVTransport":
            if last_change.Event.InstanceID.TransportState != self.state.name:
                self.set_state(
                    Yas209State[last_change.Event.InstanceID.TransportState],
                    local_only=True,
                )
            if last_change.Event.InstanceID.CurrentTrackMetaData is None:
                self.current_track = CurrentTrack.null_track()
            else:
                self.current_track = CurrentTrack.from_last_change(last_change)
        elif service.service_id == "urn:upnp-org:serviceId:RenderingControl":
            # The DLNA payload has volume as a string value between 0 and 100
            self.set_volume_level(
                float(last_change.Event.InstanceID.Volume.val) / 100,
                local_only=True,
            )

        if self.on_event is not None:
            self.on_event(event_payload)

    @_needs_device
    async def _subscribe(self) -> None:  # noqa: PLR0912
        """Subscribe to service(s) and output updates."""
        # start notify server/event handler
        local_ip = get_local_ip(self.device.device_url)
        source = (local_ip, self._source_port)

        callback_url = (
            None
            if self._listen_port is None
            else f"http://{self._listen_ip or local_ip}:{self._listen_port}/notify"
        )
        server = AiohttpNotifyServer(
            self.device.requester,
            source=source,
            callback_url=callback_url,
        )
        await server.async_start_server()

        if self._logging:
            LOGGER.debug(
                dedent(
                    """
            Listen IP:          %s
            Listen Port:        %s
            Source IP:          %s
            Source Port:        %s
            Callback URL:       %s
            Server Listen IP:   %s
            Server Listen Port: %s
            """,
                ),
                self._listen_ip,
                str(self._listen_port),
                local_ip,
                str(self._source_port),
                str(callback_url),
                server.listen_ip,
                server.listen_port,
            )

        # create service subscriptions
        failed_subscriptions = []
        for service in self.device.services.values():
            if service.service_id not in self.SUBSCRIPTION_SERVICES:
                continue

            service.on_event = self.on_event_wrapper
            try:
                await server.event_handler.async_subscribe(service)
                self._active_service_ids.append(service.service_id)
                LOGGER.info("Subscribed to %s", service.service_id)
            except UpnpCommunicationError:
                if self._logging:
                    LOGGER.exception(
                        "Unable to subscribe to %s",
                        service.service_id,
                    )
                failed_subscriptions.append(service)

        self._listening = True

        # keep the webservice running (force resubscribe)
        while self._listening:
            for _ in range(self.resubscribe_seconds):
                if not self._listening:
                    if self._logging:
                        LOGGER.debug("Exiting listener loop")
                    break
                await async_sleep(1)

            # The break above only covers the for loop, this is for the while loop
            if not self._listening:
                break

            LOGGER.debug("Resubscribing to all services")
            await server.event_handler.async_resubscribe_all()

            services_to_remove = []
            for service in failed_subscriptions:
                try:
                    if self._logging:
                        LOGGER.debug(
                            "Attempting to create originally failed subscription for"
                            " %s",
                            service.service_id,
                        )
                    await server.event_handler.async_subscribe(service)
                    self._active_service_ids.append(service.service_id)
                    services_to_remove.append(service)
                except UpnpCommunicationError as exc:  # noqa: PERF203
                    log_message = (
                        f"Still unable to subscribe to {service.service_id}: {exc!r}"
                    )

                    if self._logging:
                        LOGGER.exception(log_message)
                    else:
                        # Should still log this exception, regardless
                        LOGGER.warning(log_message)

            # This needs to be separate because `.remove` is the cleanest way to remove
            # the items, but can't be done within the loop, and I can't `deepcopy`
            # `failed_subscriptions` and its threaded content
            for service in services_to_remove:
                failed_subscriptions.remove(service)

        if self._logging:
            LOGGER.debug(
                "Exiting subscription loop, `self._listening` is `%s`",
                str(self._listening),
            )

    def _call_service_action(
        self,
        service: Yas209Service,
        action: str,
        callback: Callable[[Mapping[str, object]], None] | None = None,
        **call_kwargs: str | int,
    ) -> dict[str, Any] | None:
        if action not in service.actions:
            raise ValueError(
                f"Unexpected action {action!r} for service {service.value!r}. "
                f"""Must be one of '{"', '".join(service.actions)}'""",
            )

        @_needs_device
        async def _worker(_: YamahaYas209) -> Mapping[str, Any]:
            res: Mapping[str, Any] = (
                await self.device.services[service.service_name]
                .action(action)
                .async_call(**call_kwargs)
            )

            if callback is not None:
                callback(res)

            return res

        return run(_worker(self))  # type: ignore[no-any-return]

    @staticmethod
    def _parse_xml_dict(xml_dict: MutableMapping[str, object]) -> None:
        """Convert XML to JSON within dict in place.

        Parse a dictionary where some values are/could be XML strings, and unpack
        the XML into JSON within the dict

        Args:
            xml_dict (dict): the dictionary to parse
        """

        pattern = re_compile(r"&(?!(amp|apos|lt|gt|quot);)")

        traverse_dict(
            xml_dict,
            target_type=str,
            target_processor_func=lambda val, **_: parse_xml(  # type: ignore[arg-type]
                pattern.sub("&amp;", val),
                attr_prefix="",
                cdata_key="text",
            ),
            single_keys_to_remove=["val", "DIDL-Lite"],
        )

    # TODO: @on_exception()
    def pause(self) -> None:
        """Pause the current media."""
        self._call_service_action(Yas209Service.AVT, "Pause", InstanceID=0)

    def play(self) -> None:
        """Play the current media."""
        self._call_service_action(Yas209Service.AVT, "Play", InstanceID=0, Speed="1")

    def play_pause(self) -> None:
        """Toggle the playing/paused state."""
        if self.state == Yas209State.PLAYING:
            self.pause()
        else:
            self.play()

    def mute(self) -> None:
        """Mute."""
        self._call_service_action(
            Yas209Service.RC,
            "SetMute",
            InstanceID=0,
            Channel="Master",
            DesiredMute=True,
        )

    def next_track(self) -> None:
        """Skip to the next track."""
        self._call_service_action(Yas209Service.AVT, "Next", InstanceID=0)

    def previous_track(self) -> None:
        """Go to the previous track."""
        self._call_service_action(Yas209Service.AVT, "Previous", InstanceID=0)

    def set_state(self, value: Yas209State, *, local_only: bool = False) -> None:
        """Set the state to the given value.

        Args:
            value (Yas209State): the new state of the YAS-209
            local_only (bool): only change the local value of the state (i.e. don't
                update the soundbar)

        Raises:
            TypeError: if the value is not a valid state
        """
        if not isinstance(value, Yas209State):
            raise TypeError("Expected a Yas209State instance.")

        self._state = value

        if not local_only:
            func = {
                Yas209State.PLAYING: self.play,
                Yas209State.PAUSED_PLAYBACK: self.pause,
                Yas209State.STOPPED: self.stop,
            }.get(value)

            if func is not None:
                func()

        if self.on_state_update is not None:
            self.on_state_update(self._state.value)

    def set_volume_level(self, value: float, *, local_only: bool = False) -> None:
        """Set the soundbar's volume level.

        Args:
            value (float): the new volume level, as a float between 0 and 1
            local_only (bool): only change the local value of the volume level (i.e.
                don't update the soundbar)

        Raises:
            ValueError: if the value is not between 0 and 1
        """

        if not 0 <= value <= 1:
            raise ValueError("Volume level must be between 0 and 1")

        self._volume_level = round(value, 2)

        if not local_only:
            self._call_service_action(
                Yas209Service.RC,
                "SetVolume",
                InstanceID=0,
                Channel="Master",
                DesiredVolume=int(self._volume_level * 100),
            )

        if self.on_volume_update is not None:
            self.on_volume_update(self._volume_level)

    def stop(self) -> None:
        """Stop whatever is currently playing."""
        self._call_service_action(Yas209Service.AVT, "Stop", InstanceID=0, Speed="1")

    def stop_listening(self) -> None:
        """Stop the event listener."""
        if self._logging:
            LOGGER.debug(
                "Stopping event listener (will take <= %i seconds)",
                self.resubscribe_seconds,
            )

        self._listening = False

    def unmute(self) -> None:
        """Unmute."""
        self._call_service_action(
            Yas209Service.RC,
            "SetMute",
            InstanceID=0,
            Channel="Master",
            DesiredMute=False,
        )

    def volume_down(self) -> None:
        """Decrease the volume by 2 points."""
        self.set_volume_level(round(self.volume_level - 0.02, 2))

    def volume_up(self) -> None:
        """Increase the volume by 2 points."""
        self.set_volume_level(round(self.volume_level + 0.02, 2))

    @property
    def album_art_uri(self) -> str | None:
        """Album art URI for the currently playing media.

        Returns:
            str: URL for the current album's artwork
        """
        return self.current_track.album_art_uri

    @property
    def current_track(self) -> CurrentTrack:
        """Currently playing track.

        Returns:
            dict: the current track's info
        """
        if not hasattr(self, "_current_track"):
            media_info = self.get_media_info()
            self._current_track = CurrentTrack.from_get_media_info(
                GetMediaInfoResponse.model_validate(media_info),
            )

        return self._current_track

    @current_track.setter
    def current_track(self, value: CurrentTrack) -> None:
        """Set the current track.

        Args:
            value (CurrentTrack): the new current track

        Raises:
            TypeError: if the value is not a CurrentTrack instance
        """

        if not isinstance(value, CurrentTrack):
            raise TypeError("Expected a CurrentTrack instance.")

        self._current_track = value

        if self.on_track_update is not None:
            self.on_track_update(value.json)

    @property
    def is_listening(self) -> bool:
        """Whether the event listener is running.

        Returns:
            bool: whether the event listener is running
        """
        return self._listening

    @property
    def media_album_name(self) -> str | None:
        """Name of the current album.

        Returns:
            str: the current media_title
        """
        return self.current_track.media_album_name

    @property
    def media_artist(self) -> str | None:
        """Currently playing artist.

        Returns:
            str: the current media_artist
        """
        return self.current_track.media_artist

    @property
    def media_duration(self) -> float | None:
        """Duration of current playing media in seconds.

        Returns:
            str: the current media_duration
        """
        return self.current_track.media_duration

    def get_media_info(self) -> dict[str, Any]:
        """Get the current media info from the soundbar.

        Returns:
            dict: the response in JSON form
        """

        media_info = (
            self._call_service_action(Yas209Service.AVT, "GetMediaInfo", InstanceID=0)
            or {}
        )

        self._parse_xml_dict(media_info)

        return media_info

    @property
    def media_title(self) -> str | None:
        """Currently playing media title.

        Returns:
            str: the current media_album_name
        """
        return self.current_track.media_title

    @property
    def state(self) -> Yas209State:
        """Current state of the soundbar.

        Returns:
            Yas209State: the current state of the YAS-209 (e.g. playing, stopped)
        """
        if hasattr(self, "_state"):
            return self._state

        return Yas209State.UNKNOWN

    @property
    def volume_level(self) -> float:
        """Current volume level.

        Returns:
            float: the current volume level
        """
        if not hasattr(self, "_volume_level"):
            res = (
                self._call_service_action(
                    Yas209Service.RC,
                    "GetVolume",
                    InstanceID=0,
                    Channel="Master",
                )
                or {}
            )

            self._volume_level = float(res.get("CurrentVolume", 0) / 100)

        return self._volume_level

album_art_uri: str | None property

Album art URI for the currently playing media.

Returns:

Name Type Description
str str | None

URL for the current album's artwork

current_track: CurrentTrack property writable

Currently playing track.

Returns:

Name Type Description
dict CurrentTrack

the current track's info

is_listening: bool property

Whether the event listener is running.

Returns:

Name Type Description
bool bool

whether the event listener is running

media_album_name: str | None property

Name of the current album.

Returns:

Name Type Description
str str | None

the current media_title

media_artist: str | None property

Currently playing artist.

Returns:

Name Type Description
str str | None

the current media_artist

media_duration: float | None property

Duration of current playing media in seconds.

Returns:

Name Type Description
str float | None

the current media_duration

media_title: str | None property

Currently playing media title.

Returns:

Name Type Description
str str | None

the current media_album_name

state: Yas209State property

Current state of the soundbar.

Returns:

Name Type Description
Yas209State Yas209State

the current state of the YAS-209 (e.g. playing, stopped)

volume_level: float property

Current volume level.

Returns:

Name Type Description
float float

the current volume level

EventPayloadInfo

Bases: TypedDict

Info for the payload sent to the on_event callback.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
578
579
580
581
582
583
584
585
class EventPayloadInfo(TypedDict):
    """Info for the payload sent to the `on_event` callback."""

    timestamp: datetime
    service_id: str
    service_type: str
    last_change: LastChange
    other_xml_payloads: dict[str, Any]

get_media_info()

Get the current media info from the soundbar.

Returns:

Name Type Description
dict dict[str, Any]

the response in JSON form

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
def get_media_info(self) -> dict[str, Any]:
    """Get the current media info from the soundbar.

    Returns:
        dict: the response in JSON form
    """

    media_info = (
        self._call_service_action(Yas209Service.AVT, "GetMediaInfo", InstanceID=0)
        or {}
    )

    self._parse_xml_dict(media_info)

    return media_info

listen()

Start the listener.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
def listen(self) -> None:
    """Start the listener."""
    if self._logging:
        LOGGER.info("Starting listener")

    if self._listening:
        if self._logging:
            LOGGER.debug(
                "Already listening to '%s', returning immediately",
                "', '".join(self._active_service_ids),
            )
        return

    worker_exception: BaseException | None = None

    def _worker() -> None:
        nonlocal worker_exception
        try:
            new_event_loop().run_until_complete(self._subscribe())
        except Exception as exc:
            worker_exception = exc

    listener_thread = Thread(target=_worker)
    listener_thread.start()

    while not self._listening and worker_exception is None:
        sleep(0.01)

    if isinstance(worker_exception, BaseException):
        raise worker_exception

    if self._logging:
        LOGGER.debug(
            "Listen action complete, now subscribed to '%s'",
            "', '".join(self._active_service_ids),
        )

mute()

Mute.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
905
906
907
908
909
910
911
912
913
def mute(self) -> None:
    """Mute."""
    self._call_service_action(
        Yas209Service.RC,
        "SetMute",
        InstanceID=0,
        Channel="Master",
        DesiredMute=True,
    )

next_track()

Skip to the next track.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
915
916
917
def next_track(self) -> None:
    """Skip to the next track."""
    self._call_service_action(Yas209Service.AVT, "Next", InstanceID=0)

on_event_wrapper(service, service_variables)

Wrap the on_event callback to process the XML payload(s) first.

Parameters:

Name Type Description Default
service UpnpService

the service which has sent an update

required
service_variables list

a list of state variables that have updated

required
Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
def on_event_wrapper(
    self,
    service: UpnpService,
    service_variables: Sequence[UpnpStateVariable[str]],
) -> None:
    """Wrap the `on_event` callback to process the XML payload(s) first.

    Args:
        service (UpnpService): the service which has sent an update
        service_variables (list): a list of state variables that have updated
    """

    xml_payloads: dict[str, object] = {sv.name: sv.value for sv in service_variables}

    # Convert any nested XML into JSON
    self._parse_xml_dict(xml_payloads)

    last_change = self.LAST_CHANGE_PAYLOAD_PARSERS[service.service_id](
        xml_payloads.pop("LastChange"),  # type: ignore[arg-type]
    )

    event_payload: YamahaYas209.EventPayloadInfo = {
        "timestamp": datetime.now(UTC),
        "service_id": service.service_id,
        "service_type": service.service_type,
        "last_change": last_change,
        "other_xml_payloads": xml_payloads,
    }

    if service.service_id == "urn:upnp-org:serviceId:AVTransport":
        if last_change.Event.InstanceID.TransportState != self.state.name:
            self.set_state(
                Yas209State[last_change.Event.InstanceID.TransportState],
                local_only=True,
            )
        if last_change.Event.InstanceID.CurrentTrackMetaData is None:
            self.current_track = CurrentTrack.null_track()
        else:
            self.current_track = CurrentTrack.from_last_change(last_change)
    elif service.service_id == "urn:upnp-org:serviceId:RenderingControl":
        # The DLNA payload has volume as a string value between 0 and 100
        self.set_volume_level(
            float(last_change.Event.InstanceID.Volume.val) / 100,
            local_only=True,
        )

    if self.on_event is not None:
        self.on_event(event_payload)

pause()

Pause the current media.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
890
891
892
def pause(self) -> None:
    """Pause the current media."""
    self._call_service_action(Yas209Service.AVT, "Pause", InstanceID=0)

play()

Play the current media.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
894
895
896
def play(self) -> None:
    """Play the current media."""
    self._call_service_action(Yas209Service.AVT, "Play", InstanceID=0, Speed="1")

play_pause()

Toggle the playing/paused state.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
898
899
900
901
902
903
def play_pause(self) -> None:
    """Toggle the playing/paused state."""
    if self.state == Yas209State.PLAYING:
        self.pause()
    else:
        self.play()

previous_track()

Go to the previous track.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
919
920
921
def previous_track(self) -> None:
    """Go to the previous track."""
    self._call_service_action(Yas209Service.AVT, "Previous", InstanceID=0)

set_state(value, *, local_only=False)

Set the state to the given value.

Parameters:

Name Type Description Default
value Yas209State

the new state of the YAS-209

required
local_only bool

only change the local value of the state (i.e. don't update the soundbar)

False

Raises:

Type Description
TypeError

if the value is not a valid state

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
def set_state(self, value: Yas209State, *, local_only: bool = False) -> None:
    """Set the state to the given value.

    Args:
        value (Yas209State): the new state of the YAS-209
        local_only (bool): only change the local value of the state (i.e. don't
            update the soundbar)

    Raises:
        TypeError: if the value is not a valid state
    """
    if not isinstance(value, Yas209State):
        raise TypeError("Expected a Yas209State instance.")

    self._state = value

    if not local_only:
        func = {
            Yas209State.PLAYING: self.play,
            Yas209State.PAUSED_PLAYBACK: self.pause,
            Yas209State.STOPPED: self.stop,
        }.get(value)

        if func is not None:
            func()

    if self.on_state_update is not None:
        self.on_state_update(self._state.value)

set_volume_level(value, *, local_only=False)

Set the soundbar's volume level.

Parameters:

Name Type Description Default
value float

the new volume level, as a float between 0 and 1

required
local_only bool

only change the local value of the volume level (i.e. don't update the soundbar)

False

Raises:

Type Description
ValueError

if the value is not between 0 and 1

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
def set_volume_level(self, value: float, *, local_only: bool = False) -> None:
    """Set the soundbar's volume level.

    Args:
        value (float): the new volume level, as a float between 0 and 1
        local_only (bool): only change the local value of the volume level (i.e.
            don't update the soundbar)

    Raises:
        ValueError: if the value is not between 0 and 1
    """

    if not 0 <= value <= 1:
        raise ValueError("Volume level must be between 0 and 1")

    self._volume_level = round(value, 2)

    if not local_only:
        self._call_service_action(
            Yas209Service.RC,
            "SetVolume",
            InstanceID=0,
            Channel="Master",
            DesiredVolume=int(self._volume_level * 100),
        )

    if self.on_volume_update is not None:
        self.on_volume_update(self._volume_level)

stop()

Stop whatever is currently playing.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
981
982
983
def stop(self) -> None:
    """Stop whatever is currently playing."""
    self._call_service_action(Yas209Service.AVT, "Stop", InstanceID=0, Speed="1")

stop_listening()

Stop the event listener.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
985
986
987
988
989
990
991
992
993
def stop_listening(self) -> None:
    """Stop the event listener."""
    if self._logging:
        LOGGER.debug(
            "Stopping event listener (will take <= %i seconds)",
            self.resubscribe_seconds,
        )

    self._listening = False

unmute()

Unmute.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
 995
 996
 997
 998
 999
1000
1001
1002
1003
def unmute(self) -> None:
    """Unmute."""
    self._call_service_action(
        Yas209Service.RC,
        "SetMute",
        InstanceID=0,
        Channel="Master",
        DesiredMute=False,
    )

volume_down()

Decrease the volume by 2 points.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
1005
1006
1007
def volume_down(self) -> None:
    """Decrease the volume by 2 points."""
    self.set_volume_level(round(self.volume_level - 0.02, 2))

volume_up()

Increase the volume by 2 points.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
1009
1010
1011
def volume_up(self) -> None:
    """Increase the volume by 2 points."""
    self.set_volume_level(round(self.volume_level + 0.02, 2))

yamaha_yas_209

Classes etc. for subscribing to YAS-209 updates.

CurrentTrack

Class for easy processing/passing of track metadata.

Attributes:

Name Type Description
album_art_uri str

URL for album artwork

media_album_name str

album name

media_artist str

track's artist(s)

media_title str

track's title

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
class CurrentTrack:
    """Class for easy processing/passing of track metadata.

    Attributes:
        album_art_uri (str): URL for album artwork
        media_album_name (str): album name
        media_artist (str): track's artist(s)
        media_title (str): track's title
    """

    DURATION_FORMAT = "%H:%M:%S.%f"

    NULL_TRACK_STR = "NULL"

    class Info(TypedDict):
        """Info for the attributes of this class."""

        album_art_uri: str | None
        media_album_name: str | None
        media_artist: str | None
        media_duration: float
        media_title: str | None

    def __init__(
        self,
        *,
        album_art_uri: str | None,
        media_album_name: str | None,
        media_artist: str | None,
        media_duration: float,
        media_title: str | None,
    ):
        self.album_art_uri = album_art_uri
        self.media_album_name = media_album_name
        self.media_artist = media_artist
        self.media_duration = media_duration
        self.media_title = media_title

    @classmethod
    def _create_from_metadata_item(cls, metadata_item: TrackMetaDataItem) -> CurrentTrack:
        """Create a CurrentTrack instance from a response metadata item.

        Args:
            metadata_item (TrackMetaDataItem): the metadata pulled from the response

        Returns:
            CurrentTrack: instance containing relevant info
        """
        duration_time = strptime(metadata_item.res.duration, cls.DURATION_FORMAT)

        duration_delta = timedelta(
            hours=duration_time.tm_hour,
            minutes=duration_time.tm_min,
            seconds=duration_time.tm_sec,
        )

        return CurrentTrack(
            album_art_uri=(
                metadata_item.upnp_albumArtURI
                if metadata_item.upnp_albumArtURI != "un_known"
                else None
            ),
            media_album_name=metadata_item.upnp_album,
            media_artist=metadata_item.dc_creator,
            media_duration=duration_delta.total_seconds(),
            media_title=metadata_item.dc_title,
        )

    @classmethod
    def from_get_media_info(cls, response: GetMediaInfoResponse) -> CurrentTrack:
        """Create a CurrentTrack instance from a GetMediaInfo response.

        Args:
            response (GetMediaInfoResponse): the response from a GetMediaInfo request

        Returns:
            CurrentTrack: a CurrentTrack instance with relevant info
        """
        return cls._create_from_metadata_item(response.CurrentURIMetaData.item)

    @classmethod
    def from_last_change(cls, last_change: LastChangeTypeVar) -> CurrentTrack:
        """Create a CurrentTrack instance from a LastChange response.

        Args:
            last_change (LastChangeAVTransport): the payload from the last DLNA change

        Returns:
            CurrentTrack: a CurrentTrack instance with relevant info
        """
        return cls._create_from_metadata_item(
            last_change.Event.InstanceID.CurrentTrackMetaData.item,
        )

    @classmethod
    def null_track(cls) -> CurrentTrack:
        """Create a null track.

        Returns:
            CurrentTrack: a CurrentTrack instance with all attributes set to None
        """
        return cls(
            album_art_uri=None,
            media_album_name=None,
            media_artist=None,
            media_duration=0.0,
            media_title=None,
        )

    @property
    def json(self) -> CurrentTrack.Info:
        """JSON representation of the current track.

        Returns:
            CurrentTrack.Info: info on the currently playing track
        """
        return {
            "album_art_uri": self.album_art_uri,
            "media_album_name": self.media_album_name,
            "media_artist": self.media_artist,
            "media_duration": self.media_duration,
            "media_title": self.media_title,
        }

    def __eq__(self, other: object) -> bool:
        """Check equality of this instance with another object.

        Args:
            other (object): the object to compare to

        Returns:
            bool: True if the objects are equal, False otherwise
        """
        if not isinstance(other, CurrentTrack):
            return NotImplemented

        return self.json == other.json

    def __repr__(self) -> str:
        """Get a string representation of this instance."""
        return f"{self.__class__.__name__}({self.__str__()!r})"

    def __str__(self) -> str:
        """Return a string representation of the current track."""

        if self.media_title is None and self.media_artist is None:
            return self.NULL_TRACK_STR

        return f"{self.media_title!r} by {self.media_artist}"
json: CurrentTrack.Info property

JSON representation of the current track.

Returns:

Type Description
Info

CurrentTrack.Info: info on the currently playing track

Info

Bases: TypedDict

Info for the attributes of this class.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
215
216
217
218
219
220
221
222
class Info(TypedDict):
    """Info for the attributes of this class."""

    album_art_uri: str | None
    media_album_name: str | None
    media_artist: str | None
    media_duration: float
    media_title: str | None
__eq__(other)

Check equality of this instance with another object.

Parameters:

Name Type Description Default
other object

the object to compare to

required

Returns:

Name Type Description
bool bool

True if the objects are equal, False otherwise

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
325
326
327
328
329
330
331
332
333
334
335
336
337
def __eq__(self, other: object) -> bool:
    """Check equality of this instance with another object.

    Args:
        other (object): the object to compare to

    Returns:
        bool: True if the objects are equal, False otherwise
    """
    if not isinstance(other, CurrentTrack):
        return NotImplemented

    return self.json == other.json
__repr__()

Get a string representation of this instance.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
339
340
341
def __repr__(self) -> str:
    """Get a string representation of this instance."""
    return f"{self.__class__.__name__}({self.__str__()!r})"
__str__()

Return a string representation of the current track.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
343
344
345
346
347
348
349
def __str__(self) -> str:
    """Return a string representation of the current track."""

    if self.media_title is None and self.media_artist is None:
        return self.NULL_TRACK_STR

    return f"{self.media_title!r} by {self.media_artist}"
from_get_media_info(response) classmethod

Create a CurrentTrack instance from a GetMediaInfo response.

Parameters:

Name Type Description Default
response GetMediaInfoResponse

the response from a GetMediaInfo request

required

Returns:

Name Type Description
CurrentTrack CurrentTrack

a CurrentTrack instance with relevant info

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
269
270
271
272
273
274
275
276
277
278
279
@classmethod
def from_get_media_info(cls, response: GetMediaInfoResponse) -> CurrentTrack:
    """Create a CurrentTrack instance from a GetMediaInfo response.

    Args:
        response (GetMediaInfoResponse): the response from a GetMediaInfo request

    Returns:
        CurrentTrack: a CurrentTrack instance with relevant info
    """
    return cls._create_from_metadata_item(response.CurrentURIMetaData.item)
from_last_change(last_change) classmethod

Create a CurrentTrack instance from a LastChange response.

Parameters:

Name Type Description Default
last_change LastChangeAVTransport

the payload from the last DLNA change

required

Returns:

Name Type Description
CurrentTrack CurrentTrack

a CurrentTrack instance with relevant info

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
281
282
283
284
285
286
287
288
289
290
291
292
293
@classmethod
def from_last_change(cls, last_change: LastChangeTypeVar) -> CurrentTrack:
    """Create a CurrentTrack instance from a LastChange response.

    Args:
        last_change (LastChangeAVTransport): the payload from the last DLNA change

    Returns:
        CurrentTrack: a CurrentTrack instance with relevant info
    """
    return cls._create_from_metadata_item(
        last_change.Event.InstanceID.CurrentTrackMetaData.item,
    )
null_track() classmethod

Create a null track.

Returns:

Name Type Description
CurrentTrack CurrentTrack

a CurrentTrack instance with all attributes set to None

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
@classmethod
def null_track(cls) -> CurrentTrack:
    """Create a null track.

    Returns:
        CurrentTrack: a CurrentTrack instance with all attributes set to None
    """
    return cls(
        album_art_uri=None,
        media_album_name=None,
        media_artist=None,
        media_duration=0.0,
        media_title=None,
    )

CurrentTrackMetaDataItemRes

Bases: BaseModel

BaseModel for part of the DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
45
46
47
48
49
50
class CurrentTrackMetaDataItemRes(BaseModel, extra="allow"):
    """BaseModel for part of the DLNA payload."""

    protocolInfo: str  # noqa: N815
    duration: str
    text: str | None = None

EventAVTransport

Bases: BaseModel

BaseModel for part of the DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
123
124
125
126
127
class EventAVTransport(BaseModel, extra="allow"):
    """BaseModel for part of the DLNA payload."""

    xmlns: Literal["urn:schemas-upnp-org:metadata-1-0/AVT/"]
    InstanceID: InstanceIDAVTransport

EventRenderingControl

Bases: BaseModel

BaseModel for part of the DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
130
131
132
133
134
class EventRenderingControl(BaseModel, extra="allow"):
    """BaseModel for part of the DLNA payload."""

    xmlns: Literal["urn:schemas-upnp-org:metadata-1-0/RCS/"]
    InstanceID: InstanceIDRenderingControl

GetMediaInfoResponse

Bases: BaseModel

BaseModel for the response from a GetMediaInfo request.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
186
187
188
189
190
191
192
193
194
195
196
197
198
class GetMediaInfoResponse(BaseModel):
    """BaseModel for the response from a GetMediaInfo request."""

    NrTracks: int
    MediaDuration: str
    CurrentURI: str
    CurrentURIMetaData: TrackMetaData
    NextURI: str
    NextURIMetaData: str
    TrackSource: str
    PlayMedium: str
    RecordMedium: str
    WriteStatus: str

InstanceIDAVTransport

Bases: BaseModel

BaseModel for part of the DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
 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
class InstanceIDAVTransport(BaseModel, extra="allow"):
    """BaseModel for part of the DLNA payload."""

    val: str
    TransportState: str
    TransportStatus: str | None = None
    NumberOfTracks: str | None = None
    CurrentTrack: str | None = None
    CurrentTrackDuration: str | None = None
    CurrentMediaDuration: str | None = None
    CurrentTrackURI: str | None = None
    AVTransportURI: str | None = None
    TrackSource: str | None = None
    CurrentTrackMetaData: TrackMetaData | None = None
    AVTransportURIMetaData: TrackMetaData | None = None
    PlaybackStorageMedium: str | None = None
    PossiblePlaybackStorageMedia: str | None = None
    PossibleRecordStorageMedia: str | None = None
    RecordStorageMedium: str | None = None
    CurrentPlayMode: str | None = None
    TransportPlaySpeed: str | None = None
    RecordMediumWriteStatus: str | None = None
    CurrentRecordQualityMode: str | None = None
    PossibleRecordQualityModes: str | None = None
    RelativeTimePosition: str | None = None
    AbsoluteTimePosition: str | None = None
    RelativeCounterPosition: str | None = None
    AbsoluteCounterPosition: str | None = None
    CurrentTransportActions: str | None = None

InstanceIDRenderingControl

Bases: BaseModel

BaseModel for part of the DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
109
110
111
112
113
114
115
116
117
118
119
120
class InstanceIDRenderingControl(BaseModel, extra="allow"):
    """BaseModel for part of the DLNA payload."""

    val: str
    Mute: StateVariable
    Channel: StateVariable | None = None
    Equalizer: StateVariable | None = None
    # There's a typo in the schema, this is correct for some payloads -.-
    Equaluzer: StateVariable | None = None
    Volume: StateVariable
    PresetNameList: str | None = None
    TimeStamp: str | None = None

LastChange

Bases: BaseModel

BaseModel for the DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
class LastChange(BaseModel, extra="allow"):
    """BaseModel for the DLNA payload."""

    Event: Any

    @classmethod
    def parse(cls, payload: dict[Literal["Event"], object]) -> LastChange:
        """Parse a `LastChange` model from the payload dictionary.

        Args:
            payload (Dict[str, Any]): the DLNA DMR payload

        Returns:
            LastChange: The parsed `Case`.

        Raises:
            TypeError: if the payload isn't a dict
            ValueError: if more than just "Event" is in the payload
        """
        if not isinstance(payload, dict):
            raise TypeError(f"Expected a dict, got {type(payload)!r}")

        payload = payload.copy()

        event = payload.pop("Event")

        if payload:
            raise ValueError(
                f"Extra fields not permitted: {list(payload.keys())!r}",
            )

        return cls(Event=event)
parse(payload) classmethod

Parse a LastChange model from the payload dictionary.

Parameters:

Name Type Description Default
payload Dict[str, Any]

the DLNA DMR payload

required

Returns:

Name Type Description
LastChange LastChange

The parsed Case.

Raises:

Type Description
TypeError

if the payload isn't a dict

ValueError

if more than just "Event" is in the payload

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
@classmethod
def parse(cls, payload: dict[Literal["Event"], object]) -> LastChange:
    """Parse a `LastChange` model from the payload dictionary.

    Args:
        payload (Dict[str, Any]): the DLNA DMR payload

    Returns:
        LastChange: The parsed `Case`.

    Raises:
        TypeError: if the payload isn't a dict
        ValueError: if more than just "Event" is in the payload
    """
    if not isinstance(payload, dict):
        raise TypeError(f"Expected a dict, got {type(payload)!r}")

    payload = payload.copy()

    event = payload.pop("Event")

    if payload:
        raise ValueError(
            f"Extra fields not permitted: {list(payload.keys())!r}",
        )

    return cls(Event=event)

LastChangeAVTransport

Bases: LastChange

BaseModel for an AVTransport DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
171
172
173
174
class LastChangeAVTransport(LastChange):
    """BaseModel for an AVTransport DLNA payload."""

    Event: EventAVTransport

LastChangeRenderingControl

Bases: LastChange

BaseModel for a RenderingControl DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
177
178
179
180
class LastChangeRenderingControl(LastChange):
    """BaseModel for a RenderingControl DLNA payload."""

    Event: EventRenderingControl

StateVariable

Bases: BaseModel

BaseModel for state variables in DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
38
39
40
41
42
class StateVariable(BaseModel, extra="allow"):
    """BaseModel for state variables in DLNA payload."""

    channel: str
    val: str

TrackMetaData

Bases: BaseModel

BaseModel for part of the DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
72
73
74
75
class TrackMetaData(BaseModel, extra="allow"):
    """BaseModel for part of the DLNA payload."""

    item: TrackMetaDataItem

TrackMetaDataItem

Bases: BaseModel

BaseModel for part of the DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class TrackMetaDataItem(BaseModel, extra="allow"):
    """BaseModel for part of the DLNA payload."""

    id: str
    song_subid: str | None = Field(None, alias="song:subid")
    song_description: str | None = Field(None, alias="song:description")
    song_skiplimit: str | None = Field(None, alias="song:skiplimit")
    song_id: str | None = Field(None, alias="song:id")
    song_like: str | None = Field(None, alias="song:like")
    song_singerid: str | None = Field(None, alias="song:singerid")
    song_albumid: str | None = Field(None, alias="song:albumid")
    res: CurrentTrackMetaDataItemRes
    dc_title: str | None = Field(None, alias="dc:title")
    dc_creator: str | None = Field(None, alias="dc:creator")
    upnp_artist: str | None = Field(None, alias="upnp:artist")
    upnp_album: str | None = Field(None, alias="upnp:album")
    upnp_albumArtURI: str | None = Field(None, alias="upnp:albumArtURI")  # noqa: N815

YamahaYas209

Class for consuming information from a YAS-209 in real time.

Callback functions can be provided, as well as the option to start the listener immediately.

Parameters:

Name Type Description Default
ip str

the IP address of the YAS-209

required
on_event Callable[[YamahaYas209, Event], None]

a callback function to be called when an event is received. Defaults to None.

None
start_listener bool

whether to start the listener

False
on_volume_update Callable[[YamahaYas209, int], None]

a callback function to be called when the volume is updated. Defaults to None.

None
on_track_update Callable[[YamahaYas209, Track], None]

a callback function to be called when the track is updated. Defaults to None.

None
on_state_update Callable[[YamahaYas209, State], None]

a callback function to be called when the state is updated. Defaults to None.

None
logging bool

whether to log events. Defaults to False.

True
listen_ip str

the IP address to listen on. Defaults to None.

None
listen_port int

the port to listen on. Defaults to None.

None
source_port int

the port to use for the source. Defaults to None.

None
resubscribe_seconds int

the number of seconds between each resubscription. Defaults to 2 minutes.

120
Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
 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
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
class YamahaYas209:
    """Class for consuming information from a YAS-209 in real time.

    Callback functions can be provided, as well as the option to start the
    listener immediately.

    Args:
        ip (str): the IP address of the YAS-209
        on_event (Callable[[YamahaYas209, Event], None], optional): a callback
            function to be called when an event is received. Defaults to None.
        start_listener (bool, optional): whether to start the listener
        on_volume_update (Callable[[YamahaYas209, int], None], optional): a
            callback function to be called when the volume is updated. Defaults
            to None.
        on_track_update (Callable[[YamahaYas209, Track], None], optional): a
            callback function to be called when the track is updated. Defaults
            to None.
        on_state_update (Callable[[YamahaYas209, State], None], optional): a
            callback function to be called when the state is updated. Defaults
            to None.
        logging (bool, optional): whether to log events. Defaults to False.
        listen_ip (str, optional): the IP address to listen on. Defaults to
            None.
        listen_port (int, optional): the port to listen on. Defaults to None.
        source_port (int, optional): the port to use for the source. Defaults
            to None.
        resubscribe_seconds (int, optional): the number of seconds between each
            resubscription. Defaults to 2 minutes.
    """

    SUBSCRIPTION_SERVICES = (
        Yas209Service.AVT.service_id,
        Yas209Service.RC.service_id,
    )

    LAST_CHANGE_PAYLOAD_PARSERS: ClassVar[
        dict[str, Callable[[dict[Literal["Event"], object]], LastChange]]
    ] = {
        Yas209Service.AVT.service_id: LastChangeAVTransport.parse,
        Yas209Service.RC.service_id: LastChangeRenderingControl.parse,
    }

    class EventPayloadInfo(TypedDict):
        """Info for the payload sent to the `on_event` callback."""

        timestamp: datetime
        service_id: str
        service_type: str
        last_change: LastChange
        other_xml_payloads: dict[str, Any]

    def __init__(  # noqa: PLR0913
        self,
        ip: str,
        *,
        on_event: Callable[[EventPayloadInfo], None] | None = None,
        start_listener: bool = False,
        on_volume_update: Callable[[float], None] | None = None,
        on_track_update: Callable[[CurrentTrack.Info], None] | None = None,
        on_state_update: Callable[[str], None] | None = None,
        logging: bool = True,
        listen_ip: str | None = None,
        listen_port: int | None = None,
        source_port: int | None = None,
        resubscribe_seconds: int = 120,
    ):
        self.ip = ip
        self.on_event = on_event

        # noinspection HttpUrlsUsage
        self.description_url = f"http://{ip}:49152/description.xml"

        self.on_volume_update = on_volume_update
        self.on_track_update = on_track_update
        self.on_state_update = on_state_update

        self._current_track: CurrentTrack
        self._state: Yas209State
        self._volume_level: float

        self._listening = False

        self.device: UpnpDevice

        self._logging = logging
        self._listen_ip = listen_ip
        self._listen_port = listen_port
        self._source_port = source_port or 0

        self.resubscribe_seconds = resubscribe_seconds

        self._active_service_ids: list[str] = []

        if self._listen_ip is not None and self._listen_port is None:
            raise ValueError(
                "Argument `listen_port` cannot be None when `listen_ip` is not None:"
                f" {self._listen_ip!r}",
            )

        if start_listener:
            self.listen()

    def listen(self) -> None:
        """Start the listener."""
        if self._logging:
            LOGGER.info("Starting listener")

        if self._listening:
            if self._logging:
                LOGGER.debug(
                    "Already listening to '%s', returning immediately",
                    "', '".join(self._active_service_ids),
                )
            return

        worker_exception: BaseException | None = None

        def _worker() -> None:
            nonlocal worker_exception
            try:
                new_event_loop().run_until_complete(self._subscribe())
            except Exception as exc:
                worker_exception = exc

        listener_thread = Thread(target=_worker)
        listener_thread.start()

        while not self._listening and worker_exception is None:
            sleep(0.01)

        if isinstance(worker_exception, BaseException):
            raise worker_exception

        if self._logging:
            LOGGER.debug(
                "Listen action complete, now subscribed to '%s'",
                "', '".join(self._active_service_ids),
            )

    def on_event_wrapper(
        self,
        service: UpnpService,
        service_variables: Sequence[UpnpStateVariable[str]],
    ) -> None:
        """Wrap the `on_event` callback to process the XML payload(s) first.

        Args:
            service (UpnpService): the service which has sent an update
            service_variables (list): a list of state variables that have updated
        """

        xml_payloads: dict[str, object] = {sv.name: sv.value for sv in service_variables}

        # Convert any nested XML into JSON
        self._parse_xml_dict(xml_payloads)

        last_change = self.LAST_CHANGE_PAYLOAD_PARSERS[service.service_id](
            xml_payloads.pop("LastChange"),  # type: ignore[arg-type]
        )

        event_payload: YamahaYas209.EventPayloadInfo = {
            "timestamp": datetime.now(UTC),
            "service_id": service.service_id,
            "service_type": service.service_type,
            "last_change": last_change,
            "other_xml_payloads": xml_payloads,
        }

        if service.service_id == "urn:upnp-org:serviceId:AVTransport":
            if last_change.Event.InstanceID.TransportState != self.state.name:
                self.set_state(
                    Yas209State[last_change.Event.InstanceID.TransportState],
                    local_only=True,
                )
            if last_change.Event.InstanceID.CurrentTrackMetaData is None:
                self.current_track = CurrentTrack.null_track()
            else:
                self.current_track = CurrentTrack.from_last_change(last_change)
        elif service.service_id == "urn:upnp-org:serviceId:RenderingControl":
            # The DLNA payload has volume as a string value between 0 and 100
            self.set_volume_level(
                float(last_change.Event.InstanceID.Volume.val) / 100,
                local_only=True,
            )

        if self.on_event is not None:
            self.on_event(event_payload)

    @_needs_device
    async def _subscribe(self) -> None:  # noqa: PLR0912
        """Subscribe to service(s) and output updates."""
        # start notify server/event handler
        local_ip = get_local_ip(self.device.device_url)
        source = (local_ip, self._source_port)

        callback_url = (
            None
            if self._listen_port is None
            else f"http://{self._listen_ip or local_ip}:{self._listen_port}/notify"
        )
        server = AiohttpNotifyServer(
            self.device.requester,
            source=source,
            callback_url=callback_url,
        )
        await server.async_start_server()

        if self._logging:
            LOGGER.debug(
                dedent(
                    """
            Listen IP:          %s
            Listen Port:        %s
            Source IP:          %s
            Source Port:        %s
            Callback URL:       %s
            Server Listen IP:   %s
            Server Listen Port: %s
            """,
                ),
                self._listen_ip,
                str(self._listen_port),
                local_ip,
                str(self._source_port),
                str(callback_url),
                server.listen_ip,
                server.listen_port,
            )

        # create service subscriptions
        failed_subscriptions = []
        for service in self.device.services.values():
            if service.service_id not in self.SUBSCRIPTION_SERVICES:
                continue

            service.on_event = self.on_event_wrapper
            try:
                await server.event_handler.async_subscribe(service)
                self._active_service_ids.append(service.service_id)
                LOGGER.info("Subscribed to %s", service.service_id)
            except UpnpCommunicationError:
                if self._logging:
                    LOGGER.exception(
                        "Unable to subscribe to %s",
                        service.service_id,
                    )
                failed_subscriptions.append(service)

        self._listening = True

        # keep the webservice running (force resubscribe)
        while self._listening:
            for _ in range(self.resubscribe_seconds):
                if not self._listening:
                    if self._logging:
                        LOGGER.debug("Exiting listener loop")
                    break
                await async_sleep(1)

            # The break above only covers the for loop, this is for the while loop
            if not self._listening:
                break

            LOGGER.debug("Resubscribing to all services")
            await server.event_handler.async_resubscribe_all()

            services_to_remove = []
            for service in failed_subscriptions:
                try:
                    if self._logging:
                        LOGGER.debug(
                            "Attempting to create originally failed subscription for"
                            " %s",
                            service.service_id,
                        )
                    await server.event_handler.async_subscribe(service)
                    self._active_service_ids.append(service.service_id)
                    services_to_remove.append(service)
                except UpnpCommunicationError as exc:  # noqa: PERF203
                    log_message = (
                        f"Still unable to subscribe to {service.service_id}: {exc!r}"
                    )

                    if self._logging:
                        LOGGER.exception(log_message)
                    else:
                        # Should still log this exception, regardless
                        LOGGER.warning(log_message)

            # This needs to be separate because `.remove` is the cleanest way to remove
            # the items, but can't be done within the loop, and I can't `deepcopy`
            # `failed_subscriptions` and its threaded content
            for service in services_to_remove:
                failed_subscriptions.remove(service)

        if self._logging:
            LOGGER.debug(
                "Exiting subscription loop, `self._listening` is `%s`",
                str(self._listening),
            )

    def _call_service_action(
        self,
        service: Yas209Service,
        action: str,
        callback: Callable[[Mapping[str, object]], None] | None = None,
        **call_kwargs: str | int,
    ) -> dict[str, Any] | None:
        if action not in service.actions:
            raise ValueError(
                f"Unexpected action {action!r} for service {service.value!r}. "
                f"""Must be one of '{"', '".join(service.actions)}'""",
            )

        @_needs_device
        async def _worker(_: YamahaYas209) -> Mapping[str, Any]:
            res: Mapping[str, Any] = (
                await self.device.services[service.service_name]
                .action(action)
                .async_call(**call_kwargs)
            )

            if callback is not None:
                callback(res)

            return res

        return run(_worker(self))  # type: ignore[no-any-return]

    @staticmethod
    def _parse_xml_dict(xml_dict: MutableMapping[str, object]) -> None:
        """Convert XML to JSON within dict in place.

        Parse a dictionary where some values are/could be XML strings, and unpack
        the XML into JSON within the dict

        Args:
            xml_dict (dict): the dictionary to parse
        """

        pattern = re_compile(r"&(?!(amp|apos|lt|gt|quot);)")

        traverse_dict(
            xml_dict,
            target_type=str,
            target_processor_func=lambda val, **_: parse_xml(  # type: ignore[arg-type]
                pattern.sub("&amp;", val),
                attr_prefix="",
                cdata_key="text",
            ),
            single_keys_to_remove=["val", "DIDL-Lite"],
        )

    # TODO: @on_exception()
    def pause(self) -> None:
        """Pause the current media."""
        self._call_service_action(Yas209Service.AVT, "Pause", InstanceID=0)

    def play(self) -> None:
        """Play the current media."""
        self._call_service_action(Yas209Service.AVT, "Play", InstanceID=0, Speed="1")

    def play_pause(self) -> None:
        """Toggle the playing/paused state."""
        if self.state == Yas209State.PLAYING:
            self.pause()
        else:
            self.play()

    def mute(self) -> None:
        """Mute."""
        self._call_service_action(
            Yas209Service.RC,
            "SetMute",
            InstanceID=0,
            Channel="Master",
            DesiredMute=True,
        )

    def next_track(self) -> None:
        """Skip to the next track."""
        self._call_service_action(Yas209Service.AVT, "Next", InstanceID=0)

    def previous_track(self) -> None:
        """Go to the previous track."""
        self._call_service_action(Yas209Service.AVT, "Previous", InstanceID=0)

    def set_state(self, value: Yas209State, *, local_only: bool = False) -> None:
        """Set the state to the given value.

        Args:
            value (Yas209State): the new state of the YAS-209
            local_only (bool): only change the local value of the state (i.e. don't
                update the soundbar)

        Raises:
            TypeError: if the value is not a valid state
        """
        if not isinstance(value, Yas209State):
            raise TypeError("Expected a Yas209State instance.")

        self._state = value

        if not local_only:
            func = {
                Yas209State.PLAYING: self.play,
                Yas209State.PAUSED_PLAYBACK: self.pause,
                Yas209State.STOPPED: self.stop,
            }.get(value)

            if func is not None:
                func()

        if self.on_state_update is not None:
            self.on_state_update(self._state.value)

    def set_volume_level(self, value: float, *, local_only: bool = False) -> None:
        """Set the soundbar's volume level.

        Args:
            value (float): the new volume level, as a float between 0 and 1
            local_only (bool): only change the local value of the volume level (i.e.
                don't update the soundbar)

        Raises:
            ValueError: if the value is not between 0 and 1
        """

        if not 0 <= value <= 1:
            raise ValueError("Volume level must be between 0 and 1")

        self._volume_level = round(value, 2)

        if not local_only:
            self._call_service_action(
                Yas209Service.RC,
                "SetVolume",
                InstanceID=0,
                Channel="Master",
                DesiredVolume=int(self._volume_level * 100),
            )

        if self.on_volume_update is not None:
            self.on_volume_update(self._volume_level)

    def stop(self) -> None:
        """Stop whatever is currently playing."""
        self._call_service_action(Yas209Service.AVT, "Stop", InstanceID=0, Speed="1")

    def stop_listening(self) -> None:
        """Stop the event listener."""
        if self._logging:
            LOGGER.debug(
                "Stopping event listener (will take <= %i seconds)",
                self.resubscribe_seconds,
            )

        self._listening = False

    def unmute(self) -> None:
        """Unmute."""
        self._call_service_action(
            Yas209Service.RC,
            "SetMute",
            InstanceID=0,
            Channel="Master",
            DesiredMute=False,
        )

    def volume_down(self) -> None:
        """Decrease the volume by 2 points."""
        self.set_volume_level(round(self.volume_level - 0.02, 2))

    def volume_up(self) -> None:
        """Increase the volume by 2 points."""
        self.set_volume_level(round(self.volume_level + 0.02, 2))

    @property
    def album_art_uri(self) -> str | None:
        """Album art URI for the currently playing media.

        Returns:
            str: URL for the current album's artwork
        """
        return self.current_track.album_art_uri

    @property
    def current_track(self) -> CurrentTrack:
        """Currently playing track.

        Returns:
            dict: the current track's info
        """
        if not hasattr(self, "_current_track"):
            media_info = self.get_media_info()
            self._current_track = CurrentTrack.from_get_media_info(
                GetMediaInfoResponse.model_validate(media_info),
            )

        return self._current_track

    @current_track.setter
    def current_track(self, value: CurrentTrack) -> None:
        """Set the current track.

        Args:
            value (CurrentTrack): the new current track

        Raises:
            TypeError: if the value is not a CurrentTrack instance
        """

        if not isinstance(value, CurrentTrack):
            raise TypeError("Expected a CurrentTrack instance.")

        self._current_track = value

        if self.on_track_update is not None:
            self.on_track_update(value.json)

    @property
    def is_listening(self) -> bool:
        """Whether the event listener is running.

        Returns:
            bool: whether the event listener is running
        """
        return self._listening

    @property
    def media_album_name(self) -> str | None:
        """Name of the current album.

        Returns:
            str: the current media_title
        """
        return self.current_track.media_album_name

    @property
    def media_artist(self) -> str | None:
        """Currently playing artist.

        Returns:
            str: the current media_artist
        """
        return self.current_track.media_artist

    @property
    def media_duration(self) -> float | None:
        """Duration of current playing media in seconds.

        Returns:
            str: the current media_duration
        """
        return self.current_track.media_duration

    def get_media_info(self) -> dict[str, Any]:
        """Get the current media info from the soundbar.

        Returns:
            dict: the response in JSON form
        """

        media_info = (
            self._call_service_action(Yas209Service.AVT, "GetMediaInfo", InstanceID=0)
            or {}
        )

        self._parse_xml_dict(media_info)

        return media_info

    @property
    def media_title(self) -> str | None:
        """Currently playing media title.

        Returns:
            str: the current media_album_name
        """
        return self.current_track.media_title

    @property
    def state(self) -> Yas209State:
        """Current state of the soundbar.

        Returns:
            Yas209State: the current state of the YAS-209 (e.g. playing, stopped)
        """
        if hasattr(self, "_state"):
            return self._state

        return Yas209State.UNKNOWN

    @property
    def volume_level(self) -> float:
        """Current volume level.

        Returns:
            float: the current volume level
        """
        if not hasattr(self, "_volume_level"):
            res = (
                self._call_service_action(
                    Yas209Service.RC,
                    "GetVolume",
                    InstanceID=0,
                    Channel="Master",
                )
                or {}
            )

            self._volume_level = float(res.get("CurrentVolume", 0) / 100)

        return self._volume_level
album_art_uri: str | None property

Album art URI for the currently playing media.

Returns:

Name Type Description
str str | None

URL for the current album's artwork

current_track: CurrentTrack property writable

Currently playing track.

Returns:

Name Type Description
dict CurrentTrack

the current track's info

is_listening: bool property

Whether the event listener is running.

Returns:

Name Type Description
bool bool

whether the event listener is running

media_album_name: str | None property

Name of the current album.

Returns:

Name Type Description
str str | None

the current media_title

media_artist: str | None property

Currently playing artist.

Returns:

Name Type Description
str str | None

the current media_artist

media_duration: float | None property

Duration of current playing media in seconds.

Returns:

Name Type Description
str float | None

the current media_duration

media_title: str | None property

Currently playing media title.

Returns:

Name Type Description
str str | None

the current media_album_name

state: Yas209State property

Current state of the soundbar.

Returns:

Name Type Description
Yas209State Yas209State

the current state of the YAS-209 (e.g. playing, stopped)

volume_level: float property

Current volume level.

Returns:

Name Type Description
float float

the current volume level

EventPayloadInfo

Bases: TypedDict

Info for the payload sent to the on_event callback.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
578
579
580
581
582
583
584
585
class EventPayloadInfo(TypedDict):
    """Info for the payload sent to the `on_event` callback."""

    timestamp: datetime
    service_id: str
    service_type: str
    last_change: LastChange
    other_xml_payloads: dict[str, Any]
get_media_info()

Get the current media info from the soundbar.

Returns:

Name Type Description
dict dict[str, Any]

the response in JSON form

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
def get_media_info(self) -> dict[str, Any]:
    """Get the current media info from the soundbar.

    Returns:
        dict: the response in JSON form
    """

    media_info = (
        self._call_service_action(Yas209Service.AVT, "GetMediaInfo", InstanceID=0)
        or {}
    )

    self._parse_xml_dict(media_info)

    return media_info
listen()

Start the listener.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
def listen(self) -> None:
    """Start the listener."""
    if self._logging:
        LOGGER.info("Starting listener")

    if self._listening:
        if self._logging:
            LOGGER.debug(
                "Already listening to '%s', returning immediately",
                "', '".join(self._active_service_ids),
            )
        return

    worker_exception: BaseException | None = None

    def _worker() -> None:
        nonlocal worker_exception
        try:
            new_event_loop().run_until_complete(self._subscribe())
        except Exception as exc:
            worker_exception = exc

    listener_thread = Thread(target=_worker)
    listener_thread.start()

    while not self._listening and worker_exception is None:
        sleep(0.01)

    if isinstance(worker_exception, BaseException):
        raise worker_exception

    if self._logging:
        LOGGER.debug(
            "Listen action complete, now subscribed to '%s'",
            "', '".join(self._active_service_ids),
        )
mute()

Mute.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
905
906
907
908
909
910
911
912
913
def mute(self) -> None:
    """Mute."""
    self._call_service_action(
        Yas209Service.RC,
        "SetMute",
        InstanceID=0,
        Channel="Master",
        DesiredMute=True,
    )
next_track()

Skip to the next track.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
915
916
917
def next_track(self) -> None:
    """Skip to the next track."""
    self._call_service_action(Yas209Service.AVT, "Next", InstanceID=0)
on_event_wrapper(service, service_variables)

Wrap the on_event callback to process the XML payload(s) first.

Parameters:

Name Type Description Default
service UpnpService

the service which has sent an update

required
service_variables list

a list of state variables that have updated

required
Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
def on_event_wrapper(
    self,
    service: UpnpService,
    service_variables: Sequence[UpnpStateVariable[str]],
) -> None:
    """Wrap the `on_event` callback to process the XML payload(s) first.

    Args:
        service (UpnpService): the service which has sent an update
        service_variables (list): a list of state variables that have updated
    """

    xml_payloads: dict[str, object] = {sv.name: sv.value for sv in service_variables}

    # Convert any nested XML into JSON
    self._parse_xml_dict(xml_payloads)

    last_change = self.LAST_CHANGE_PAYLOAD_PARSERS[service.service_id](
        xml_payloads.pop("LastChange"),  # type: ignore[arg-type]
    )

    event_payload: YamahaYas209.EventPayloadInfo = {
        "timestamp": datetime.now(UTC),
        "service_id": service.service_id,
        "service_type": service.service_type,
        "last_change": last_change,
        "other_xml_payloads": xml_payloads,
    }

    if service.service_id == "urn:upnp-org:serviceId:AVTransport":
        if last_change.Event.InstanceID.TransportState != self.state.name:
            self.set_state(
                Yas209State[last_change.Event.InstanceID.TransportState],
                local_only=True,
            )
        if last_change.Event.InstanceID.CurrentTrackMetaData is None:
            self.current_track = CurrentTrack.null_track()
        else:
            self.current_track = CurrentTrack.from_last_change(last_change)
    elif service.service_id == "urn:upnp-org:serviceId:RenderingControl":
        # The DLNA payload has volume as a string value between 0 and 100
        self.set_volume_level(
            float(last_change.Event.InstanceID.Volume.val) / 100,
            local_only=True,
        )

    if self.on_event is not None:
        self.on_event(event_payload)
pause()

Pause the current media.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
890
891
892
def pause(self) -> None:
    """Pause the current media."""
    self._call_service_action(Yas209Service.AVT, "Pause", InstanceID=0)
play()

Play the current media.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
894
895
896
def play(self) -> None:
    """Play the current media."""
    self._call_service_action(Yas209Service.AVT, "Play", InstanceID=0, Speed="1")
play_pause()

Toggle the playing/paused state.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
898
899
900
901
902
903
def play_pause(self) -> None:
    """Toggle the playing/paused state."""
    if self.state == Yas209State.PLAYING:
        self.pause()
    else:
        self.play()
previous_track()

Go to the previous track.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
919
920
921
def previous_track(self) -> None:
    """Go to the previous track."""
    self._call_service_action(Yas209Service.AVT, "Previous", InstanceID=0)
set_state(value, *, local_only=False)

Set the state to the given value.

Parameters:

Name Type Description Default
value Yas209State

the new state of the YAS-209

required
local_only bool

only change the local value of the state (i.e. don't update the soundbar)

False

Raises:

Type Description
TypeError

if the value is not a valid state

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
def set_state(self, value: Yas209State, *, local_only: bool = False) -> None:
    """Set the state to the given value.

    Args:
        value (Yas209State): the new state of the YAS-209
        local_only (bool): only change the local value of the state (i.e. don't
            update the soundbar)

    Raises:
        TypeError: if the value is not a valid state
    """
    if not isinstance(value, Yas209State):
        raise TypeError("Expected a Yas209State instance.")

    self._state = value

    if not local_only:
        func = {
            Yas209State.PLAYING: self.play,
            Yas209State.PAUSED_PLAYBACK: self.pause,
            Yas209State.STOPPED: self.stop,
        }.get(value)

        if func is not None:
            func()

    if self.on_state_update is not None:
        self.on_state_update(self._state.value)
set_volume_level(value, *, local_only=False)

Set the soundbar's volume level.

Parameters:

Name Type Description Default
value float

the new volume level, as a float between 0 and 1

required
local_only bool

only change the local value of the volume level (i.e. don't update the soundbar)

False

Raises:

Type Description
ValueError

if the value is not between 0 and 1

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
def set_volume_level(self, value: float, *, local_only: bool = False) -> None:
    """Set the soundbar's volume level.

    Args:
        value (float): the new volume level, as a float between 0 and 1
        local_only (bool): only change the local value of the volume level (i.e.
            don't update the soundbar)

    Raises:
        ValueError: if the value is not between 0 and 1
    """

    if not 0 <= value <= 1:
        raise ValueError("Volume level must be between 0 and 1")

    self._volume_level = round(value, 2)

    if not local_only:
        self._call_service_action(
            Yas209Service.RC,
            "SetVolume",
            InstanceID=0,
            Channel="Master",
            DesiredVolume=int(self._volume_level * 100),
        )

    if self.on_volume_update is not None:
        self.on_volume_update(self._volume_level)
stop()

Stop whatever is currently playing.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
981
982
983
def stop(self) -> None:
    """Stop whatever is currently playing."""
    self._call_service_action(Yas209Service.AVT, "Stop", InstanceID=0, Speed="1")
stop_listening()

Stop the event listener.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
985
986
987
988
989
990
991
992
993
def stop_listening(self) -> None:
    """Stop the event listener."""
    if self._logging:
        LOGGER.debug(
            "Stopping event listener (will take <= %i seconds)",
            self.resubscribe_seconds,
        )

    self._listening = False
unmute()

Unmute.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
 995
 996
 997
 998
 999
1000
1001
1002
1003
def unmute(self) -> None:
    """Unmute."""
    self._call_service_action(
        Yas209Service.RC,
        "SetMute",
        InstanceID=0,
        Channel="Master",
        DesiredMute=False,
    )
volume_down()

Decrease the volume by 2 points.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
1005
1006
1007
def volume_down(self) -> None:
    """Decrease the volume by 2 points."""
    self.set_volume_level(round(self.volume_level - 0.02, 2))
volume_up()

Increase the volume by 2 points.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
1009
1010
1011
def volume_up(self) -> None:
    """Increase the volume by 2 points."""
    self.set_volume_level(round(self.volume_level + 0.02, 2))

Yas209Service

Bases: Enum

Enumeration for available YAS-209 services.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
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
class Yas209Service(Enum):
    """Enumeration for available YAS-209 services."""

    AVT = (
        "AVTransport",
        "urn:upnp-org:serviceId:AVTransport",
        "urn:schemas-upnp-org:service:AVTransport:1",
        (
            "GetCurrentTransportActions",
            "GetDeviceCapabilities",
            "GetInfoEx",
            "GetMediaInfo",
            "GetPlayType",
            "GetPositionInfo",
            "GetTransportInfo",
            "GetTransportSettings",
            "Next",
            "Pause",
            "Play",
            "Previous",
            "Seek",
            "SeekBackward",
            "SeekForward",
            "SetAVTransportURI",
            "SetPlayMode",
            "Stop",
        ),
    )
    CM = (
        "ConnectionManager",
        "urn:upnp-org:serviceId:ConnectionManager",
        "urn:schemas-upnp-org:service:ConnectionManager:1",
        (
            "GetCurrentConnectionIDs",
            "GetCurrentConnectionInfo",
            "GetProtocolInfo",
        ),
    )
    PQ = (
        "PlayQueue",
        "urn:wiimu-com:serviceId:PlayQueue",
        "urn:schemas-wiimu-com:service:PlayQueue:1",
        (
            "AppendQueue",
            "AppendTracksInQueue",
            "AppendTracksInQueueEx",
            "BackUpQueue",
            "BrowseQueue",
            "CreateQueue",
            "DeleteActionQueue",
            "DeleteQueue",
            "GetKeyMapping",
            "GetQueueIndex",
            "GetQueueLoopMode",
            "GetQueueOnline",
            "GetUserAccountHistory",
            "GetUserFavorites",
            "GetUserInfo",
            "PlayQueueWithIndex",
            "RemoveTracksInQueue",
            "ReplaceQueue",
            "SearchQueueOnline",
            "SetKeyMapping",
            "SetQueueLoopMode",
            "SetQueuePolicy",
            "SetQueueRecord",
            "SetSongsRecord",
            "SetSpotifyPreset",
            "SetUserFavorites",
            "UserLogin",
            "UserLogout",
            "UserRegister",
        ),
    )
    Q_PLAY = (
        "QPlay",
        "urn:tencent-com:serviceId:QPlay",
        "urn:schemas-tencent-com:service:QPlay:1",
        (
            "GetMaxTracks",
            "GetTracksCount",
            "GetTracksInfo",
            "InsertTracks",
            "QPlayAuth",
            "RemoveAllTracks",
            "RemoveTracks",
            "SetNetwork",
            "SetTracksInfo",
        ),
    )
    RC = (
        "RenderingControl",
        "urn:upnp-org:serviceId:RenderingControl",
        "urn:schemas-upnp-org:service:RenderingControl:1",
        (
            "DeleteAlarmQueue",
            "GetAlarmQueue",
            "GetChannel",
            "GetControlDeviceInfo",
            "GetEqualizer",
            "GetMute",
            "GetSimpleDeviceInfo",
            "GetVolume",
            "ListPresets",
            "MultiPlaySlaveMask",
            "SelectPreset",
            "SetAlarmQueue",
            "SetChannel",
            "SetDeviceName",
            "SetEqualizer",
            "SetMute",
            "SetVolume",
            "StreamServicesCapability",
        ),
    )

    def __init__(
        self,
        value: str,
        service_id: str,
        service_name: str,
        actions: tuple[str],
    ):
        self._value_ = value
        self.service_id = service_id
        self.service_name = service_name
        self.actions = actions

Yas209State

Bases: Enum

Enumeration for states as they come in the DLNA payload.

Source code in wg_utilities/devices/yamaha_yas_209/yamaha_yas_209.py
352
353
354
355
356
357
358
359
360
361
362
363
class Yas209State(Enum):
    """Enumeration for states as they come in the DLNA payload."""

    PLAYING = "playing", "Play"
    PAUSED_PLAYBACK = "paused", "Pause"
    STOPPED = "off", "Stop"
    NO_MEDIA_PRESENT = "idle", None
    UNKNOWN = "unknown", None

    def __init__(self, value: str, action: str | None):
        self._value_ = value
        self.action = action