def start_server(self, ip): """ :param ip: :return: """ server = ServerThread(ip) server.start()
def start_server(self): self.log("Trying to start server thread ...") self.server = ServerThread(port=int(self.txt_port.text, 10)) self.logbox.connect(self.server, SIGNAL("log(QString)"), self.log) self.logbox.connect(self.server, SIGNAL("command(QString)"), self.command) self.server.set_taskview(self) self.server.start()
def run(self): while (self.runningThread): if (self.beacon_thread != None and not self.beacon_thread.is_alive()): print("Restart beacon thread") self.logFile.saveWithDate("Restart beacon thread") self.beacon_thread = ServerBeaconThread( threadID=self.threadID + 1, host_ip=self.host_ip, broadcast_ip=self.broadcast_ip, negotiation_port=self.negotiation_port, sleepDuration=1.9, logFile=self.logFile) self.beacon_thread.start() if (self.server_thread != None and not self.server_thread.is_alive()): print("Restart server thread") self.logFile.saveWithDate("Restart server thread") self.server_thread = ServerThread( threadID=self.threadID + 2, address=self.server_address.asTuple(), carMap=self.carMap, logFile=self.logFile) self.server_thread.start() if (self.forwarding_thread != None and not self.forwarding_thread.is_alive()): print("Restart forwarding thread") self.logFile.saveWithDate("Restart forwarding thread") self.forwarding_thread = Forward2CarThread( threadID=self.threadID + 3, car_communication_port=self.car_communication_port, carMap=self.carMap, period=1.0, logFile=self.logFile) self.forwarding_thread.start() if (self.carSubscriber_thread != None and not self.carSubscriber_thread.is_alive()): print("Restart carSubscriber thread") self.logFile.saveWithDate("Restart carSubscriber thread") self.carSubscriber_thread = Listen4CarSubscriberThread( threadID=self.threadID + 4, host_ip=self.host_ip, car_subscription_port=self.car_subscription_port, carMap=self.carMap, logFile=self.logFile) self.carSubscriber_thread.start() if (self.server_address.ip == '' and self.server_address.port == -1): self.NegotiateServer() time.sleep(1.1)
def __init__(self, host='localhost', port_range=range(6776, 6781), server_host='localhost', server_port=24011, parent=None): super(BrytonClient, self).__init__(parent) self._host = host self._port = port_range[0] self._port_range = port_range self._server_port = None self._server_host = server_host self._socket = s = QTcpSocket(self) s.readyRead.connect(self._onReadyRead) s.connected.connect(self._onConnected) s.disconnected.connect(self._onDisconnected) s.error.connect(self._onSocketError) self.connected.connect(self._getState) self.deviceReady.connect(self._refreshTrackList) self.server = ServerThread(server_host, server_port, self) self.server.trackListUploaded.connect(self._onTrackListUploaded) self.server.trackDataUploaded.connect(self._onTrackDataUploaded) self.server.trackListReady.connect(self._onTracksUploaded) self.server.error.connect(self._onError) self.server.serverStarted.connect(self._onServerStarted) self.reset() self.server.start()
def main(): parser = argparse.ArgumentParser(description='LP options') parser.add_argument('-logging_dir', type=str, default="logs", help="Logging directory") args = parser.parse_args() server_thread = ServerThread(args.logging_dir) server_thread.start() menu_loop = menu.Menu() try: menu_loop.cmdloop() except KeyboardInterrupt as e: pass server_thread.should_stop = True
def launch_server(server_id, entities_threads, network_data): # unpack dictionaries servers_data = network_data["servers_data"] routers_data = network_data["routers_data"] routers_threads = entities_threads["routers_threads"] servers_threads = entities_threads["servers_threads"] server_data = servers_data[server_id] default_gateway = server_data["gateway_ip"] arp_table_mac = data.server_arp_table_generator(default_gateway, routers_data) # find the id of the router to which the client will connect for router, router_data in routers_data.items(): if (router_data["server_side"]["ip_address"] == default_gateway): router_id = router break router_thread = routers_threads[router_id] init_params = { "servers_threads": servers_threads, "arp_table_mac": arp_table_mac, "router_id": router_id, "router_thread": router_thread, "server_data": server_data, "server_id": server_id, } server_thread = ServerThread(init_params) servers_threads[server_id] = server_thread server_thread.start()
def main_loop(self): client = Client() t = ServerThread(client) t.start() while True: data = raw_input('>>> ') if data == 'exit': break else: if data == 'exit lego': data = 'exit' client.send(data) client.close() t.exit_server = True t.join()
def main_loop(self): client = Client() t = ServerThread(client) t.start() while True: data = raw_input(">>> ") if data == "exit": break else: if data == "exit lego": data = "exit" client.send(data) client.close() t.exit_server = True t.join()
def standalone_server(bin_prefix, tmp_path): server = ServerThread(bin_prefix, str(tmp_path)) server.start() wait_result = server.wait() if wait_result is not None: with open(os.path.join(server.log_dir, 'server', 'stdout.txt'), 'r') as f: print >> sys.stderr, f.read() with open(os.path.join(server.log_dir, 'server', 'stderr.txt'), 'r') as f: print >> sys.stderr, f.read() pytest.fail('Server died unexpectedly with code {code}'.format( code=server._proc.returncode), pytrace=False) yield server server.stop()
def listening_thread(stop_event): sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', 1337)) sock.listen(5) while not stop_event.is_set(): try: conn, addr = sock.accept() except KeyboardInterrupt as e: raise ValueError("Can't accept new connection") try: server_thread = ServerThread(1, conn) server_thread.set_caller(taskmasterd) server_thread.run() except: #print ("Error: unable to start thread") conn.close()
An order can only be executed once """ self.order.add_batch([ { 'loan_id': 123, 'invest_amount': 50 }, { 'loan_id': 234, 'invest_amount': 75 } ]) order_id = self.order.execute() self.assertNotEqual(order_id, 0) self.assertRaises( AssertionError, lambda: self.order.execute() ) if __name__ == '__main__': # Start the web-server in a background thread http = ServerThread() http.start() # Run tests unittest.main() # Stop threads http.stop()
class ServerThreadManager(Thread): ''' A server thread manager functionality It periodically verifies the server thread's state, in the case of blocking it restarts the thread. ''' def __init__(self, threadID, server_address, broadcast_ip, host_ip, negotiation_port, subscription_port, car_subscription_port, car_communication_port, max_wait_time_for_server, logFile=None): ''' Decide which simulated GPS starts the server. Arguments: threadID {int} -- the thread id server_address {str} -- the server address broadcast_ip {str} -- broadcast IP address host_ip {str} -- localhost IP address negotiation_port {int} -- negotiation port subscription_port {int} -- subscription port used to transmite the data from the detectors to the server car_subscription_port {int} -- port used for the vechile client to subscribe on the server car_communication_port {int} -- port used for trasmiting the data from the server to the clients max_wait_time_for_server {float} -- maximum waiting time to receive a beacon from the server ''' Thread.__init__(self) self.name = 'ServerManager' self.threadID = threadID self.logFile = logFile self.server_address = server_address self.beacon_thread = None self.server_thread = None self.forwarding_thread = None self.carSubscriber_thread = None self.carMap = None self.broadcast_ip = broadcast_ip self.host_ip = host_ip self.negotiation_port = negotiation_port self.subscription_port = subscription_port self.car_subscription_port = car_subscription_port self.car_communication_port = car_communication_port self.max_wait_time_for_server = max_wait_time_for_server self.runningThread = True #================================ NEGOTIATION SERVER ===================== def NegotiateServer(self): ''' Function that decides which simulated GPS starts the server. ''' print("Negotiation start!") s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) s.bind(('', self.negotiation_port)) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) randTime = 10 * self.max_wait_time_for_server * random.random() wait_time = 2 + math.floor(randTime) / 100 print("Waiting " + str(wait_time) + " seconds for server") t = time.time() server = [] try: # listen for server broadcast s.settimeout(wait_time) data, SERVER_IP = s.recvfrom(1500, 0) # server beacon received s.close() print("Server started on " + str((SERVER_IP[0]))) # store server info self.server_address.ip = str(SERVER_IP[0]) self.server_address.port = self.subscription_port except KeyboardInterrupt: print('KeyboardInterrupt') except Exception as e: print("No response, starting server here", e) s.sendto(bytes(self.host_ip, "UTF-8"), (self.broadcast_ip, self.negotiation_port)) s.close() self.stopAllThread() self.server_address.ip = self.host_ip self.server_address.port = self.subscription_port if (self.logFile != None): log_message = 'NegotiateServer- server address %s' % str( self.server_address) self.logFile.saveWithDate(log_message) self.carMap = Data4CarMap(256) # thread responsible for broadcasting itself as the server self.beacon_thread = ServerBeaconThread( threadID=self.threadID + 1, host_ip=self.host_ip, broadcast_ip=self.broadcast_ip, negotiation_port=self.negotiation_port, sleepDuration=1.9, logFile=self.logFile) self.beacon_thread.start() # thread responsible for collecting GPS data from clients self.server_thread = ServerThread( threadID=self.threadID + 2, address=self.server_address.asTuple(), carMap=self.carMap, logFile=self.logFile) self.server_thread.start() # thread responsible for sending GPS data to each registered vehicle self.forwarding_thread = Forward2CarThread( threadID=self.threadID + 3, car_communication_port=self.car_communication_port, carMap=self.carMap, period=1.0, logFile=self.logFile) self.forwarding_thread.start() # thread responsible for registering vehicles self.carSubscriber_thread = Listen4CarSubscriberThread( threadID=self.threadID + 4, host_ip=self.host_ip, car_subscription_port=self.car_subscription_port, carMap=self.carMap, logFile=self.logFile) self.carSubscriber_thread.start() print(str(time.time() - t) + " seconds elapsed") #================================ STOP ==================================== def stopAllThread(self): ''' Function responsible for stoppinf all threads ''' #beacon thread if self.beacon_thread != None: self.beacon_thread.stop() if (self.beacon_thread.is_alive()): self.beacon_thread.join() self.beacon_thread = None print("beacon_thread stoped!") #server thread if self.server_thread != None: self.server_thread.stop() if (self.server_thread.is_alive()): self.server_thread.join() self.server_thread = None print("server_thread stoped!") #forwarding thread if self.forwarding_thread != None: self.forwarding_thread.stop() if (self.forwarding_thread.is_alive()): self.forwarding_thread.join() self.forwarding_thread = None print("forwarding_thread stoped!") #car subscriber thread if self.carSubscriber_thread != None: self.carSubscriber_thread.stop() if (self.carSubscriber_thread.is_alive()): self.carSubscriber_thread.join() self.carSubscriber_thread = None print("carSubscriber_thread stoped!") #================================ RUN THREADS ============================= def run(self): while (self.runningThread): if (self.beacon_thread != None and not self.beacon_thread.is_alive()): print("Restart beacon thread") self.logFile.saveWithDate("Restart beacon thread") self.beacon_thread = ServerBeaconThread( threadID=self.threadID + 1, host_ip=self.host_ip, broadcast_ip=self.broadcast_ip, negotiation_port=self.negotiation_port, sleepDuration=1.9, logFile=self.logFile) self.beacon_thread.start() if (self.server_thread != None and not self.server_thread.is_alive()): print("Restart server thread") self.logFile.saveWithDate("Restart server thread") self.server_thread = ServerThread( threadID=self.threadID + 2, address=self.server_address.asTuple(), carMap=self.carMap, logFile=self.logFile) self.server_thread.start() if (self.forwarding_thread != None and not self.forwarding_thread.is_alive()): print("Restart forwarding thread") self.logFile.saveWithDate("Restart forwarding thread") self.forwarding_thread = Forward2CarThread( threadID=self.threadID + 3, car_communication_port=self.car_communication_port, carMap=self.carMap, period=1.0, logFile=self.logFile) self.forwarding_thread.start() if (self.carSubscriber_thread != None and not self.carSubscriber_thread.is_alive()): print("Restart carSubscriber thread") self.logFile.saveWithDate("Restart carSubscriber thread") self.carSubscriber_thread = Listen4CarSubscriberThread( threadID=self.threadID + 4, host_ip=self.host_ip, car_subscription_port=self.car_subscription_port, carMap=self.carMap, logFile=self.logFile) self.carSubscriber_thread.start() if (self.server_address.ip == '' and self.server_address.port == -1): self.NegotiateServer() time.sleep(1.1) #============================= STOP ======================================= def stop(self): self.runningThread = False
class MHServerTaskView(gui3d.TaskView): human = None # Reference to the in-scene human toggle = None # Toggle button for server enable / disable logbox = None # Log view of any server spew server = None # ServerThread instance def __init__(self, category): """ Constructor for the TaskView. This accepts the category under which this feature is enabled. The category is registered with the app and passed into this constructor on the `load()` API below. """ self.human = gui3d.app.selectedHuman gui3d.TaskView.__init__(self, category, "MHServer") fr_left = self.addLeftWidget(gui.GroupBox("Settings:")) self.txt_port = fr_left.addWidget(gui.TextEdit(text="18830")) self.btn_restart = fr_left.addWidget(gui.Button("Restart")) @self.btn_restart.mhEvent def onClicked(e): self.restart_server() self.logbox = self.addTopWidget(gui.DocumentEdit()) self.logbox.setText("") self.logbox.setLineWrapMode(gui.DocumentEdit.NoWrap) def bootstrap(self, app): """ `bootstrap` allows this TaskView to figure out dependent task views to trigger downstream functions. """ self.pose_lib = app.getTask("Pose/Animate", "Pose") self.skel_lib = app.getTask("Pose/Animate", "Skeleton") self.clothes_lib = app.getTask("Geometries", "Clothes") self.eyebrows_lib = app.getTask("Geometries", "Eyebrows") self.eyes_lib = app.getTask("Geometries", "Eyes") self.topologies_lib = app.getTask("Geometries", "Topologies") self.eyelashes_lib = app.getTask("Geometries", "Eyelashes") self.hair_lib = app.getTask("Geometries", "Hair") self.teeth_lib = app.getTask("Geometries", "Teeth") self.tongue_lib = app.getTask("Geometries", "Tongue") def log(self, msg): """ Logs a message to the text box `log`. """ self.logbox.addText(msg + "\n") if self.server: self.server.broadcast(str(msg)) def command(self, msg, conn=None): words = str(msg).rstrip().split(" ") cmd, args = words[0], words[1:] factory.run(self, cmd, args) def start_server(self): self.log("Trying to start server thread ...") self.server = ServerThread(port=int(self.txt_port.text, 10)) self.logbox.connect(self.server, SIGNAL("log(QString)"), self.log) self.logbox.connect(self.server, SIGNAL("command(QString)"), self.command) self.server.set_taskview(self) self.server.start() def stop_server(self): self.log("Trying to close server thread ...") if self.server is None: return self.server.stop() self.server = None def restart_server(self): self.stop_server() self.start_server() """ ----------------------------------------------------------------------- Registered makehuman commands. """ """ Modeling :: Main """ @factory.register( "set_age", "Set the human's age", ["value", float, 0, "parameter value (between 1.0 and 90.0"]) def set_age(self, age): age = min(max(age, 1.0), 90.0) G.mhapi.modifiers.setAge(age) @factory.register( "set_weight", "Set the human's weight", ["value", float, 0, "parameter value (between 50%% and 150%%"]) def set_weight(self, weight): weight = min(max(weight, 50.0), 150.0) G.mhapi.modifiers.setWeight(weight) @factory.register( "set_muscle", "Set the human's muscle", ["value", float, 0, "parameter value (between 0%% and 100%%"]) def set_muscle(self, muscle): muscle = min(max(muscle, 0.0), 100.0) G.mhapi.modifiers.setMuscle(muscle) @factory.register("set_height", "Set the human's height", ["value", float, 0, "parameter value (in cm)"]) def set_height(self, height): G.mhapi.modifiers.setHeight(height) @factory.register("set_gender", "Set the human's gender", [ "value", float, 0, "parameter value (100%% is female and 0%% is male" ]) def set_gender(self, gender): gender = min(max(gender, 0.0), 100.0) G.mhapi.modifiers.setGender(gender) """ ------------------------------------------------------------------- """ """ Geometries :: Clothes """ @factory.register( "add_clothes", "Set the human's clothes -- these are addititve (see remove_clothes)", [ "clothes_path", str, "data/clothes/male_casualsuit02/male_casualsuit02.mhclo", "path to clothes file" ]) def add_clothes(self, clothes_path): self.clothes_lib.selectProxy(clothes_path) @factory.register( "remove_clothes", "Remove the human's clothes -- these are addititve (see add_clothes)", [ "clothes_path", str, "data/clothes/male_casualsuit02/male_casualsuit02.mhclo", "path to clothes file" ]) def remove_clothes(self, clothes_path): self.clothes_lib.deselectProxy(clothes_path) """ Geometries :: Eyes """ @factory.register( "set_eyes", "Set the human's eyes -- should always set low-poly", [ "eyes_path", str, "data/eyes/low-poly/low-poly.mhclo", "path to eyes file" ]) def set_eyes(self, eyes_path): self.eyes_lib.selectProxy(eyes_path) """ Geometries :: Hair """ @factory.register("set_hair", "Set the human's hair", [ "hair_path", str, "data/hair/afro01/afro01.mhclo", "path to hair file" ]) def set_hair(self, hair_path): self.hair_lib.selectProxy(hair_path) """ Geometries :: Teeth """ @factory.register("set_teeth", "Set the human's teeth", [ "teeth_path", str, "data/teeth/teeth_shape01/teeth_shape01.mhclo", "path to teeth file" ]) def set_teeth(self, teeth_path): self.teeth_lib.selectProxy(teeth_path) """ Geometries :: Topologies """ @factory.register("set_topologies", "Set the human's topologies", ["topologies_path", str, "", "path to topologies file"]) def set_topologies(self, topologies_path): self.topologies_lib.selectProxy(topologies_path) """ Geometries :: Eyebrows """ @factory.register("set_eyebrows", "Set the human's eyebrows", [ "eyebrows_path", str, "data/eyebrows/eyebrow001/eyebrow001.mhclo", "path to eyebrows file" ]) def set_eyebrows(self, eyebrows_path): self.eyebrows_lib.selectProxy(eyebrows_path) """ Geometries :: Eyelashes """ @factory.register("set_eyelashes", "Set the human's eyelashes", [ "eyelashes_path", str, "data/eyelashes/eyelashes02/eyelashes02.mhclo", "path to eyelashes file" ]) def set_eyelashes(self, eyelashes_path): self.eyelashes_lib.selectProxy(eyelashes_path) """ Geometries :: Tongue """ @factory.register("set_tongue", "Set the human's tongue", ["tongue_path", str, None, "path to tongue file"]) def set_tongue(self, tongue_path): self.tongue_lib.selectProxy(tongue_path) """ ------------------------------------------------------------------- """ """ Pose/Animate :: Skeleton """ @factory.register( "set_skeleton", "Set the human's skeleton from the specified .mhskel file", [ "skel_path", str, "data/rigs/game_engine.mhskel", "path to .mhskel file" ]) def set_skeleton(self, skel_path): self.skel_lib.filechooser.onFileSelected(skel_path) """ Pose/Animate :: Pose """ @factory.register( "set_pose", "Set the human's pose to the specified bvh file", ["pose_path", str, "data/poses/tpose.bvh", "path to pose file"]) def set_pose(self, pose_path): self.pose_lib.filechooser.onFileSelected(pose_path)
tzco = 80 # Initial values for data calculated by the model tr = 20 tpco = 75 # Initial flow fcob = 40 # Data dict we'll be modifying and sending data = {'Tpcob': tpco, 'Fcob': fcob, 'Tr': tr} lock = Lock() host = 'localhost' port = 50009 server = ServerThread(data, host, port) server.start() # Used for local logging and visualization, probably will be deleted later so we don't get a MemoryError because # these get too big. Another option would be to serialize them and save to file but who's got time for that? time_vector = [] tpco_vector = [] tr_vector = [] ntp = NTPClient() t = t_0 = ntp.request('1.pl.pool.ntp.org').tx_time last_error = 0 error_integral = 0 while True: try: to = request_data(energy_provider[0], energy_provider[1], 'To')
def NegotiateServer(self): ''' Function that decides which simulated GPS starts the server. ''' print("Negotiation start!") s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) s.bind(('', self.negotiation_port)) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) randTime = 10 * self.max_wait_time_for_server * random.random() wait_time = 2 + math.floor(randTime) / 100 print("Waiting " + str(wait_time) + " seconds for server") t = time.time() server = [] try: # listen for server broadcast s.settimeout(wait_time) data, SERVER_IP = s.recvfrom(1500, 0) # server beacon received s.close() print("Server started on " + str((SERVER_IP[0]))) # store server info self.server_address.ip = str(SERVER_IP[0]) self.server_address.port = self.subscription_port except KeyboardInterrupt: print('KeyboardInterrupt') except Exception as e: print("No response, starting server here", e) s.sendto(bytes(self.host_ip, "UTF-8"), (self.broadcast_ip, self.negotiation_port)) s.close() self.stopAllThread() self.server_address.ip = self.host_ip self.server_address.port = self.subscription_port if (self.logFile != None): log_message = 'NegotiateServer- server address %s' % str( self.server_address) self.logFile.saveWithDate(log_message) self.carMap = Data4CarMap(256) # thread responsible for broadcasting itself as the server self.beacon_thread = ServerBeaconThread( threadID=self.threadID + 1, host_ip=self.host_ip, broadcast_ip=self.broadcast_ip, negotiation_port=self.negotiation_port, sleepDuration=1.9, logFile=self.logFile) self.beacon_thread.start() # thread responsible for collecting GPS data from clients self.server_thread = ServerThread( threadID=self.threadID + 2, address=self.server_address.asTuple(), carMap=self.carMap, logFile=self.logFile) self.server_thread.start() # thread responsible for sending GPS data to each registered vehicle self.forwarding_thread = Forward2CarThread( threadID=self.threadID + 3, car_communication_port=self.car_communication_port, carMap=self.carMap, period=1.0, logFile=self.logFile) self.forwarding_thread.start() # thread responsible for registering vehicles self.carSubscriber_thread = Listen4CarSubscriberThread( threadID=self.threadID + 4, host_ip=self.host_ip, car_subscription_port=self.car_subscription_port, carMap=self.carMap, logFile=self.logFile) self.carSubscriber_thread.start() print(str(time.time() - t) + " seconds elapsed")
if not q.empty(): r = q.get() if isinstance(r, MailDataFrame): print(r.data) else: for i in range(2): if r[-i] in ["\r", "\n"]: r = r[:-i] print(r) HOST = '127.0.0.1' SERVPORT = 42069 DESTPORT = 25 BACKLOG = 5 msg_q = Queue() log_q = Queue() client_thread = ClientThread((HOST, DESTPORT), msg_q, log_q, daemon=True) client_thread.start() log = Thread(target=logger, args=(log_q, ), daemon=True) log.start() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, SERVPORT)) i = 0 while True: s.listen(BACKLOG) cl_skt, addr = s.accept() t = ServerThread(cl_skt, msg_q, log_q, daemon=True) t.start() i = i + 1
class BrytonClient(QObject): connected = pyqtSignal() deviceReady = pyqtSignal() deviceOffline = pyqtSignal() error = pyqtSignal(str) BBVersion = pyqtSignal(str) refreshingTrackList = pyqtSignal() trackListProgress = pyqtSignal(str) trackListReady = pyqtSignal() statusMessage = pyqtSignal(str) uploadFinished = pyqtSignal() uploadFailed = pyqtSignal() uploadProgress = pyqtSignal(int) finalizingProgress = pyqtSignal(int) tracksDeleted = pyqtSignal() deleteFailed = pyqtSignal() def __init__(self, host='localhost', port_range=range(6776, 6781), server_host='localhost', server_port=24011, parent=None): super(BrytonClient, self).__init__(parent) self._host = host self._port = port_range[0] self._port_range = port_range self._server_port = None self._server_host = server_host self._socket = s = QTcpSocket(self) s.readyRead.connect(self._onReadyRead) s.connected.connect(self._onConnected) s.disconnected.connect(self._onDisconnected) s.error.connect(self._onSocketError) self.connected.connect(self._getState) self.deviceReady.connect(self._refreshTrackList) self.server = ServerThread(server_host, server_port, self) self.server.trackListUploaded.connect(self._onTrackListUploaded) self.server.trackDataUploaded.connect(self._onTrackDataUploaded) self.server.trackListReady.connect(self._onTracksUploaded) self.server.error.connect(self._onError) self.server.serverStarted.connect(self._onServerStarted) self.reset() self.server.start() def reset(self): self._last_req_id = 1 self._cid = None self._req_is_ack = False self._deviceReady = False self._current_status = 'connecting' self._state = CONNECTING self._track_count = 0 self._started = False self._aborted_by_error = False self._req_state_on_ack = False self._port = self._port_range[0] self._socket.abort() def is_connected(self): return self._cid is not None def is_server_started(self): return self._server_port is not None def start(self): self._started = True # If the server has not yet started we wait until the server has # been started before we start the client. if self.is_server_started(): self._doStart() else: self.statusMessage.emit('Starting internal server') def uploadToBrytonSport(self, session_id): self._state = UPLOAD_BRYTONSPORT self._writeRequest('$GetDevDataAll', data=[session_id, '"http://api.brytonsport.com/storages/put"']) # QTimer.singleShot(1500, self._getReqState) self._req_state_on_ack = True def deleteTracks(self, track_ids): self._state = DELETE_TRACKS self._writeRequest('$DelDevData', data=[self.server.session_id, '"{}"'.format(','.join(track_ids))]) self._req_state_on_ack = True def _doStart(self): log.debug('Starting client') self.statusMessage.emit('Connecting to BrytonBridge') self._connect() def _onServerStarted(self, port): log.debug('Internal server started') self._server_port = port self._server_addr = 'http://{0}:{1}'.format(self._server_host, self._server_port) if self._started: self._doStart() def _onTrackListUploaded(self, track_count): self._track_count = track_count self.trackListProgress.emit('loading track data') def _onTrackDataUploaded(self): self.trackListProgress.emit('processing track data') def _onTracksUploaded(self, track_list): self.track_list = track_list self.trackListReady.emit() def _onReadyRead(self): while self._socket.canReadLine(): line = str(self._socket.readLine()).rstrip() log.debug('readLine, %s', line) self._parseResponse(line) def _onConnected(self): log.debug('Connected') self._writeLine(['$Connect', '1']) def _connectionTimeoutTest(): if not self.is_connected() and not self._aborted_by_error: log.debug('No response from $Connect, aborting.') # if we are not connected by the time we get here # we try the next port. # this can happen if another server is running on the port and let # us connect, but does not respond to the $Connect command self._socket.abort() self._connect(1) QTimer.singleShot(2000, _connectionTimeoutTest) def _onDisconnected(self): log.debug('Disconnected') if self.is_connected() and not self._aborted_by_error: self._onError('Lost connection to BrytonBridge') def _onSocketError(self, code): if code == QTcpSocket.ConnectionRefusedError: log.debug('Connection refused') # Try the next port self._connect(1) else: log.debug('Socket error "%s"', self._socket.errorString()) self._onError(self._socket.errorString()) def _onError(self, msg): log.debug('Error "%s"', msg) self._aborted_by_error = True self._socket.abort() self.error.emit(msg) def _refreshTrackList(self): self.refreshingTrackList.emit() self._current_status = 'refresh-tracklist' self._state = REFRESH_TRACKLIST self._track_count = None self._getState() def _getState(self): self._writeRequest('$GetState') def _getReqState(self): self._writeRequest('$GetState', req_id=self._last_req_id) def _getDevState(self): self._writeRequest('$GetDevState') def _getDevDataList(self): self._writeRequest('$GetDevDataList', data=[self.server.session_id, '"{0}/{1}"'.format(self._server_addr, 'track_list')]) self._req_state_on_ack = True def _getDevDataAll(self): self._writeRequest('$GetDevDataAll', data=[self.server.session_id, '"{0}/{1}"'.format(self._server_addr, 'track_data')]) self._req_state_on_ack = True def _finalize(self): log.debug('Finalizing') self._state = FINALIZING self._writeRequest('$Finalize') self._req_state_on_ack = True def _writeRequest(self, cmd, data=None, req_id=None): self._req_is_ack = False if req_id is None: req_id = self._nextReqId() req = [cmd, req_id, self._last_resp_id] if self.is_connected(): req.append(self._cid) if data is not None: req.extend(data) self._writeLine(req) def _writeLine(self, cmd): log.debug('writeLine, %s', ','.join(map(str, cmd))) self._socket.write(','.join(map(str, cmd))+'\r\n') def _writeACK(self, resp_id): self._last_resp_id = resp_id self._writeLine(['$ACK', resp_id, self._cid]) def _parseResponse(self, resp): cmd, rest = resp.split(',', 1) if cmd == '$NAK': self._parseNAK(rest) elif not self.is_connected(): if not self._last_req_confirmed(): self._parseACK(cmd, rest) elif cmd == '$CID': self._parseCID(rest) else: self._onError('Unexpected Response') elif cmd == '$DevState': # DevState can be sendt without being requested when # the device is pluggen in or out while connected to # BrytonBridge self._parseDevState(rest) elif not self._last_req_confirmed(): self._parseACK(cmd, rest) elif cmd == '$State': self._parseState(rest) else: self._onError('Unexpected Response') def _parseACK(self, cmd, resp): if cmd != '$ACK': self._onError('Unexpected Response') return if not self.is_connected(): if resp == '1': self._set_req_confirmed() else: req_id, cid = resp.split(',') if self._validateResponse(req_id, cid): self._set_req_confirmed() if self._req_state_on_ack: self._req_state_on_ack = False QTimer.singleShot(1000, self._getReqState) def _parseCID(self, resp): resp_id, req_id, cid = resp.split(',') if req_id != str(self._last_req_id): self._onError('Unexpected Response') return self._cid = cid self._writeACK(resp_id) self.connected.emit() def _parseNAK(self, resp): msg = resp.split(',')[-1] if msg == 'undefined': msg = 'Unknown error response from BrytonBridge' elif msg == 'NOT SUPPORT MULTI CONNECTION': msg = 'You can only have one connection to BrytonBridge open.'\ ' If you have your web browser opened at brytonsport.com please'\ ' close the browser and retry.' self._onError(msg) def _parseDevState(self, resp): resp_id, _, _, name, rev, firmware, _, serial, size, used, state = resp.split(',') self.dev_state = state = { 'name' : name, 'rev' : rev, #Not sure what this value is 'firmware' : firmware, 'serial' : serial, 'total_storage' : int(size), 'storage_used' : int(used), 'state' : state, } self._writeACK(resp_id) if state['state'] == 'READY' and not self._deviceReady: self._deviceReady = True self.deviceReady.emit() elif state['state'] == 'OFFLINE': self._deviceReady = False self.deviceOffline.emit() def _parseState(self, resp): resp_id, req_id, cid, bb_version, status, progress, _ = resp.split(',') if not self._validateResponse(req_id, cid): return if self._current_status == 'connecting': self.BBVersion.emit(bb_version) self.state = state = { 'req_id' : int(req_id), 'bb_version' : bb_version, 'state' : status, 'progress' : progress, } self._writeACK(resp_id) if state['progress'] == 'ERROR': msg = 'Request failed' if self._state == UPLOAD_BRYTONSPORT: log.debug('Upload failed') self._brytonSportUploadFailed() return elif self._state in (FINALIZING, DELETE_TRACKS): log.debug('Delete Failed') self._state = IDLE self.deleteFailed.emit() return elif self._state in (REFRESH_TRACKLIST, WAITING_TRACKDATA, WAITING_TRACKDATA): msg = '''Request failed. Make sure the hostname of the internal server is correct.''' self._onError(msg) return state['progress'] = float(state['progress']) if state['state'] == 'READY': if self._state == CONNECTING: self._getDevState() elif self._state == REFRESH_TRACKLIST: self._state = WAITING_TRACKLIST self._getDevDataList() # QTimer.singleShot(1000, self._getReqState) elif self._state == WAITING_TRACKLIST: if self._track_count is None: # Bryton bridge is finished sending the data, but the server # thread is not yet finished processing the data, so we wait. QTimer.singleShot(1000, self._getReqState) return elif self._track_count == 0: self._current_status = '' self._onTracksUploaded([]) return self._getDevDataAll() self._state = WAITING_TRACKDATA # QTimer.singleShot(1000, self._getReqState) elif self._state == WAITING_TRACKDATA: self._state = IDLE elif self._state == UPLOAD_BRYTONSPORT: self._state = IDLE self.uploadFinished.emit() log.debug('Upload finished') elif self._state == DELETE_TRACKS: self._state = IDLE self._finalize() elif self._state == FINALIZING: log.debug('Finalize complete') self._state = IDLE self.tracksDeleted.emit() self._refreshTrackList() elif state['state'] == 'PROGRESSING': QTimer.singleShot(2000, self._getReqState) if self._state == UPLOAD_BRYTONSPORT: log.debug('Upload progress %f', state['progress']) self.uploadProgress.emit(state['progress']*100) elif self._state == FINALIZING: log.debug('Finalize progress %f', state['progress']) self.finalizingProgress.emit(state['progress']*100) def _connect(self, incr_port=0): port = self._port + incr_port if port in self._port_range: self._port = port self._socket.connectToHost(self._host, port) else: self._onError('Could not connect to BrytonBridge') def _validateResponse(self, req_id, cid): if req_id != str(self._last_req_id) or cid != self._cid: self._onError('Unexpected response from BrytonBridge') return False return True def _brytonSportUploadFailed(self): self._state = IDLE self.uploadFailed.emit() def _nextReqId(self): self._last_req_id += 1 return self._last_req_id def _last_req_confirmed(self): return self._req_is_ack def _set_req_confirmed(self): self._req_is_ack = True
def test_validation_2_3(self): """ test_validation_3 Filter 2 against filter_validation 3 """ saved = SavedFilter(self.lc, 2) # Get loan list response = self.lc.session.get('/filter_validation', query={'id': 3}) json_response = response.json() self.loan_list = json_response['loanFractions'] # Validate, should fail on 'exclude_invested' try: saved.validate(self.loan_list) assert False, 'Test should fail on grade' except FilterValidationError as e: print e.criteria self.assertTrue(matches('grade', e.criteria)) if __name__ == '__main__': # Start the web-server in a background thread http = ServerThread() http.start() # Run tests unittest.main() # Stop threads http.stop()
from threading import Thread from server import ServerThread import socket import sys port = sys.argv[1] path = sys.argv[2] address = '127.0.0.1' socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_server.bind((address, int(port))) socket_server.listen() while (True): print("Esperando conexão ....") conn, addr = socket_server.accept() newThread = ServerThread(address, port, conn, addr, path) newThread.start()