aboutsummaryrefslogtreecommitdiffstats
path: root/pyagl/services/mediaplayer.py
blob: d1e913778dd6ad43917a8b6b98e7df07a16f6aab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# Copyright (C) 2020 Konsulko Group
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from pyagl.services.base import AGLBaseService, AFBResponse
from typing import Union
import logging
import asyncio
import os

class AFBMediaPlayerResponse(AFBResponse):
    status: str
    info: str
    data = None

    def __init__(self, data: AFBResponse):
        if isinstance(data, list):
            super().__init__(data)
        self.msgid = data.msgid
        self.type = data.type
        self.data = data.data


class MediaPlayerService(AGLBaseService):
    service = 'agl-service-mediaplayer'
    parser = AGLBaseService.getparser()
    parser.add_argument('--playlist', help='Get current playlist', action='store_true')
    parser.add_argument('--control', help='Play/Pause/Previous/Next')
    parser.add_argument('--seek', help='Seek time through audio track', metavar='msec', type=int)
    parser.add_argument('--rewind', help='Rewind time', metavar='msec', type=int)
    parser.add_argument('--fastforward', help='Fast forward time', metavar='msec', type=int)
    parser.add_argument('--picktrack', help='Play specific track in the playlist', metavar='index', type=int)
    parser.add_argument('--volume', help='Volume control - <1-100>', metavar='int')
    parser.add_argument('--loop', help='Set loop state - <off/track/playlist>', metavar='string')
    parser.add_argument('--avrcp', help='AVRCP Controls')

    def __await__(self):
        return super()._async_init().__await__()

    def __init__(self, ip, port=None):
        super().__init__(api='mediaplayer', ip=ip, port=port, service='agl-service-mediaplayer')

    async def playlist(self):
        return await self.request('playlist')

    async def subscribe(self, event='metadata'):
        return await super().subscribe(event=event)

    async def unsubscribe(self, event='metadata'):
        return await super().subscribe(event=event)

    async def control(self, name, value=None):
        loopstate = ['off', 'playlist', 'track']
        avrcp_controls = ['next', 'previous', 'play', 'pause']
        controls = {
            'play': None,
            'pause': None,
            'previous': None,
            'next': None,
            'seek': 'position',
            'fast-forward': 'position',
            'rewind': 'position',
            'pick-track': 'index',
            'volume': 'volume',
            'loop': 'state',
            # 'avrcp_controls': 'value'
        }
        assert name in controls.keys(), f'Tried to use non-existent {name} as control for {self.api}'
        msg = None
        if name in ['play', 'pause', 'previous', 'next']:
            msg = {'value': name}
        elif name in ['seek', 'fast-forward', 'rewind']:
            # assert value > 0, "Tried to seek with negative integer"
            msg = {'value': name, controls[name]: str(value)}
        elif name == 'pick-track':
            assert type(value) is int, "Try picking a song with an integer"
            assert value > 0, "Tried to pick a song with a negative integer"
            msg = {'value': name, controls[name]: str(value)}
        elif name == 'volume':
            assert type(value) is int, "Try setting the volume with an integer"
            assert value > 0, "Tried to set the volume with a negative integer, use values betwen 0-100"
            assert value < 100, "Tried to set the volume over 100%, use values betwen 0-100"
            msg = {'value': name, name: str(value)}
        elif name == 'loop':
            assert value in loopstate, f'Tried to set invalid loopstate - {value}, use "off", "playlist" or "track"'
            msg = {'value': name, controls[name]: str(value)}
        # elif name == 'avrcp_controls':
        #     msg = {'value': name, }
        assert msg is not None, "Congratulations, somehow you made an invalid control request"

        return await self.request('controls', msg)


async def main(loop):
    args = MediaPlayerService.parser.parse_args()
    MPS = await MediaPlayerService(ip=args.ipaddr)

    if args.playlist:
        msgid = await MPS.playlist()
        r = await MPS.afbresponse()
        for l in r.data['list']: print(l)

    if args.control:
        msgid = await MPS.control(args.control)
        print(f'Sent {args.control} request with messageid {msgid}')
        r = await MPS.afbresponse()
        print(r)

    if args.seek:
        msgid = await MPS.control('seek', args.seek)
        print(f'Sent seek request to {args.seek} msec with messageid {msgid}')
        r = await MPS.afbresponse()
        print(r)

    if args.fastforward:
        msgid = await MPS.control('fast-forward', args.fastforward)
        print(f'Sent fast-forward request for {args.fastforward} msec with messageid {msgid}')
        r = await MPS.afbresponse()
        print(r)

    if args.rewind:
        msgid = await MPS.control('rewind', -args.rewind)
        print(f'Sent rewind request for {args.rewind} msec with messageid {msgid}')
        r = await MPS.afbresponse()
        print(r)

    if args.picktrack:
        msgid = await MPS.control('pick-track', args.picktrack)
        print(f'Sent pick-track request with index {args.rewind} with messageid {msgid}')
        r = await MPS.afbresponse()
        print(r)

    if args.volume:
        msgid = await MPS.control('volume', int(args.volume))
        print(f'Sent volume request: {args.rewind} with messageid {msgid}')
        r = await MPS.afbresponse()
        print(r)

    if args.loop:
        msgid = await MPS.control('loop', args.loop)
        print(f'Sent loop-state request: {args.loop} with messageid {msgid}')
        r = await MPS.afbresponse()
        print(r)

    # if args.avrcp:
    #     id = await MPS.control('avrcp_controls', args.avrcp)
    #     print(f'Sent AVRCP control request: {args.loop} with messageid {id}')
    #     r = AFBResponse(await MPS.response())
    #     print(r)

    if args.subscribe:
        for event in args.subscribe:
            msgid = await MPS.subscribe(event)
            print(f"Subscribed for event {event} with messageid {msgid}")
            r = await MPS.afbresponse()
            print(r)

    if args.listener:
        async for response in MPS.listener():
            print(response)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))