Add sound manager initial source code
[staging/soundmanager.git] / sample / radio / app / api / Binding.qml
1 /*
2  * Copyright (C) 2016 The Qt Company Ltd.
3  * Copyright (C) 2017 Konsulko Group
4  * Copyright (c) 2017 TOYOTA MOTOR CORPORATION
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 import QtQuick 2.6
20 import QtWebSockets 1.0
21
22 WebSocket {
23     id: root
24     active: true
25     url: bindingAddress
26
27     property string apiString: "radio"
28     property var verbs: []
29     property string payloadLength: "9999"
30
31     readonly property var msgid: {
32          "call": 2,
33          "retok": 3,
34          "reterr": 4,
35          "event": 5
36     }
37
38     readonly property int amBand: 0
39     readonly property int fmBand: 1
40
41     readonly property int stoppedState: 0
42     readonly property int activeState: 1
43
44     property int band: fmBand
45     property int frequency
46     property int frequencyStep
47     property int minimumFrequency
48     property int maximumFrequency
49     property int state: stoppedState
50     property int scanningState: stoppedState
51     property bool scanningFreqUpdate: false
52     property string stationId: ""
53
54     signal stationFound
55
56     property Connections c : Connections {
57         target: root
58
59         onFrequencyChanged: {
60             if(scanningState != activeState) {
61                 // Not scanning, push update
62                 sendSocketMessage("frequency", { value: frequency })
63             } else if(!scanningFreqUpdate) {
64                 // External change, stop scanning
65                 sendSocketMessage("scan_stop", 'None')
66                 scanningState = stoppedState
67                 sendSocketMessage("frequency", { value: frequency })
68             } else {
69                 // This update was from scanning, clear state
70                 scanningFreqUpdate = false
71             }
72         }
73
74         onBandChanged: {
75             sendSocketMessage("band", { value: band })
76             updateFrequencyRange(band)
77             updateFrequencyStep(band)
78             frequency = minimumFrequency
79         }
80     }
81
82     onTextMessageReceived: {
83         var json = JSON.parse(message)
84         //console.debug("Raw response: " + message)
85         var request = json[2].request
86         var response = json[2].response
87
88         switch (json[0]) {
89         case msgid.call:
90             break
91         case msgid.retok:
92             var verb = verbs.shift()
93             if (verb == "frequency_range") {
94                 minimumFrequency = response.min
95                 maximumFrequency = response.max
96             } else if (verb == "frequency_step") {
97                 frequencyStep = response.step
98             }
99             break
100         case msgid.event:
101             var event = JSON.parse(JSON.stringify(json[2]))
102             if (event.event === "radio/frequency") {
103                 if(scanningState == activeState) {
104                     scanningFreqUpdate = true
105                     frequency = event.data.value
106                 }
107             } else if (event.event === "radio/station_found") {
108                 if(scanningState == activeState) {
109                     scanningState = stoppedState
110                     stationId = freq2str(event.data.value)
111                     root.stationFound()
112                 }
113             }
114             break
115         case msg.reterr:
116             console.debug("Bad return value, binding probably not installed")
117             break
118         case MessageId.event:
119             break
120         }
121     }
122
123     onStatusChanged: {
124         switch (status) {
125         case WebSocket.Open:
126             // Initialize band values now that we're connected to the
127             // binding
128             //smw.call("registerSource", { appname: radio })
129             updateFrequencyRange(band)
130             updateFrequencyStep(band)
131             frequency = minimumFrequency
132             sendSocketMessage("subscribe", { value: "frequency" })
133             sendSocketMessage("subscribe", { value: "station_found" })
134             break
135         case WebSocket.Error:
136             console.debug("WebSocket error: " + root.errorString)
137             break
138         }
139     }
140
141     function freq2str(freq) {
142         if (freq > 5000000) {
143             return '%1 MHz'.arg((freq / 1000000).toFixed(1))
144         } else {
145             return '%1 kHz'.arg((freq / 1000).toFixed(0))
146         }
147     }
148
149     function sendSocketMessage(verb, parameter) {
150         var requestJson = [ msgid.call, payloadLength, apiString + '/'
151                            + verb, parameter ]
152         //console.debug("sendSocketMessage: " + JSON.stringify(requestJson))
153         verbs.push(verb)
154         sendTextMessage(JSON.stringify(requestJson))
155     }
156
157     function start() {
158         console.log("start radio")
159         sendSocketMessage("start", 'None')
160         state = activeState
161     }
162
163     function stop() {
164         console.log("stop radio")
165         sendSocketMessage("stop", 'None')
166         state = stoppedState
167     }
168
169     function tuneUp() {
170         frequency += frequencyStep
171         if(frequency > maximumFrequency) {
172             frequency = minimumFrequency
173         }
174     }
175
176     function tuneDown() {
177         frequency -= frequencyStep
178         if(frequency < minimumFrequency) {
179             frequency = maximumFrequency
180         }
181     }
182
183     function scanUp() {
184         scanningState = activeState
185         sendSocketMessage("scan_start", { direction: "forward" })
186     }
187
188     function scanDown() {
189         scanningState = activeState
190         sendSocketMessage("scan_start", { direction: "backward" })
191     }
192
193     function updateFrequencyRange(band) {
194         sendSocketMessage("frequency_range", { band: band })
195     }
196
197     function updateFrequencyStep(band) {
198         sendSocketMessage("frequency_step", { band: band })
199     }
200 }