class ServerManager: def __init__(self): self.socket_server = SocketServer() self.threads = [] self.socket_ip = self.socket_server.get_ip() def create_thread(self, thread_target): print('Create thread') new_thread = threading.Thread(target=thread_target) self.threads.append(new_thread) def setup(self): print('Socket setup') self.socket_server.setup() self.create_thread(self.socket_server.run_listen) self.create_thread(self.socket_server.run_send) self.create_thread(self.socket_server.record_data) print('Set dameon') for thread in self.threads: thread.setDaemon(True) def start(self): for thread in self.threads: print('Start thread') thread.start() def finish(self): self.socket_server.finish() def get_socket_instance(self): return self.socket_server def get_socket_ip(self): return self.socket_ip
def connect_socket(argument): so = SocketServer(argument["ip"], argument["port"]) if so.connect_server() == False: print("Error connexion to server ip:[{0}] port:[{1}]".format( argument["ip"], argument["port"])) exit(1) return so
def __init__(self, gateway_ip): self.Flaged_ip=dict() self.CONFIG = self.get_config() self.REPLICATION_COUNT = self.CONFIG["REPLICATION_COUNT"] self.GATEWAY_IP = gateway_ip self.mnode = SocketServer(gateway_ip) t = threading.Thread(target = self.run_mmnode_thread) t.start()
def __init__(self): self.CONFIG = self.get_config() self.GATEWAY_IPS = self.CONFIG["gateway_ips"] self.GATEWAY_SOCKS = [] self.CONTAINER_IP = self.CONFIG["api_server"] self.APISOCK = SocketServer(self.CONTAINER_IP, 44123) t = threading.Thread(target=self.run_APISOCK_thread) t.start()
def init_socket(): # Socket process parent_pipe, child_pipe = Pipe() # Starts the process proc = SocketServer(port, child_pipe) proc.start() queue = Queue() # Creates a new thread that will be listening the pipe nbpl = NBPL(parent_pipe, queue) nbpl.setDaemon(True) nbpl.start() return parent_pipe, queue
def _queue_linesplit(self): ss = SocketServer(host='localhost', port=8888) ss.create() self.lg.info('8888 Waiting connection...') while True: ss.accept() self.lg.info('Connection Accepted!') self.lg.info('8888 Waiting for stream...') data = ss.recv() while data != '\n': self.tq.put(data) data = ss.recv() self.tq.put(data) ss.close()
def start(self): server = SocketServer() thread = Thread(target=server.run, args=[self.sf2, True]) thread.start() while self.sf0.notComplete() and self.sf1.notComplete(): # camera looking at reflective tape self.sf2.setFrame( viewReflTape(self.sf0.getFrame(), self.sf1.getFrame()))
def _shipper(self, none): ss = SocketServer(host='localhost', port=8887) ss.create() self.lg.info('Waiting sub') while True: ss.accept() while True: data = self.tq.get() try: ss.send(data) except: logging.warning('Connection with 8887 losed') self.tq.put(data) break ss.close()
def scheduler(): """ Start all streams """ print("Flask up and running, now starting data streams...") # Start TCP socket Server SocketServer().start() print("SocketServer Started") ImageServer().start() print("ImageServer Started") # Start HTTP server HTTPserver().start() print("HTTPServer Started")
def run(self, lg): self.lg = lg ss = SocketServer(host='localhost', port=9999) ss.create() self.lg.info('9999 Waiting connection...') while True: ss.accept() while True: with open('res/results.txt', 'a') as outfile: try: data = ss.recv() outfile.write(data) except: logging.warning('Connection with 9999 losed') break ss.close()
class ConnectGateway(object): def __init__(self): self.CONFIG = self.get_config() self.GATEWAY_IPS = self.CONFIG["gateway_ips"] self.GATEWAY_SOCKS = [] self.CONTAINER_IP = self.CONFIG["api_server"] self.APISOCK = SocketServer(self.CONTAINER_IP, 44123) t = threading.Thread(target=self.run_APISOCK_thread) t.start() @staticmethod def get_config(): with open("./config/config.json") as fin: return json.loads(fin.read()) def run_APISOCK_thread(self): self.APISOCK.connection_accept() def get_gateway_ips(self): return self.GATEWAY_IPS def get_sock(self): return self.APISOCK
def main(): if os.path.exists("config.json"): with open("config.json", 'r') as file: configuration = json.load(file) ip = configuration["ip"] port = configuration["port"] motd = configuration["motd"]["1"] + "\n" + configuration["motd"]["2"] version_text = configuration["version_text"] kick_message = "" server_icon = None for message in configuration["kick_message"]: kick_message += message + "\n" kick_message = kick_message[:-2] if not os.path.exists(configuration["server_icon"]): print("Server icon doesn't exists - submitting none...") else: with open(configuration["server_icon"], 'rb') as image: server_icon = "data:image/png;base64," + base64.b64encode( image.read()).decode() try: global server server = SocketServer(ip, port, motd, version_text, kick_message, server_icon) server.start() except KeyboardInterrupt: server.close() exit(1) except Exception as e: print(e) else: configuration = {} configuration["ip"] = "0.0.0.0" configuration["port"] = 25565 configuration["motd"] = {} configuration["motd"]["1"] = "§4Maintenance!" configuration["motd"][ "2"] = "§aCheck example.com for more information!" configuration["version_text"] = "§4Maintenance" configuration["kick_message"] = [ "§bSorry", "", "§aThis server is offline!" ] configuration["server_icon"] = "server_icon.png" configuration["samples"] = ["§bexample.com", "", "§4Maintenance"] with open("config.json", 'w') as file: json.dump(configuration, file, sort_keys=True, indent=4, ensure_ascii=False) print("[!] A new configuration was created!") print("Please check the settings in the config.json!") exit(1)
def run(self): # Get event loop # -------------------- # Get the current event loop. If there is no current event loop set in # the current OS thread and set_event_loop() has not yet been called, # asyncio will create a new event loop and set it as the current one. self.loop = asyncio.get_event_loop() self.context.loop = self.loop self.futures = [] # Register actor instances logger.info('Registering {0} actor instances'.format( len(self.context.config['actors']) )) self.context.actors = list(map( lambda a: a['class'](a, self.context), self.context.config['actors'] )) # Message processor self.futures.append(asyncio.ensure_future(self.events_processor())) try: # Servers self.context.http_server = HttpServer() self.context.socket_server = SocketServer(async_mode='aiohttp') self.context.socket_server.configure(self.context) asyncio.ensure_future( self.context.http_server.configure(self.context), loop=self.loop) # Startup event self.context.queue_event('homeghost', 'startup', payload={}) # Run the event loop logger.info('Running core event loop') self.context.running = True self.loop.run_forever() finally: # Stop event loop self.context.running = False asyncio.wait(self.futures, loop=self.loop) self.loop.close()
def scheduler(): """ Start all streams """ print("Flask up and running, now starting data streams...") # Start TCP socket Server SocketServer().start() ImageServer().start() # Start HTTP server HTTPserver().start() # Can be a smart idea to start streams here! # Start some demo flows demo()
from oled_print import OLEDPrint from wifi import Wifi from socket_server import SocketServer from motor_control import MotorControl from wheel_encoder import WheelEncoder import global_params if __name__ == '__main__': global_params.init() global_params.set_value("motor_control", MotorControl()) global_params.set_value("wheel_encoder", WheelEncoder()) oled = OLEDPrint() wifi = Wifi(output_fun=oled) flag = wifi.do_connect() if flag is False: oled.output("Wifi Error") exit(0) ip = wifi.get_ip() socket_server = SocketServer(ip, output_fun=oled) socket_server.run()
def create_router_instance(self): SocketClient().create_socket_client_instance(self.interfaces) SocketServer().create_socket_server_instance(self.router_name)
isServer.width = 50 isServer.height = 30 isServer.x = 30 isServer.y = 650 isServer.bind(active=on_server_active) layout.add_widget(isServer) global ed ed = TextInput(hint_text='digite a mensagem a ser enviada') ed.size_hint = None, None ed.height = 500 ed.width = 400 ed.y = 100 layout.add_widget(ed) global bt bt = Button(text='send') bt.size_hint = None, None bt.width = 400 bt.height = 60 bt.y = 20 bt.on_press = handleClick layout.add_widget(bt) return layout global socket socket = SocketServer() janela = App() Window.size = 400, 700 janela.build = build janela.run()
def run_inference(args): from modules.inference_engine_pytorch import InferenceEnginePyTorch socket_server = SocketServer(args.port) joint_angle_calculator = JointAngleCalculator() stride = 8 model_path = os.path.join('models', 'human-pose-estimation-3d.pth') net = InferenceEnginePyTorch(model_path, "GPU") canvas_3d = np.zeros((720, 1280, 3), dtype=np.uint8) plotter = Plotter3d(canvas_3d.shape[:2]) canvas_3d_window_name = 'Canvas 3D' cv2.namedWindow(canvas_3d_window_name) cv2.setMouseCallback(canvas_3d_window_name, Plotter3d.mouse_callback) file_path = None if file_path is None: file_path = os.path.join('data', 'extrinsics.json') with open(file_path, 'r') as f: extrinsics = json.load(f) R = np.array(extrinsics['R'], dtype=np.float32) t = np.array(extrinsics['t'], dtype=np.float32) frame_provider = ImageReader(args.images) is_video = False if args.video != '': frame_provider = VideoReader(args.video) is_video = True base_height = args.height_size fx = 1 # focal length delay = 1 esc_code = 27 p_code = 112 space_code = 32 mean_time = 0 for frame in frame_provider: current_time = cv2.getTickCount() if frame is None: break input_scale = base_height / frame.shape[0] scaled_img = cv2.resize(frame, dsize=None, fx=input_scale, fy=input_scale) scaled_img = scaled_img[:, 0:scaled_img.shape[1] - (scaled_img.shape[1] % stride)] # better to pad, but cut out for demo if fx < 0: # Focal length is unknown fx = np.float32(0.8 * frame.shape[1]) inference_result = net.infer(scaled_img) poses_3d, poses_2d = parse_poses(inference_result, input_scale, stride, fx, is_video) edges = [] if len(poses_3d): poses_3d = rotate_poses(poses_3d, R, t) poses_3d_copy = poses_3d.copy() x = poses_3d_copy[:, 0::4] y = poses_3d_copy[:, 1::4] z = poses_3d_copy[:, 2::4] poses_3d[:, 0::4], poses_3d[:, 1::4], poses_3d[:, 2::4] = -z, x, -y poses_3d = poses_3d.reshape(poses_3d.shape[0], 19, -1)[:, :, 0:3] edges = (Plotter3d.SKELETON_EDGES + 19 * np.arange(poses_3d.shape[0]).reshape((-1, 1, 1))).reshape((-1, 2)) plotter.plot(canvas_3d, poses_3d, edges) cv2.imshow(canvas_3d_window_name, canvas_3d) draw_poses(frame, poses_2d) current_time = (cv2.getTickCount() - current_time) / cv2.getTickFrequency() if mean_time == 0: mean_time = current_time else: mean_time = mean_time * 0.95 + current_time * 0.05 cv2.putText(frame, 'FPS: {}'.format(int(1 / mean_time * 10) / 10), (40, 80), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255)) cv2.imshow('ICV 3D Human Pose Estimation', frame) key = cv2.waitKey(delay) if key == esc_code: break if key == p_code: if delay == 1: delay = 0 else: delay = 1 if delay == 0 or not is_video: # allow to rotate 3D canvas while on pause key = 0 while (key != p_code and key != esc_code and key != space_code): plotter.plot(canvas_3d, poses_3d, edges) cv2.imshow(canvas_3d_window_name, canvas_3d) key = cv2.waitKey(33) if key == esc_code: break else: delay = 1 joint_angles = joint_angle_calculator.calculate_angles(poses_3d) if joint_angles: socket_server.send_data(joint_angles)
for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1]]) if l ][0][0] #--------------------------------------------------------------------------- ###################################### MAIN ########################################### if __name__ == "__main__": # Thread for socket server socket_host = getIpAddress() socket_port = "8889" print "Start MAIN - host: ", socket_host, ", port: ", socket_port socketServer = SocketServer(socket_host, socket_port) socketThread = threading.Thread(target=socketServer.communicate) socketThread.setDaemon(True) socketThread.start() print "SocketServer is running" # Streaming thread GObject.threads_init() Gst.init(None) server = GstServer() loop = GObject.MainLoop() loop.run() # End
from socket_server import SocketServer s = SocketServer('', 7000) s.start()
def main(): logger = logging.getLogger("FakeMCServer") if not os.path.exists("logs"): os.makedirs("logs") logger.setLevel(logging.INFO) console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) file_handler = logging.FileHandler("logs/access.log") file_handler.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) console_handler.setFormatter(formatter) logger.addHandler(console_handler) logger.addHandler(file_handler) if os.path.exists("config.json"): logger.info("Loading configuration...") with open("config.json", 'r') as file: configuration = json.load(file) ip = configuration["ip"] port = configuration["port"] motd = configuration["motd"]["1"] + "\n" + configuration["motd"]["2"] version_text = configuration["version_text"] kick_message = "" samples = configuration["samples"] try: show_hostname = configuration["show_hostname_if_available"] except KeyError: configuration["show_hostname_if_available"] = True show_hostname = True with open("config.json", 'w') as file: json.dump(configuration, file, sort_keys=True, indent=4, ensure_ascii=False) player_max = configuration.get("player_max", 0) player_online = configuration.get("player_online", 0) protocol = configuration.get("protocol", 2) server_icon = None for message in configuration["kick_message"]: kick_message += message + "\n" if not os.path.exists(configuration["server_icon"]): logger.warning("Server icon doesn't exists - submitting none...") else: with open(configuration["server_icon"], 'rb') as image: server_icon = "data:image/png;base64," + base64.b64encode( image.read()).decode() try: global server logger.info("Setting up server...") server = SocketServer(ip, port, motd, version_text, kick_message, samples, server_icon, logger, show_hostname, player_max, player_online, protocol) server.start() except KeyboardInterrupt: logger.info("Shutting down server...") server.close() logger.info("Done. Thanks for using FakeMCServer!") exit(0) except Exception as e: logger.exception(e) else: logger.warning("No configuration file found. Creating config.json...") configuration = {} configuration["ip"] = "0.0.0.0" configuration["port"] = 25565 configuration["protocol"] = 2 configuration["motd"] = {} configuration["motd"]["1"] = "§4Maintenance!" configuration["motd"][ "2"] = "§aCheck example.com for more information!" configuration["version_text"] = "§4Maintenance" configuration["kick_message"] = [ "§bSorry", "", "§aThis server is offline!" ] configuration["server_icon"] = "server_icon.png" configuration["samples"] = ["§bexample.com", "", "§4Maintenance"] configuration["show_ip_if_hostname_available"] = True configuration["player_max"] = 0 configuration["player_online"] = 0 with open("config.json", 'w') as file: json.dump(configuration, file, sort_keys=True, indent=4, ensure_ascii=False) logger.info("Please adjust the settings in the config.json!") exit(1)
def run_websocket_svr(): socket_svr = SocketServer() socket_svr.start()
def connect_socket(argument): so = SocketServer(argument["ip"], argument["port"]) if so.connect_server() == False: print ("Error connexion to server ip:[{0}] port:[{1}]".format(argument["ip"], argument["port"])) exit(1) return so
async def init_server(): server = SocketServer(int(os.getenv("TELEGRAM_PORT")), on_response_message) await server.create()
from myutils import * from machine import reset from socket_server import SocketServer from ubinascii import a2b_base64 l = Logger() l.info('Started main.py') wifi_connect() wifi = network.WLAN(network.STA_IF) ap = network.WLAN(network.AP_IF) ss = SocketServer('10.0.0.32', 8888)
None Returns: None """ from urllib.request import urlopen import json byte_str = urlopen('https://www.howsmyssl.com/a/check').read() data = json.loads(byte_str.decode('utf-8')) tls_version = data['tls_version'] print('>>>Support TSL version {}'.format(tls_version)) print('>>>SSL library version {}'.format(ssl.OPENSSL_VERSION)) print('>>>SSL API version {}'.format(ssl._OPENSSL_API_VERSION)) if __name__ == "__main__": try: check_ssl() except Exception as ex: print(ex) server = SocketServer(is_debug=True, is_flushing=True) while True: if len(server.queuing_clients) > 0: print("Start recording ...") server.record() break # # server.start() # time.sleep(5.0) # server.record()
def __init__(self): self.socket_server = SocketServer() self.threads = [] self.socket_ip = self.socket_server.get_ip()
class Gateway(): def __init__(self, gateway_ip): self.Flaged_ip=dict() self.CONFIG = self.get_config() self.REPLICATION_COUNT = self.CONFIG["REPLICATION_COUNT"] self.GATEWAY_IP = gateway_ip self.mnode = SocketServer(gateway_ip) t = threading.Thread(target = self.run_mmnode_thread) t.start() def run_mmnode_thread(self): self.mnode.connection_accept() @staticmethod def get_config(): with open("./config/config.json") as fin: return json.loads(fin.read()) def get_crush(self): with open("./config/crushmap.json") as fin: return json.loads(fin.read()) @staticmethod def create_hash(user_id:str, pid:str): m = hashlib.sha1() m.update(user_id.encode()) m.update(pid.encode()) digest = m.hexdigest() digest_int = int(digest, 16) % 10**8 # decoded = binascii.unhexlify(str(encoded).encode()).decode() return digest_int def run_crush(self, user_id:str, pid:str, rcount:int): val = self.create_hash(user_id, pid) proc = subprocess.Popen(['python2', 'crush_runner.py', str(val), str(rcount)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, ) stdout_value = proc.communicate() print(stdout_value) device_ids = stdout_value[0].decode() device_ids = [str(devid).strip() for devid in device_ids.split("\n") if len(devid) > 0] print(device_ids, "in running crush") return device_ids def update_crush(self, critera): print("Update crush", critera) crush_map = self.get_crush() did = int(critera["DEVICE"].strip("_")[-1]) if critera["OP"] == "ADD": crush_map["trees"][0]["children"].insert(did-1, { "type": "host", "name": "host{}".format(did-1), "id": -1*did, "children": [ { "id": did, "name": critera["DEVICE"], "weight": 65536 } ] }) elif critera["OP"] == "REMOVE": del crush_map["trees"][0]["children"][did-1] fout = open("config/crushmap.json", "w") json.dump(crush_map, fout) fout.close() def insert(self, data:dict): kmaster = kazooMaster( self.GATEWAY_IP, "p", "", data["USERID"], data["PRODUCTID"], data["OPERATION"] ) for dname,val in self.Flaged_ip.items(): path = "/ephemeral_" + dname if kmaster.exist(path) and val == -1: self.update_crush({"OP": "ADD","DEVICE": dname}) #UP Update update crush #old MAX_loop_checker = 5 while MAX_loop_checker > 0: MAX_loop_checker -= 1 down_devices = False device_ids = list(self.run_crush(data["USERID"], data["PRODUCTID"], self.REPLICATION_COUNT)) device_ip_map = {} for node in self.CONFIG["nodes"]: if node["device_id"] in device_ids: device_ip_map[node["device_id"]] = node["ip"] print(self.Flaged_ip, ":flagged ips") kmaster.start_client() for did, ip in device_ip_map.items(): path = "/ephemeral_" + did if kmaster.exist(path): if did in self.Flaged_ip.keys() and self.Flaged_ip[did] == -1: self.read_repair({"NODES":device_ids}) self.Flaged_ip[did]=0 del self.Flaged_ip[did] else: self.update_crush({"OP": "REMOVE","DEVICE": did}) self.Flaged_ip[did]=-1 down_devices = True if not down_devices: break for did, ip in device_ip_map.items(): path = "/ephemeral_" + did if kmaster.exist(path): self.mnode.send_command(device_ip_map[did], data) kmaster.stop_client() return True def read_repair(self,info:dict): print("In read repair", info) """ dict={"NODES":[node1,node2,node3]} """ kmaster = kazooMaster( self.GATEWAY_IP,"p","","","","",False ) kmaster.start_client() all_user = set() flag = False down_node = [] for nodes in info["NODES"]: path = "/" + nodes print(path, "in read_repar") all_child = [] all_child = kmaster.get_children(path) print(all_child) if all_child == "": print("Node does not exists") kmaster.create(path) flag = True down_node.append(nodes) else: for child in all_child: all_user.add(child) for child in all_user: self.list_all({"USERID":child}, flag, down_node) kmaster.stop_client() def get_device_ip_map(self): device_ip_map = {} for node in self.CONFIG["nodes"]: device_ip_map[node["device_id"]] = node["ip"] return device_ip_map def list_all(self,info:dict, flag = False, down_nodes = None): """ dict={ "userid":username } """ print("list_all", info, flag, down_nodes) kmaster = kazooMaster( self.GATEWAY_IP,"p","",info["USERID"],"","",False ) kmaster.start_client() to_return = kmaster.getmap() if len(to_return) == 0: return [] self.mnode latest=dict() key="" maxVersion_replace = [] device_ip_map = self.get_device_ip_map() for i in range(len(to_return)): tkey = to_return[i]["key"] tdevice = to_return[i]["device"] tversion = to_return[i]["version"] if key != tkey: key = tkey all_dev=[] all_dev.append((tdevice,tversion)) latest[key]=all_dev else: all_dev.append((tdevice,tversion)) latest[key]=all_dev # print(latest[key]) maxData = None maxProductid = None for keys in latest: max_version=-1 List = latest[keys] #print(keys,List) for i in range(len(List)): x,y = List[i] # print("FOR PID: ",keys," DEVICE: ",x," VERSION: ",y) if max_version < int(y): max_version = int(y) maxDevice = x maxProductid = keys for node in self.CONFIG["nodes"]: if node["device_id"] == maxDevice: self.mnode.send_command([node["ip"], ], {"COMMAND":"RETRIEVE","USERID":info["USERID"], "PRODUCTID": maxProductid}) target= self.mnode.targets[node["ip"]] print(target) maxData = self.mnode.reliable_recv(target) # GOT THE PRODUCTS maxData = json.loads(maxData)["PRODUCT"] """ HUGE DOUBT IF SEND WILL I RECIVE USING RELIABLE RECV """ for i in range(len(List)): x,y = List[i] if max_version != int(y): path = "/" + info["USERID"] + "/"+ str(keys) + "/" + str(x) path_rev = "/" + str(x) + "/" + info["USERID"] + "/"+ str(keys) device_ids = list(x) for node in self.CONFIG["nodes"]: if node["device_id"] in device_ids: self.mnode.send_command( [node["ip"]], {"COMMAND":"REPLACE","USERID":info["USERID"], "UPDATEDLIST":maxData, "MAX_PRODUCTID": maxProductid} ) """ SENDING A LIST DEPENDS ON IF maxData RECIEVED """ kmaster.setVersion(path,max_version) kmaster.setVersion(path_rev,max_version) if flag == True: for down_node in down_nodes: kmaster.create("/{}/{}/{}".format(down_node, info["USERID"], keys)) kmaster.create("/{}/{}/{}".format(info["USERID"], keys, down_node)) print(maxData, type(maxData), "maxdata") """ {"COMMAND":"INSERT","USERID":"1", "PRODUCTID":"5","OPERATION":"2","PRICE":"4","CATEGORY":"12"} """ self.mnode.send_command( [device_ip_map[down_node],], {"COMMAND":"REPLACE","USERID":info["USERID"], "MAX_PRODUCTID": maxProductid, "UPDATEDLIST":[maxData]}) #TO DO CHANGE DATA NODES ALSO latest_data = kmaster.getmap() if len(latest_data) == 0: return [] kmaster.stop_client() return latest_data def list_all_user_products(self, critera): latest_data = self.list_all({"USERID": critera["USERID"]}) print(latest_data, "in gateway") device_ip_map = {} for node in self.CONFIG["nodes"]: device_ip_map[node["device_id"]] = node["ip"] counter = None to_return = [] for data in latest_data: if counter != data["key"]: counter = data["key"] self.mnode.send_command([device_ip_map[data["device"]]], { "COMMAND":"RETRIEVE","USERID":critera["USERID"], "PRODUCTID": data["key"]} ) target = self.mnode.targets[device_ip_map[data["device"]]] prod = self.mnode.reliable_recv(target) prod = json.loads(prod)["PRODUCT"] to_return.append(prod) print(to_return, "in gateway") return to_return def delete(self,info:dict): """ dict ={ "USERID":username, "PRODUCTID":productID } """ kmaster = kazooMaster( self.GATEWAY_IP,"p","",info["USERID"],info["PRODUCTID"],"",False ) kmaster.start_client() allInfo = self.list_all({"USERID": info["USERID"]}) print(allInfo) for val in range(len(allInfo)): if allInfo[val]["key"]==info["PRODUCTID"]: for node in self.CONFIG["nodes"]: if node["device_id"] == allInfo[val]["device"]: self.mnode.send_command([node["ip"]], {"COMMAND":"DELETE", "USERID":info["USERID"],"PRODUCTID":allInfo[val]["key"]}) def list_category(self,info:dict): """ { Find all the alive nodes and take secondary indexes from them } dict = { info={ "CATEGORY":CATEGORY_NUMBER } } } """ val = self.get_crush() all_category_info = [] device_ip_map = self.get_device_ip_map() for value in range(len(val["trees"][0]["children"])): name = val["trees"][0]["children"][value]["children"][0]["name"] # for node in self.CONFIG["nodes"]: self.mnode.send_command( [device_ip_map[name], ], {"COMMAND":"LISTCATEGORY", "CATEGORY":info["CATEGORY"] }) target= self.mnode.targets[device_ip_map[name]] temp = self.mnode.reliable_recv(target) temp = json.loads(temp) all_category_info.append(temp) print(all_category_info, "in list_category") return all_category_info
def thd_worker(inst, idx, conn, addr): print(f"got {idx} {addr}") conn.settimeout(3) buff = "" try: while (_ := conn.recv(512).decode()): if not _: break buff += _ except socket.timeout: pass conn.settimeout(None) conn.send(b"ok\n") inst.halted = buff.strip() == "halt" print(inst.halted, buff.strip().encode()) conn.close() if __name__ != "__main__": raise SystemExit server = SocketServer(port=randint(49152, 65535), logger_file=sys.stdout) print(f"started server on address {server.host}:{server.port}") server.handle_connections( thd_worker, proxy_worker_thd=lambda fn, *args, **kwargs: threading.Thread( target=fn, args=args, kwargs=kwargs).start())
def run_websocket_svr(): socket_svr = SocketServer() socket_svr.start()