Skip to content

Commit ea18bfe

Browse files
Revert all changes to spot connect meta
1 parent 090c9c9 commit ea18bfe

File tree

2 files changed

+71
-79
lines changed

2 files changed

+71
-79
lines changed

streams/spot_connect_meta.py

Lines changed: 67 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ class Event:
139139
data: Union[None, Track, PlayChange, VolumeChange, SeekChange, ValueChange] = None
140140

141141
@staticmethod
142-
def from_json(parent: "SpotifyMetadataReader", json_data: dict) -> "Event":
142+
def from_json(json_data: dict) -> "Event":
143143
"""Create an Event object from a JSON payload"""
144144
e = Event(event_type=json_data["type"])
145145
if e.event_type in ["active", "inactive"]:
@@ -160,78 +160,71 @@ def from_json(parent: "SpotifyMetadataReader", json_data: dict) -> "Event":
160160
return e
161161

162162

163-
class SpotifyMetadataReader:
164-
165-
def __init__(self, url, metadata_file, debug=False):
166-
self.url: str = url
167-
self.metadata_file: str = metadata_file
168-
self.debug: bool = debug
169-
self._api_port: int = 3678 + int([char for char in metadata_file if char.isdigit()][0])
170-
171-
def read_metadata(self) -> Optional[Status]:
172-
"""
173-
Reads metadata from the given URL and writes it to the specified metadata file.
174-
If the metadata file already exists, it will be overwritten.
175-
"""
176-
endpoint = self.url + "/status"
177-
178-
# Send a GET request to the URL to retrieve the metadata
179-
response = requests.get(endpoint, timeout=2)
180-
181-
# Check if the request was successful
182-
if response.status_code == 200:
183-
# Parse the metadata from the response
184-
return Status.from_dict(response.json())
185-
elif response.status_code == 204:
186-
# the metadata isn't populated yet
187-
return Status(stopped=True)
188-
else:
189-
# If the request failed, print an error message
190-
print(f"Failed to retrieve metadata from {endpoint}. Status code: {response.status_code}")
191-
return Status()
192-
193-
def watch_metadata(self) -> None:
194-
"""
195-
Watches the api at `url` for metadata updates and writes the current state to `metadata_file`.
196-
If the metadata file already exists, it will be overwritten.
197-
"""
198-
# Get the websocket-based event updates
199-
ws_events = self.url.replace("http://", "ws://") + "/events"
200-
try:
201-
# read the initial state
202-
metadata = self.read_metadata()
203-
with open(self.metadata_file, 'w', encoding='utf8') as mf:
204-
mf.write(json.dumps(asdict(metadata)))
205-
if self.debug:
206-
print(f"Initial metadata: {metadata}")
207-
# Connect to the websocket and listen for state changes
208-
with connect(ws_events, open_timeout=5) as websocket:
209-
while True:
210-
try:
211-
msg = websocket.recv()
212-
if self.debug:
213-
print(f"Received: {msg}")
214-
event = Event.from_json(self, json.loads(msg))
215-
if event.event_type == "metadata":
216-
metadata.track = event.data
217-
elif event.event_type == "playing":
218-
metadata.stopped = False
219-
metadata.paused = False
220-
elif event.event_type == "paused":
221-
metadata.paused = True
222-
elif event.event_type == "stopped":
223-
metadata.stopped = True
224-
metadata.track = Track()
225-
else:
226-
continue
227-
with open(args.metadata_file, 'w', encoding='utf8') as mf:
228-
mf.write(json.dumps(asdict(metadata)))
229-
except (KeyError, ConnectionClosed, json.JSONDecodeError) as e:
230-
print(f"Error: {e}")
231-
break
232-
except (OSError, InvalidHandshake, TimeoutError) as e:
233-
print(f"Error: {e}")
234-
return
163+
def read_metadata(url) -> Optional[Track]:
164+
"""
165+
Reads metadata from the given URL and writes it to the specified metadata file.
166+
If the metadata file already exists, it will be overwritten.
167+
"""
168+
endpoint = url + "/status"
169+
170+
# Send a GET request to the URL to retrieve the metadata
171+
response = requests.get(endpoint, timeout=2)
172+
173+
# Check if the request was successful
174+
if response.status_code == 200:
175+
# Parse the metadata from the response
176+
return Status.from_dict(response.json())
177+
elif response.status_code == 204:
178+
# the metadata isn't populated yet
179+
return Status(stopped=True)
180+
else:
181+
# If the request failed, print an error message
182+
print(f"Failed to retrieve metadata from {endpoint}. Status code: {response.status_code}")
183+
return Status()
184+
185+
186+
def watch_metadata(url, metadata_file, debug=False) -> None:
187+
"""
188+
Watches the api at `url` for metadata updates and writes the current state to `metadata_file`.
189+
If the metadata file already exists, it will be overwritten.
190+
"""
191+
# Get the websocket-based event updates
192+
ws_events = url.replace("http://", "ws://") + "/events"
193+
try:
194+
# read the initial state
195+
metadata = read_metadata(url)
196+
with open(metadata_file, 'w', encoding='utf8') as mf:
197+
mf.write(json.dumps(asdict(metadata)))
198+
if debug:
199+
print(f"Initial metadata: {metadata}")
200+
# Connect to the websocket and listen for state changes
201+
with connect(ws_events, open_timeout=5) as websocket:
202+
while True:
203+
try:
204+
msg = websocket.recv()
205+
if debug:
206+
print(f"Received: {msg}")
207+
event = Event.from_json(json.loads(msg))
208+
if event.event_type == "metadata":
209+
metadata.track = event.data
210+
elif event.event_type == "playing":
211+
metadata.stopped = False
212+
metadata.paused = False
213+
elif event.event_type == "paused":
214+
metadata.paused = True
215+
elif event.event_type == "stopped":
216+
metadata.stopped = True
217+
metadata.track = Track()
218+
else:
219+
continue
220+
with open(args.metadata_file, 'w', encoding='utf8') as mf:
221+
mf.write(json.dumps(asdict(metadata)))
222+
except (KeyError, ConnectionClosed, json.JSONDecodeError) as e:
223+
print(f"Error: {e}")
224+
break
225+
except (OSError, InvalidHandshake, TimeoutError) as e:
226+
print(f"Error: {e}")
227+
return
235228

236229

237230
if __name__ == "__main__":
@@ -246,7 +239,7 @@ def watch_metadata(self) -> None:
246239

247240
while (True):
248241
try:
249-
SpotifyMetadataReader(args.url, args.metadata_file, args.debug).watch_metadata()
242+
watch_metadata(args.url, args.metadata_file, args.debug)
250243
except (KeyboardInterrupt, SystemExit):
251244
print("Exiting...")
252245
break

streams/spotify_volume_handler.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,11 @@ def get_status(self):
4141

4242
def get_volume(self):
4343
if self.connected_zones:
44-
total_vol_f = 0
45-
for zone in self.connected_zones:
46-
total_vol_f += zone["vol_f"]
44+
total_vol_f = sum([zone["vol_f"] for zone in self.connected_zones])
45+
avg_vol = total_vol_f / len(self.connected_zones)
4746
if self.debug:
48-
print(f"Got AmpliPi volume: {total_vol_f / len(self.connected_zones)}")
49-
return total_vol_f / len(self.connected_zones)
47+
print(f"Got AmpliPi volume: {avg_vol}")
48+
return avg_vol
5049

5150

5251
class SpotifyVolumeHandler:

0 commit comments

Comments
 (0)