-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
101 lines (75 loc) · 2.77 KB
/
main.py
File metadata and controls
101 lines (75 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import os
import time
from fastapi import FastAPI, Request, HTTPException
import asyncio
import pyatv
from pyatv.storage.file_storage import FileStorage
# PAIRING:
# To connect use the pairning function of "atvremote wizard". Next copy or mount the
# .pyatv.conf file from the current user into the root dir of the python app.
os.environ['TZ'] = 'Europe/Berlin'
time.tzset()
app = FastAPI()
async def get_atv(givenId):
"""Add credentials to pyatv device configuration."""
connect: bool = False
if not hasattr(app.state, 'devices'):
app.state.devices = {}
connect = True
elif not givenId in app.state.devices:
connect = True
if connect:
loop = asyncio.get_event_loop()
results = await pyatv.scan(identifier=givenId, loop=loop)
if not results:
raise HTTPException(status_code=404, detail="Device not found")
try:
# Load the same storage that pyatv uses internally (e.g. in atvremote)
storage = FileStorage('.pyatv.conf', loop)
await storage.load()
atv = await pyatv.connect(results[0], loop=loop, storage=storage)
except Exception as ex:
raise HTTPException(status_code=500, detail=f"Failed to connect to device: {ex}")
if not hasattr(app.state, 'devices'):
app.state.devices = {}
app.state.devices[givenId] = atv
return app.state.devices[givenId]
@app.get("/scan")
async def scan():
devices = []
for result in await pyatv.scan(loop=asyncio.get_event_loop()):
devices.append({
"name": result.name,
"identifier": result.identifier,
"address": str(result.address)
})
return {"devices": devices}
@app.get("/playing/{givenId}")
async def playing(givenId):
try:
atv = await get_atv(givenId)
playing = await atv.metadata.playing()
#artwork = await atv.metadata.artwork()
except Exception as ex:
raise HTTPException(status_code=500, detail=f"Remote control command failed: {ex}")
return {"status": playing}
@app.get("/set_position/{givenId}/{position}")
async def playing(givenId, position):
try:
atv = await get_atv(givenId)
rc = atv.remote_control
await rc.set_position(int(position))
except Exception as ex:
raise HTTPException(status_code=500, detail=f"Remote control command failed: {ex}")
return {"status": "ok"}
@app.get("/current_app/{givenId}")
async def playing(givenId):
try:
atv = await get_atv(givenId)
currentApp = atv.metadata.app
except Exception as ex:
raise HTTPException(status_code=500, detail=f"Remote control command failed: {ex}")
return {
"name": currentApp.name,
"identifier": currentApp.identifier,
}