summaryrefslogtreecommitdiffstats
path: root/agl_service_voiceagent/utils/kuksa_interface.py
blob: ca1090bdd8cf69d47d0ef1a340d9befdc3122bc4 (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
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
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
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (c) 2023 Malik Talha
#
# 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.

import time
import json
import threading
from kuksa_client import KuksaClientThread
from agl_service_voiceagent.utils.config import get_config_value, get_logger

class KuksaInterface:
    """
    Kuksa Interface

    This class provides methods to initialize, authorize, connect, send values,
    check the status, and close the Kuksa client.
    """

    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        """
        Get the unique instance of the class.

        Returns:
            KuksaInterface: The instance of the class.
        """
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(KuksaInterface, cls).__new__(cls)
                cls._instance.init_client()
        return cls._instance
    

    def init_client(self):
        """
        Initialize the Kuksa client configuration.
        """
        # get config values
        self.ip = str(get_config_value("ip", "Kuksa"))
        self.port = str(get_config_value("port", "Kuksa"))
        self.insecure = bool(int(get_config_value("insecure", "Kuksa")))
        self.protocol = get_config_value("protocol", "Kuksa")
        self.token = get_config_value("token", "Kuksa")
        self.tls_server_name = get_config_value("tls_server_name", "Kuksa")
        self.logger = get_logger()

        # validate config
        if not self.validate_config():
            exit(1)

        print(self.ip, self.port, self.insecure, self.protocol, self.token)

        # define class methods
        self.kuksa_client = None

    def validate_config(self):
        """
        Validate the Kuksa client configuration.

        Returns:
            bool: True if the configuration is valid, False otherwise.
        """
        if self.ip is None:
            print("[-] Error: Kuksa IP address is not set.")
            self.logger.error("Kuksa IP address is not set.")
            return False

        if self.port is None:
            print("[-] Error: Kuksa port is not set.")
            self.logger.error("Kuksa port is not set.")
            return False

        if self.token is None:
            print("[-] Warning: Kuksa auth token is not set.")
            self.logger.warning("Kuksa auth token is not set.")

        if self.protocol != "ws" and self.protocol != "grpc":
            print("[-] Error: Invalid Kuksa protocol. Only 'ws' and 'grpc' are supported.")
            self.logger.error("Invalid Kuksa protocol. Only 'ws' and 'grpc' are supported.")
            return False

        return True


    def get_kuksa_client(self):
        """
        Get the Kuksa client instance.

        Returns:
            KuksaClientThread: The Kuksa client instance.
        """
        return self.kuksa_client


    def get_kuksa_status(self):
        """
        Check the status of the Kuksa client connection.

        Returns:
            bool: True if the client is connected, False otherwise.
        """
        if self.kuksa_client:
            return self.kuksa_client.checkConnection()
        return False


    def connect_kuksa_client(self):
        """
        Connect and start the Kuksa client.
        """
        try:
            with self._lock:
                if self.kuksa_client is None:
                    self.kuksa_client = KuksaClientThread({
                        "ip": self.ip,
                        "port": self.port,
                        "insecure": self.insecure,
                        "protocol": self.protocol,
                        "tls_server_name": self.tls_server_name
                    })
                    self.kuksa_client.start()
                    time.sleep(2)  # Give the thread time to start

                if not self.get_kuksa_status():
                    print("[-] Error: Connection to Kuksa server failed.")
                    self.logger.error("Connection to Kuksa server failed.")
                else:
                    print("[+] Connection to Kuksa established.")
                    self.logger.info("Connection to Kuksa established.")

        except Exception as e:
            print("[-] Error: Connection to Kuksa server failed. ", str(e))
            self.logger.error(f"Connection to Kuksa server failed. {str(e)}")

    
    def authorize_kuksa_client(self):
        """
        Authorize the Kuksa client with the provided token.
        """
        if self.kuksa_client:
            response = self.kuksa_client.authorize(self.token)

            if self.protocol == "ws" and "error" in json.loads(response):
                response = json.loads(response)
                error_message = response.get("error", "Unknown error")
                print(f"[-] Error: Authorization failed. {error_message}")
                self.logger.error(f"Authorization failed. {error_message}")

            elif self.protocol == "grpc" and "error" in response:
                print("[-] Error: Authorization failed.")
                self.logger.error("Authorization failed.")

            else:
                print("[+] Kuksa client authorized successfully.")
                self.logger.info("Kuksa client authorized successfully.")
        else:
            print("[-] Error: Kuksa client is not initialized. Call `connect_kuksa_client` first.")
            self.logger.error("Kuksa client is not initialized. Call `connect_kuksa_client` first.")


    def send_values(self, path=None, value=None):
        """
        Send values to the Kuksa server.

        Args:
            path (str): The path to the value.
            value (str): The value to be sent.
        Returns:
            bool: True if the value was set, False otherwise.
        """
        result = False
        if self.kuksa_client is None:
            print(f"[-] Error: Failed to send value '{value}' to Kuksa. Kuksa client is not initialized.")
            self.logger.error(f"Failed to send value '{value}' to Kuksa. Kuksa client is not initialized.")
            return result

        if self.get_kuksa_status():
            try:
                response = self.kuksa_client.setValue(path, value)

                if not "error" in response:
                    print(f"[+] Value '{value}' sent to Kuksa successfully.")
                    result = True

                else:
                    response = json.loads(response)
                    error_message = response.get("error", "{\"message\": \"Unknown error.\"}")
                    print(f"[-] Error: Failed to send value '{value}' to Kuksa. {error_message}")
                    self.logger.error(f"Failed to send value '{value}' to Kuksa. {error_message}")
            
            except Exception as e:
                print(f"[-] Error: Failed to send value '{value}' to Kuksa. ", str(e))
                self.logger.error(f"Failed to send value '{value}' to Kuksa. {str(e)}")

        else:
            print(f"[-] Error: Failed to send value '{value}' to Kuksa. Connection to Kuksa failed.")
            self.logger.error(f"Failed to send value '{value}' to Kuksa. Connection to Kuksa failed.")

        return result
    

    def get_value(self, path=None):
        """
        Get values from the Kuksa server.

        Args:
            path (str): The path to the value.
        Returns:
            str: The value if the path is valid, None otherwise.
        """
        result = None
        if self.kuksa_client is None:
            print(f"[-] Error: Failed to get value at path '{path}' from Kuksa. Kuksa client is not initialized.")
            self.logger.error(f"Failed to get value at path '{path}' from Kuksa. Kuksa client is not initialized.")
            return result

        if self.get_kuksa_status():
            try:
                response = self.kuksa_client.getValue(path)
                response = json.loads(response)
                if self.protocol == "ws" and not "error" in response:
                    result = response.get("data", None)
                    result = result.get("dp", None)
                    result = result.get("value", None)
                
                elif self.protocol == "grpc" and not "error" in response:
                    result = response.get("value", None)
                    result = result.get("value", None)

                else:
                    error_message = response.get("error", "{\"message\": \"Unknown error.\"}")
                    print(f"[-] Error: Failed to get value at path '{path}' from Kuksa. {error_message}")
                    self.logger.error(f"Failed to get value at path '{path}' from Kuksa. {error_message}")
            
            except Exception as e:
                print(f"[-] Error: Failed to get value at path '{path}' from Kuksa. ", str(e))
                self.logger.error(f"Failed to get value at path '{path}' from Kuksa. {str(e)}")

        else:
            print(f"[-] Error: Failed to get value at path '{path}' from Kuksa. Connection to Kuksa failed.")
            self.logger.error(f"Failed to get value at path '{path}' from Kuksa. Connection to Kuksa failed.")

        return result
    

    def close_kuksa_client(self):
        """
        Close and stop the Kuksa client.
        """
        try:
            with self._lock:
                if self.kuksa_client:
                    self.kuksa_client.stop()
                    self.kuksa_client = None
                    print("[+] Kuksa client stopped.")
                    self.logger.info("Kuksa client stopped.")
        except Exception as e:
            print("[-] Error: Failed to close Kuksa client. ", str(e))
            self.logger.error(f"Failed to close Kuksa client. {str(e)}")