def __init__(self): threading.Thread.__init__(self) self.env = backend.Environment() addr = ('127.0.0.1', 12500) self.sock = backend.TCPSocket.connection(self.env, addr) self.client = Client(self.sock) self.sock.sock.setblocking(True)
def start_simulation(simulator, description='', extra_options=None): """Start the simulation process for ``simulation``. *simulation* is the instance of your API implementation (see :class:`Simulator`). *description* may override the default description printed with the help on the command line. *extra_option* may be a list of options for `docopt <http://docopt.org/>`_ (example: ``['-e, --example Enable example mode']``). Commandline arguments are passed to :meth:`Simulator.configure()` so that your API implementation can handle them. """ OK, ERR = 0, 1 args = _parse_args(description or 'Start the simulation service.', extra_options or []) logging.basicConfig(level=args['--log-level']) sim_name = simulator.__class__.__name__ try: logger.info('Starting %s ...' % sim_name) env = backend.Environment() simulator.configure(args, backend, env) # Setup simpy.io and start the event loop. addr = _parse_addr(args['HOST:PORT']) sock = backend.TCPSocket.connection(env, addr) sock = Message(env, Packet(sock, max_packet_size=10 * 1024 * 1024)) simulator.mosaik = MosaikProxy(sock) proc = env.process(run(sock, simulator)) env.run(until=proc) except ConnectionRefusedError: logger.error('Could not connect to mosaik.') return ERR except (ConnectionError, KeyboardInterrupt): pass # Exit silently. except Exception as exc: if type(exc) is OSError and exc.errno == 10057: # ConnectionRefusedError in Windows O.o logger.error('Could not connect to mosaik.') return ERR print('Error in %s:' % sim_name) import simpy._compat as compat if compat.PY2: compat.print_chain(type(exc), exc, exc.__traceback__) else: traceback.print_exc() # Exit loudly print('---------%s-' % ('-' * len(sim_name))) return ERR finally: sock.close() simulator.finalize() return OK
def env(request): env = select.Environment() request.addfinalizer(env.close) return env
raise ValueError content_type = mimetypes.guess_type(req_path)[0] if content_type.startswith('text/'): content_type = '%s; charset=utf-8' % content_type return content_type, open(req_path, 'rb').read() def set_new_data(self, time, progress, node_data): self.data_buf['time'] = time self.data_buf['progress'] = progress self.data_buf['node_data'].append(node_data) def _reset_data_buf(self): data = self.data_buf self.data_buf = { 'time': None, 'progress': None, 'node_data': [], } return data if __name__ == '__main__': addr = ('localhost', 8000) env = backend.Environment() server_sock = backend.TCPSocket.server(env, addr) server = Server(env, server_sock) env.run()
def start_simulation(simulator, description='', extra_options=None): """Start the simulation process for ``simulation``. *simulation* is the instance of your API implementation (see :class:`Simulator`). *description* may override the default description printed with the help on the command line. *extra_option* may be a list of options for `docopt <http://docopt.org/>`_ (example: ``['-e, --example Enable example mode']``). Commandline arguments are passed to :meth:`Simulator.configure()` so that your API implementation can handle them. """ OK, ERR = 0, 1 args = _parse_args(description or 'Start the simulation service.', extra_options or []) logging.basicConfig(level=args['--log-level']) remote_flag = args['--remote'] if '--remote' in args.keys() else False sim_name = simulator.__class__.__name__ sock = None srv_sock = None try: logger.info('Starting %s ...' % sim_name) env = backend.Environment() simulator.configure(args, backend, env) # Setup simpy.io and start the event loop. addr = _parse_addr(args['HOST:PORT']) # Interception for remote simulators if remote_flag: srv_sock = backend.TCPSocket.server(env, addr) start_timeout = env.timeout(int(args['--timeout'])) def greeter(): """ Handshake with mosaik to establish a socket for communication """ logger.info('Waiting for connection from mosaik') accept_con = srv_sock.accept() results = yield accept_con | start_timeout if start_timeout in results: raise RuntimeError( 'Connection from mosaik not received in time') else: sock = results[accept_con] return sock sock = env.run(until=env.process(greeter())) else: sock = backend.TCPSocket.connection(env, addr) sock = Message(env, Packet(sock, max_packet_size=10 * 1024 * 1024)) simulator.mosaik = MosaikProxy(sock) proc = env.process(run(sock, simulator)) env.run(until=proc) except ConnectionRefusedError: logger.error('Could not connect to mosaik.') errstr = 'INFO:mosaik_api:Starting ExampleSim ...\n' + 'ERROR:mosaik_api:Could not connect to mosaik.\n' return errstr except (ConnectionError, KeyboardInterrupt): pass # Exit silently. except Exception as exc: if type(exc) is OSError and exc.errno == 10057: # ConnectionRefusedError in Windows O.o logger.error('Could not connect to mosaik.') return ERR print('Error in %s:' % sim_name) traceback.print_exc() # Exit loudly print('---------%s-' % ('-' * len(sim_name))) return ERR finally: if sock is not None: sock.close() if srv_sock is not None: srv_sock.close() simulator.finalize() return OK