server.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import socket
  4. import threading
  5. import json
  6. from client_info import ClientInfo
  7. import os
  8. class Server:
  9. def __init__(self, host, port, config_file):
  10. self.host = host
  11. self.port = port
  12. self.clients = []
  13. self.load_config(config_file)
  14. self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  15. self.server_socket.bind((self.host, self.port))
  16. self.server_socket.listen(5)
  17. print(f"Server started on {self.host}:{self.port}")
  18. def load_config(self, config_file):
  19. with open(config_file, 'r') as f:
  20. self.config = json.load(f)
  21. self.valid_clients = self.config.get("valid_clients", [])
  22. def validate_client(self, client_socket):
  23. try:
  24. data = client_socket.recv(1024).decode('utf-8')
  25. client_info = json.loads(data)
  26. for valid_client in self.valid_clients:
  27. if (client_info["device_id"] == valid_client["device_id"] and
  28. client_info["mac_address"] == valid_client["mac_address"]):
  29. return client_info
  30. except Exception as e:
  31. print(f"Validation error: {e}")
  32. return None
  33. def connect_audio_streams(self, client_info):
  34. try:
  35. audio_output_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  36. audio_output_socket.connect((client_info.ip_address, client_info.audio_output_port))
  37. client_info.audio_output_socket = audio_output_socket
  38. audio_input_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  39. audio_input_socket.connect((client_info.ip_address, client_info.audio_input_port))
  40. client_info.audio_input_socket = audio_input_socket
  41. except Exception as e:
  42. print(f"Error connecting audio streams: {e}")
  43. def send_audio_stream(self, client_socket, file_path):
  44. try:
  45. with open(file_path, 'rb') as audio_file:
  46. while True:
  47. data = audio_file.read(1024)
  48. if not data:
  49. break
  50. client_socket.sendall(data)
  51. except Exception as e:
  52. print(f"Error sending audio stream: {e}")
  53. def handle_client(self, client_socket):
  54. client_info = self.validate_client(client_socket)
  55. if client_info:
  56. ip_address = client_socket.getpeername()[0]
  57. client = ClientInfo(
  58. client_info["device_id"],
  59. client_info["mac_address"],
  60. client_info["room_name"],
  61. ip_address=ip_address,
  62. audio_output_port=client_info["audio_output_port"],
  63. audio_input_port=client_info["audio_input_port"],
  64. command_socket=client_socket
  65. )
  66. self.clients.append(client)
  67. print(f"Client connected: {client}")
  68. client_socket.send("Validation successful".encode('utf-8'))
  69. # Connect audio streams
  70. self.connect_audio_streams(client)
  71. # Handle update requests
  72. self.handle_update_requests(client_socket)
  73. # Send the audio stream to the client's audio output socket
  74. self.send_audio_stream(client.audio_output_socket, "audio/SpeechOn.wav")
  75. try:
  76. while True:
  77. data = client_socket.recv(1024)
  78. if not data:
  79. break
  80. # Handle further communication with the client here
  81. except Exception as e:
  82. print(f"Error while communicating with client: {e}")
  83. finally:
  84. print(f"Client disconnected: {client}")
  85. self.clients.remove(client)
  86. client_socket.close()
  87. else:
  88. client_socket.send("Validation failed".encode('utf-8'))
  89. client_socket.close()
  90. def handle_update_requests(self, client_socket):
  91. try:
  92. while True:
  93. request = client_socket.recv(1024).decode('utf-8')
  94. if request == "GET_MODEL_INFO":
  95. model_info = {
  96. "name": self.config["hotword"],
  97. "size": os.path.getsize("model/hotword/"+self.config["hotword"]+".keras")
  98. }
  99. client_socket.send(json.dumps(model_info).encode('utf-8'))
  100. elif request == "SEND_MODEL":
  101. with open("model/hotword/"+self.config["hotword"]+".keras", 'rb') as model_file:
  102. while True:
  103. data = model_file.read(1024)
  104. if not data:
  105. break
  106. client_socket.sendall(data)
  107. client_socket.send(b"____~EOF____~")
  108. break
  109. except Exception as e:
  110. print(f"Error handling update requests: {e}")
  111. def start(self):
  112. while True:
  113. client_socket, addr = self.server_socket.accept()
  114. print(f"Connection from {addr}")
  115. client_thread = threading.Thread(target=self.handle_client, args=(client_socket,))
  116. client_thread.start()