Skip to content

Instantly share code, notes, and snippets.

@ahmedfgad
Created June 30, 2020 18:31
Show Gist options
  • Save ahmedfgad/912c85539c215e6eddc02d95091f16e4 to your computer and use it in GitHub Desktop.
Save ahmedfgad/912c85539c215e6eddc02d95091f16e4 to your computer and use it in GitHub Desktop.
import socket
import pickle
import numpy
import threading
import pygad
import nn
import gann
class RecvThread(threading.Thread):
def __init__(self, kivy_app, buffer_size, recv_timeout):
threading.Thread.__init__(self)
self.kivy_app = kivy_app
self.buffer_size = buffer_size
self.recv_timeout = recv_timeout
def recv(self):
received_data = b""
while str(received_data)[-2] != '.':
try:
self.kivy_app.soc.settimeout(self.recv_timeout)
received_data += self.kivy_app.soc.recv(self.buffer_size)
except socket.timeout:
print("A socket.timeout exception occurred because the server did not send any data for {recv_timeout} seconds.".format(recv_timeout=self.recv_timeout))
self.kivy_app.label.text = "{recv_timeout} Seconds of Inactivity. socket.timeout Exception Occurred".format(recv_timeout=self.recv_timeout)
return None, 0
except BaseException as e:
return None, 0
print("Error While Receiving Data from the Server: {msg}.".format(msg=e))
self.kivy_app.label.text = "Error While Receiving Data from the Server"
try:
received_data = pickle.loads(received_data)
except BaseException as e:
print("Error Decoding the Client's Data: {msg}.\n".format(msg=e))
self.kivy_app.label.text = "Error Decoding the Client's Data"
return None, 0
return received_data, 1
def run(self):
global GANN_instance
subject = "echo"
GANN_instance = None
best_sol_idx = -1
while True:
data = {"subject": subject, "data": GANN_instance, "best_solution_idx": best_sol_idx}
data_byte = pickle.dumps(data)
self.kivy_app.label.text = "Sending a Message of Type {subject} to the Server".format(subject=subject)
try:
self.kivy_app.soc.sendall(data_byte)
except BaseException as e:
self.kivy_app.label.text = "Error Connecting to the Server. The server might has been closed."
print("Error Connecting to the Server: {msg}".format(msg=e))
break
self.kivy_app.label.text = "Receiving Reply from the Server"
received_data, status = self.recv()
if status == 0:
self.kivy_app.label.text = "Nothing Received from the Server"
break
else:
self.kivy_app.label.text = "New Message from the Server"
subject = received_data["subject"]
if subject == "model":
GANN_instance = received_data["data"]
elif subject == "done":
self.kivy_app.label.text = "Model is Trained"
break
else:
self.kivy_app.label.text = "Unrecognized Message Type: {subject}".format(subject=subject)
break
ga_instance = prepare_GA(GANN_instance)
ga_instance.run()
subject = "model"
best_sol_idx = ga_instance.best_solution()[2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment