summaryrefslogtreecommitdiffstats
path: root/agl_service_voiceagent/utils/kuksa_interface.py
blob: 92703797122340e7b5257cc000743230c4c4798f (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
# 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

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 = get_config_value("insecure", "Kuksa")
        self.protocol = get_config_value("protocol", "Kuksa")
        self.token = get_config_value("token", "Kuksa")

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

        # define class methods
        self.kuksa_client = None


    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,
                    })
                    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.")
                else:
                    print("[+] Connection to Kuksa established.")

        except Exception as e:
            print("[-] Error: 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)
            response = json.loads(response)
            if "error" in response:
                error_message = response.get("error", "Unknown error")
                print(f"[-] Error: Authorization failed. {error_message}")
            else:
                print("[+] Kuksa client authorized successfully.")
        else:
            print("[-] 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("[-] Error: Kuksa client is not initialized.")
            return

        if self.get_kuksa_status():
            try:
                response = self.kuksa_client.setValue(path, value)
                response = json.loads(response)
                if not "error" in response:
                    print(f"[+] Value '{value}' sent to Kuksa successfully.")
                    result = True
                else:
                    error_message = response.get("error", "Unknown error")
                    print(f"[-] Error: Failed to send value '{value}' to Kuksa. {error_message}")
            
            except Exception as e:
                print("[-] Error: Failed to send values to Kuksa. ", str(e))

        else:
            print("[-] Error: 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("[-] Error: Kuksa client is not initialized.")
            return

        if self.get_kuksa_status():
            try:
                response = self.kuksa_client.getValue(path)
                response = json.loads(response)
                if not "error" in response:
                    result = response.get("data", None)
                    result = result.get("dp", None)
                    result = result.get("value", None)
                    
                else:
                    error_message = response.get("error", "Unknown error")
                    print(f"[-] Error: Failed to get value from Kuksa. {error_message}")
            
            except Exception as e:
                print("[-] Error: Failed to get values from Kuksa. ", str(e))

        else:
            print("[-] Error: 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.")
        except Exception as e:
            print("[-] Error: Failed to close Kuksa client. ", str(e))