Esempio n. 1
1
int main()
{
	//load config
	int ret = ZBus::Instance().LoadConfig("channel_temp.xml");

	if (ret != 0)
	{
		printf("ret %d\n", ret);
		print_error();
		exit(1);
	}

	//init channels
	ret = ZBus::Instance().InitChannels(20001);

	if (ret != 0)
	{
		printf("init channel failed\n");
		print_error();
		exit(1);
	}

	Channel* pchannel = ZBus::Instance().GetChannel(20001, 10001);

	if (!pchannel)
	{
		printf("get channel failed\n");
		print_error();
		exit(1);
	}

	Reactor reactor;
	ReactorHandler handler;

	reactor.Initialize(1);
	ret = reactor.RegisterChannel(pchannel, &handler);

	if (ret < 0)
	{
		printf("register channel failed\n");
		return -1;
	}

	int i = 10;
	while (i) {
		reactor.EventLoop(1000);

		char str[12] = "hello world";
		pchannel->Send(str, sizeof(str));

		i--;
	}

	return 0;
}
Esempio n. 2
0
int main(int argc, char** argv) {
    setup_crash_handlers();

    po::options_description desc ("Start Multilink server child");
    desc.add_options()
        ("help", "produce help message")
        ("sock-fd",
         po::value<int>(), "FD of socket to start RPC server on")
        ("target-port",
         po::value<int>(), "target port (if using connect target)")
        ("target-host",
         po::value<string>()->default_value("127.0.0.1"), "target host")
        ("connect-bind",
         po::value<string>()->default_value("0.0.0.0"), "bind to this host when creating outbound TCP connections")
        ("tun-prefix",
         po::value<string>()->default_value("mlc"), "TUN device name prefix (if using terminate target)")
        ("dry-run", "only verify that options make sense");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << "\n";
        return 0;
    }

    if (vm.count("target-port") && vm.count("tun-prefix")) {
        std::cout << desc << "\n";
        return 1;
    }

    if (vm.count("dry-run")) return 0;

    Process::init();

    Reactor reactor;
    Server server {reactor};

    auto callback = [&](std::shared_ptr<RPCStream> stream,
                        Json message) {
        server.callback(stream, message);
    };

    if (vm.count("target-port")) {
        server.setup_connect_target(vm["target-host"].as<string>(),
                                    vm["target-port"].as<int>());
    } else {
        server.setup_terminate_target(vm["connect-bind"].as<string>());
    }

    if (vm.count("tun-prefix")) {
        string prefix = vm["tun-prefix"].as<string>();
        string name = prefix + random_hex_string(15 - prefix.size());
        server.setup_tun(name);
    }

    auto rpcserver = RPCServer::create(reactor, vm["sock-fd"].as<int>(), callback);
    reactor.run();
}
Esempio n. 3
0
void processTimeEclapsed( evutil_socket_t sock, short flags, void * args )
{
	Reactor* reactor = (Reactor*)args;
	printf("定时器!!!\n");
	reactor->scanLibeventContainer();
	reactor->scanUnusedChannel(20);
}
Esempio n. 4
0
int main(int argc, char** argv)
{
	Reactor *reactor = Reactor::getInstance();
	reactor->callLater(30, &print_hello_world);
	reactor->run();
	return 0;
}
Esempio n. 5
0
void* work_run(void* arg) {
    printf("create pthread %d\n", pthread_self());

    BufBlock_t* block = NULL;
    BufBlock_t* new_block = NULL;

    Reactor* reactor = (Reactor*) arg;

    while (!stop) {
        reactor->handle_events(1000);

        //将接收到的协议 串行处理
        while ((block=g_receive_queue.pop_queue()) != NULL) {
            char* send_data;
            int send_len = 0;

            int ret_code = dll.handle_process((char*)block->page_base, block->buf_head.len, &send_data, &send_len, &(block->buf_head.sk));

            new_block = alloc_block(send_len);
            new_block->buf_head = block->buf_head;
            new_block->buf_head.len = send_len;
            memcpy(new_block->page_base, send_data, send_len);

            free_block(block);
            if (send_len != 0 && g_server_conf.need_free_send_buf) {
                free(send_data);
            }

            if (ret_code == -1) { //关闭链接
                PUSH_ERRMSG(FIN_BLOCK);
            }
            else if (send_len == 0 || send_len > 8388608) { //长度不对
                LOG4CPLUS_INFO(log4cplus::Logger::getRoot(), "socket fd="<<new_block->buf_head.sk.socket<<" send too large pkg");
                PUSH_ERRMSG(CLEAR_BLOCK);
            }
            else if (send_len > 0) {
                new_block->buf_head.buf_type = DATA_BLOCK;
                if (1 == ret_code) {
                    new_block->buf_head.buf_type |= FIN_BLOCK;
                }

                if (stop) {
                    return ((void *)0);
                }

                HandlerBase* h = reactor->get_handler(new_block->buf_head.sk.socket);
                if (NULL == h) {
                    free_block(new_block);
                    continue;
                }

                if (!h->push_buf(new_block)) {
                    free_block(new_block);
                }
            }
        }
    }
}
Esempio n. 6
0
void enableRead( evutil_socket_t sock, short flags, void * args )
{
	Reactor* reactor = (Reactor*)args;
	std::string addr = reactor->findaddrbysock(sock);
	Channel_var mychannel = reactor->mChannelTable->getChannel(addr);
	ByteBuffer_var readBuf = mychannel->getReadBuffer();
	printf("capacity %d, size %d\n", readBuf->Capacity(), readBuf->Size());
	int ret = 0;
	int offset = readBuf->Size();
	while((ret = recv(sock, readBuf->Inout() + offset, readBuf->Capacity(), 0)) > 0) {
		offset += ret;
	}
	ret = offset - readBuf->Size();
	readBuf->Size(offset);
	
	if(ret > 0)
	{
		mychannel->setTimestamp();
		while(1) {
			printf("sock %d, ret %d\n", sock, ret);
			int length = readBuf->getInt();
			int headerlength = readBuf->getInt();
			printf("length %d, headerlength %d\n", length, headerlength);
			readBuf->adjustReadpos(-8);
			if(!readBuf->isFullPackage(length+4)) {
				return (void)0;
			}

			readBuf->adjustReadpos(8);
			Byte_var headerdata = new Byte(headerlength+1);
			headerdata->setBuffer(readBuf->getBytes(headerlength), headerlength);
			RemotingCommand_var responseFuture = RemotingCommand::decode(headerdata->getBuffer());
			printf("header %s\n", headerdata->getBuffer());

			Byte_var bodydata = new Byte(length-4-headerlength);
			bodydata->setBuffer(readBuf->getBytes(length-4-headerlength), length-4-headerlength);
			
			responseFuture->setBody(Byte_var::Duplicate(bodydata));
			printf("body length %d\n", responseFuture->getBody()->size());
			
			reactor->setResponse(RemotingCommand_var::Duplicate(responseFuture));
			if(responseFuture->getCode() != 40) {
				reactor->notifyWorker(responseFuture->getOpaque());
			}
			else {
			}
			ret -= length+4;
			if(ret <= 0)
				break;
		}
		readBuf->Reset();
	}
	else
	{
		//连接断开
		printf("server closed\n");
	}
}
Esempio n. 7
0
ThreadPool::Scavenger::~Scavenger ()
    {
    TRACE_CALL;

    Reactor* reactor = reactorGet ();

    if (reactor)
	reactor->timerRemove (this);
    }
Esempio n. 8
0
void Reactor::handle_signal(int signal)
{
	std::clog
		<< "Signal "
		<< signal
		<< "caught. Terminating mainloop"
		<< std::endl;
    Reactor* reactor = getInstance();
    reactor->stop();
}
Esempio n. 9
0
int main()
{
    Eventhandler *evh=new Server;
    Reactor re;
    struct timeval tv;

    gettimeofday(&tv,NULL);
    re.register_handler(evh);
    re.waitEvents(&tv,doSthRead);
}
Esempio n. 10
0
  // called by Connector.connect() after connection successfully established
  virtual int open(void *) {
    Reactor* reactor = this->getReactor();
    Client_Timeout_Handler* timeOutHandler = new Client_Timeout_Handler;
    TimeValue tv1(0);
    TimeValue tv2(TimeSpec);
    if(reactor->scheduleTimer(timeOutHandler, this, tv1, tv2) == -1) {
      cerr << "scheduleTimer() failed!! \n";
      return -1;
    }

    return SvcHandler::open(0);
  }
Esempio n. 11
0
Reactor* Reactor::instance()
{
    if (NULL == reactorM)
    {
        boost::lock_guard<boost::mutex> lock(reactorInstanceMutex);
        if (NULL == reactorM)
        {
            Reactor* reactor = new Reactor();
            reactorInstanceReleaser.reset(reactor);
            reactor->start();
            reactorM = reactor;
        }
    }
    return reactorM;
}
Esempio n. 12
0
int main() {
  Connector<ClientHandler> connector(Reactor::instance());
  InetAddr connAddr(ServerPort, ServerIp);
  ClientHandler* handler = 0;

  // connect() will make a new ClientHandler and assign its address to handler when success
  if (connector.connect(handler, connAddr) == -1) {
    cout << "SubscribeClient::init, connect error: " << OS::strerror(OS::map_errno(OS::last_error())) << endl;
    return -1;
  }

  Reactor* reactor = handler->getReactor();
  reactor->runReactorEventLoop();

  return 0;
}
Esempio n. 13
0
void EventDriver::dispatchEvent (MZEventDispatcher* dispatcher, int events)
{
    Reactor *r;
    while ((r = timeoutReactors.removeFront())) {
        r->mask &= ~EVENT_TIMEOUT;
        tryUnbind(r);

        log.debug("process timeout event. mask:%d r:%08x\n", r->mask, r);
        r->processEvent(EVENT_TIMEOUT);
    }

    {
        // consume event
        char c;
        while (read(timeoutFds[0], &c, sizeof(c)) > 0);
    }
}
Esempio n. 14
0
ConnectorBase::ConnectorBase(Reactor& reactor,
		auto_ptr<HandlerCreatorStrategyBase> handler_creator_stg,
		auto_ptr<FilterCreatorStrategyBase> filter_stg,
		int flag)
: sp_reactor_impl_(reactor.impl()),
  sp_creator_stg_(handler_creator_stg),
  sp_filter_stg_(filter_stg),
  flag_(flag)
{
}
Esempio n. 15
0
// When data is available for reading, accept the connection
// and spawn a new handler.
bool
Acceptor::on_read(Reactor& r) {
  // FIXME: The error handling stuff is not good.
  Connection* c;
  try {
    c = new Connection(rc().accept());
  } catch(System_error&) {
    perror("error");
    r.stop();
    return false;
  } catch(std::runtime_error& err) {
    std::cout << err.what() << '\n';
    r.stop();
    return false;
  }

  // Register the connection.
  r.add_handler(c);
  return true;
}
Esempio n. 16
0
int main(void) {
    pipe(pipe_);

    Pipe pipeio(pipe_[0]);

    InnerChange inner;

    EventHandler* eventHandler = new PipeHandler(pipeio, inner);

    Reactor * reactor = new Reactor(REACTORSIZE);

    //ReactorMask mask = EventHandler::READ_MASK | EventHandler::WRITE_MASK ;
    ReactorMask mask = EventHandler::READ_MASK;
    reactor->Register(eventHandler, mask);

    boost::thread *readt = new boost::thread(boost::bind(&printout));
    boost::thread *writet = new boost::thread(boost::bind(&Reactor::Run, reactor));

    readt->join();
    writet->join();

    return 1;
}
Esempio n. 17
0
void enableWrite(evutil_socket_t sock, short flags, void * args)
{
	Reactor* reactor = (Reactor*)args;
	std::string addr = reactor->findaddrbysock(sock);
	//向对应的socket发送 连接成功可以发送信号
	//对应的channel处在未连接状态,所以这个异步事件为判断connect成功
	//此处应删除可写事件,防止再次触发
	Channel_var mychannel = reactor->mChannelTable->getChannel(addr);
	if(!mychannel->IsRunOutOfTime(3)) {
		//成功连接上
		mychannel->setTimestamp();
		mychannel->setState(CHANNEL_CONNECTED);
		reactor->addReadable(mychannel->getSocket());
		std::cout << "catch writable" << std::endl;
		reactor->notifyChannel(sock);
	}
	else {
		//等待超时
		mychannel->setState(CHANNEL_ERROR);
		std::cout << "run out of time" << std::endl;
		reactor->notifyChannel(sock);
	}
}
Esempio n. 18
0
Future<unit> write_all(Reactor& reactor, StreamPtr out, Buffer data) {
    std::shared_ptr<Buffer> datap = std::make_shared<Buffer>(data);
    Completer<unit> completer;

    auto write_ready = [completer, datap, out]() {
        if(datap->size == 0) return;

        size_t len = out->write(*datap);
        *datap = datap->slice(len);

        if(datap->size == 0)
            completer.result(unit());
    };

    out->set_on_write_ready(write_ready);

    reactor.schedule(write_ready);

    return completer.future();
}
Esempio n. 19
0
    void run(string listen_host, int listen_port, std::vector<string> child_options,
             TlsStream::ServerPskFunc identity_callback) {
        this->child_options = child_options;

        TCP::listen(reactor, listen_host, listen_port, [&](FDPtr fd) {
            LOG("incoming connection");
            auto stream = TlsStream::create(reactor, fd);
            stream->set_cipher_list("PSK-AES256-CBC-SHA");
            stream->set_psk_server_callback(identity_callback);
            stream->handshake_as_server();

            ioutil::read(stream, 128).then([this, stream](ByteString welcome) -> unit {
                // TODO: check identity
                string multilink_id = welcome.as_buffer().slice(0, 16);
                string link_name = welcome.as_buffer().slice(16);
                while (link_name.back() == 0) link_name.pop_back();

                get_or_create(multilink_id).add_link(stream, link_name);
                return {};
            }).ignore();
        }).ignore();

        reactor.run();
    }
Esempio n. 20
0
// Miscellaneous
int LuaExports::dropItemReactor(lua_State *luaVm) {
	int32_t itemid = lua_tointeger(luaVm, 1);
	int16_t amount = 1;
	if (lua_isnumber(luaVm, 2)) {
		amount = lua_tointeger(luaVm, 2);
	}
	Reactor *reactor = getReactor(luaVm);
	Player *player = getPlayer(luaVm);
	Drop *drop;
	if (GameLogicUtilities::isEquip(itemid)) {
		Item f(itemid, true);
		drop = new Drop(reactor->getMapId(), f, reactor->getPos(), player != nullptr ? player->getId() : 0);
	}
	else {
		Item f(itemid, amount);
		drop = new Drop(reactor->getMapId(), f, reactor->getPos(), player != nullptr ? player->getId() : 0);
	}
	drop->setTime(player != nullptr ? 100 : 0); // FFA if player isn't around
	drop->doDrop(reactor->getPos());
	return 0;
}
Esempio n. 21
0
	int lws_client_callback(struct libwebsocket_context* context, struct libwebsocket *ws, enum libwebsocket_callback_reasons reason, void *user, void *data, size_t len){
		const struct libwebsocket_protocols* lws_protocol = (ws == NULL ? NULL : libwebsockets_get_protocol(ws));
		int idx = lws_protocol? lws_protocol->protocol_index : 0;

		Connection* conn;

		Reactor* reactor = NULL;
		Protocol* protocol;

		for (int i=0; i<(int)reactors.size(); i++){
			if (reactors[i]->getContext() == context){
				reactor =  reactors[i];
				protocol = reactor->protocol(idx);
				conn = ((Client*) reactor)->getConnection();
				if (conn){
					conn->context = context;
				}
				break;
			} else {
			}
		}

		ofLog( OF_LOG_VERBOSE, "[ofxLibwebsockets] " + getCallbackReason(reason) );

		if (reason == LWS_CALLBACK_CLIENT_ESTABLISHED ){
			libwebsocket_callback_on_writable(context, ws);
		} else if (reason == LWS_CALLBACK_CLOSED){
		}

		switch (reason)
		{
			// cases we may use in the future
			case LWS_CALLBACK_CONFIRM_EXTENSION_OKAY:
			case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
			case LWS_CALLBACK_PROTOCOL_INIT: // this may be useful, says we're OK to allocate protocol data
			case LWS_CALLBACK_WSI_CREATE:

			case LWS_CALLBACK_HTTP_BODY_COMPLETION:
			case LWS_CALLBACK_HTTP_FILE_COMPLETION:
			case LWS_CALLBACK_HTTP_WRITEABLE:

			case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
				return 0;

			// check if we allow this connection (default is always yes)
			case LWS_CALLBACK_FILTER_HTTP_CONNECTION:
			case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
				if (protocol != NULL){
					return reactor->_allow(ws, protocol, (int)(long)user)? 0 : 1;
				} else {
					return 0;
				}

			// need to serve up an HTTP file
			case LWS_CALLBACK_HTTP:
				if ( reactor != NULL){
					return reactor->_http(ws, (char*)data);
				} else {
					return 0;
				}

			// we're not really worried about these at the moment
			case LWS_CALLBACK_CLOSED_HTTP:
			case LWS_CALLBACK_ADD_POLL_FD:
			case LWS_CALLBACK_DEL_POLL_FD:
			case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
			case LWS_CALLBACK_LOCK_POLL:
			case LWS_CALLBACK_UNLOCK_POLL:
			case LWS_CALLBACK_GET_THREAD_ID:
			case LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH:
			case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
				return 1;

			// catch-all for most important events:
			// LWS_CALLBACK_CLIENT_CONNECTION_ERROR
			// LWS_CALLBACK_CLIENT_ESTABLISHED
			// LWS_CALLBACK_RECEIVE
			// LWS_CALLBACK_CLIENT_RECEIVE
			// LWS_CALLBACK_CLIENT_RECEIVE_PONG
			// LWS_CALLBACK_CLIENT_WRITEABLE
			default:
				if ( reactor != NULL ){
					//conn = *(Connection**)user;
					if (conn && conn->ws != ws && ws != NULL){
						conn->ws = ws;
						conn->context = context;
					}
					return reactor->_notify(conn, reason, (char*)data, len);
				} else {
					return 0;
				}
		}

		return 1; // FAIL (e.g. unhandled case/break in switch)
	}
Esempio n. 22
0
// Mob
int LuaExports::spawnMobReactor(lua_State *luaVm) {
	int32_t mobid = lua_tointeger(luaVm, -1);
	Reactor *reactor = getReactor(luaVm);
	lua_pushinteger(luaVm, Maps::getMap(reactor->getMapId())->spawnMob(mobid, reactor->getPos()));
	return 1;
}
Esempio n. 23
0
void runexample()
{
    // use reaction mechanism GRI-Mech 3.0
    IdealGasMix gas("gri30.cti", "gri30");

    // create a reservoir for the fuel inlet, and set to pure methane.
    Reservoir fuel_in;
    gas.setState_TPX(300.0, OneAtm, "CH4:1.0");
    fuel_in.insert(gas);
    double fuel_mw = gas.meanMolecularWeight();

    // create a reservoir for the air inlet
    Reservoir air_in;
    IdealGasMix air("air.cti");
    gas.setState_TPX(300.0, OneAtm, "N2:0.78, O2:0.21, AR:0.01");
    double air_mw = air.meanMolecularWeight();
    air_in.insert(gas);

    // to ignite the fuel/air mixture, we'll introduce a pulse of radicals.
    // The steady-state behavior is independent of how we do this, so we'll
    // just use a stream of pure atomic hydrogen.
    gas.setState_TPX(300.0, OneAtm, "H:1.0");
    Reservoir igniter;
    igniter.insert(gas);


    // create the combustor, and fill it in initially with N2
    gas.setState_TPX(300.0, OneAtm, "N2:1.0");
    Reactor combustor;
    combustor.insert(gas);
    combustor.setInitialVolume(1.0);


    // create a reservoir for the exhaust. The initial composition
    // doesn't matter.
    Reservoir exhaust;
    exhaust.insert(gas);


    // lean combustion, phi = 0.5
    double equiv_ratio = 0.5;

    // compute fuel and air mass flow rates
    double factor = 0.1;
    double air_mdot = factor*9.52*air_mw;
    double fuel_mdot = factor*equiv_ratio*fuel_mw;

    // create and install the mass flow controllers. Controllers
    // m1 and m2 provide constant mass flow rates, and m3 provides
    // a short Gaussian pulse only to ignite the mixture
    MassFlowController m1;
    m1.install(fuel_in, combustor);
    m1.setMassFlowRate(fuel_mdot);

    // Now create the air mass flow controller.  Note that this connects
    // two reactors with different reaction mechanisms and different
    // numbers of species. Downstream and upstream species are matched by
    // name.
    MassFlowController m2;
    m2.install(air_in, combustor);
    m2.setMassFlowRate(air_mdot);


    // The igniter will use a Gaussian 'functor' object to specify the
    // time-dependent igniter mass flow rate.
    double A = 0.1;
    double FWHM = 0.2;
    double t0 = 0.5;
    Gaussian igniter_mdot(A, t0, FWHM);

    MassFlowController m3;
    m3.install(igniter, combustor);
    m3.setFunction(&igniter_mdot);

    // put a valve on the exhaust line to regulate the pressure
    Valve v;
    v.install(combustor, exhaust);
    double Kv = 1.0;
    v.setParameters(1, &Kv);

    // the simulation only contains one reactor
    ReactorNet sim;
    sim.addReactor(combustor);

    // take single steps to 6 s, writing the results to a CSV file
    // for later plotting.
    double tfinal = 1.0;
    double tnow = 0.0;
    double tres;

    std::ofstream f("combustor_cxx.csv");
    std::vector<size_t> k_out {
        gas.speciesIndex("CH4"),
        gas.speciesIndex("O2"),
        gas.speciesIndex("CO2"),
        gas.speciesIndex("H2O"),
        gas.speciesIndex("CO"),
        gas.speciesIndex("OH"),
        gas.speciesIndex("H"),
        gas.speciesIndex("C2H6")
    };

    while (tnow < tfinal) {
        tnow += 0.005;
        sim.advance(tnow);
        tres = combustor.mass()/v.massFlowRate();
        f << tnow << ", "
          << combustor.temperature() << ", "
          << tres << ", ";
        ThermoPhase& c = combustor.contents();
        for (size_t i = 0; i < k_out.size(); i++) {
            f << c.moleFraction(k_out[i]) << ", ";
        }
        f << std::endl;
    }
    f.close();
}
Esempio n. 24
0
void ReactorNet::initialize()
{
    size_t n, nv;
    char buf[100];
    m_nv = 0;
    m_reactors.clear();
    m_nreactors = 0;
    writelog("Initializing reactor network.\n", m_verbose);
    if (m_nr == 0)
        throw CanteraError("ReactorNet::initialize",
                           "no reactors in network!");
    size_t sensParamNumber = 0;
    for (n = 0; n < m_nr; n++) {
        if (m_r[n]->type() >= ReactorType) {
            m_r[n]->initialize(m_time);
            Reactor* r = (Reactor*)m_r[n];
            m_reactors.push_back(r);
            nv = r->neq();
            m_size.push_back(nv);
            m_nparams.push_back(r->nSensParams());
            std::vector<std::pair<void*, int> > sens_objs = r->getSensitivityOrder();
            for (size_t i = 0; i < sens_objs.size(); i++) {
                std::map<size_t, size_t>& s = m_sensOrder[sens_objs[i]];
                for (std::map<size_t, size_t>::iterator iter = s.begin();
                        iter != s.end();
                        ++iter) {
                    m_sensIndex.resize(std::max(iter->second + 1, m_sensIndex.size()));
                    m_sensIndex[iter->second] = sensParamNumber++;
                }
            }
            m_nv += nv;
            m_nreactors++;

            if (m_verbose) {
                sprintf(buf,"Reactor %s: %s variables.\n",
                        int2str(n).c_str(), int2str(nv).c_str());
                writelog(buf);
                sprintf(buf,"            %s sensitivity params.\n",
                        int2str(r->nSensParams()).c_str());
                writelog(buf);
            }
            if (m_r[n]->type() == FlowReactorType && m_nr > 1) {
                throw CanteraError("ReactorNet::initialize",
                                   "FlowReactors must be used alone.");
            }
        }
    }

    m_connect.resize(m_nr*m_nr,0);
    m_ydot.resize(m_nv,0.0);
    size_t i, j, nin, nout, nw;
    ReactorBase* r, *rj;
    for (i = 0; i < m_nr; i++) {
        r = m_reactors[i];
        for (j = 0; j < m_nr; j++) {
            if (i == j) {
                connect(i,j);
            } else {
                rj = m_reactors[j];
                nin = rj->nInlets();
                for (n = 0; n < nin; n++) {
                    if (&rj->inlet(n).out() == r) {
                        connect(i,j);
                    }
                }
                nout = rj->nOutlets();
                for (n = 0; n < nout; n++) {
                    if (&rj->outlet(n).in() == r) {
                        connect(i,j);
                    }
                }
                nw = rj->nWalls();
                for (n = 0; n < nw; n++) {
                    if (&rj->wall(n).left() == rj
                            && &rj->wall(n).right() == r) {
                        connect(i,j);
                    } else if (&rj->wall(n).left() == r
                               && &rj->wall(n).right() == rj) {
                        connect(i,j);
                    }
                }
            }
        }
    }

    m_atol.resize(neq());
    fill(m_atol.begin(), m_atol.end(), m_atols);
    m_integ->setTolerances(m_rtol, neq(), DATA_PTR(m_atol));
    m_integ->setSensitivityTolerances(m_rtolsens, m_atolsens);
    m_integ->setMaxStepSize(m_maxstep);
    m_integ->setMaxErrTestFails(m_maxErrTestFails);
    if (m_verbose) {
        sprintf(buf, "Number of equations: %s\n", int2str(neq()).c_str());
        writelog(buf);
        sprintf(buf, "Maximum time step:   %14.6g\n", m_maxstep);
        writelog(buf);
    }
    m_integ->initialize(m_time, *this);
    m_init = true;
}
Esempio n. 25
0
void ReactorNet::addReactor(Reactor& r)
{
    r.setNetwork(this);
    m_reactors.push_back(&r);
}
Esempio n. 26
0
int kinetics_example2(int job) {

    try {

        std::cout << "Ignition simulation using class GRI30." << std::endl;

        if (job >= 1) {
            std::cout <<
                "Constant-pressure ignition of a hydrogen/oxygen/nitrogen"
                " mixture \nbeginning at T = 1001 K and P = 1 atm." << std::endl;
        }
        if (job < 2) return 0;

        // create a GRI30 object
        GRI30 gas;
        gas.setState_TPX(1001.0, OneAtm, "H2:2.0, O2:1.0, N2:4.0");
        int kk = gas.nSpecies();

        // create a reactor
        Reactor r;

        // create a reservoir to represent the environment
        Reservoir env;

        // specify the thermodynamic property and kinetics managers
        r.setThermoMgr(gas);
        r.setKineticsMgr(gas);
        env.setThermoMgr(gas);

        // create a flexible, insulating wall between the reactor and the
        // environment
        Wall w;
        w.install(r,env);

        // set the "Vdot coefficient" to a large value, in order to
        // approach the constant-pressure limit; see the documentation 
        // for class Reactor
        w.setExpansionRateCoeff(1.e9);
        w.setArea(1.0);

        // create a container object to run the simulation
        // and add the reactor to it
        ReactorNet* sim_ptr = new ReactorNet();
        ReactorNet& sim = *sim_ptr;
        sim.addReactor(&r);

        double tm;
        double dt = 1.e-5;    // interval at which output is written
        int nsteps = 100;     // number of intervals

        // create a 2D array to hold the output variables,
        // and store the values for the initial state
        Array2D soln(kk+4, 1);
        saveSoln(0, 0.0, gas, soln);

        // main loop
        for (int i = 1; i <= nsteps; i++) {
            tm = i*dt;
            sim.advance(tm);
            saveSoln(tm, gas, soln);
        }

        // make a Tecplot data file and an Excel spreadsheet
        std::string plotTitle = "kinetics example 2: constant-pressure ignition";
        plotSoln("kin2.dat", "TEC", plotTitle, gas, soln);
        plotSoln("kin2.csv", "XL", plotTitle, gas, soln);


        // print final temperature
        std::cout << " Tfinal = " << r.temperature() << std::endl;
        std::cout << "Output files:" << std::endl
		  << "  kin2.csv    (Excel CSV file)" << std::endl
		  << "  kin2.dat    (Tecplot data file)" << std::endl;

        return 0;
    }

    // handle exceptions thrown by Cantera
    catch (CanteraError) {
        showErrors(std::cout);
        std::cout << " terminating... " << std::endl;
        appdelete();
        return -1;
    }
}
Esempio n. 27
0
int rxnpath_example1(int job)
{
    try {

        cout << "Reaction path diagram movies with file gri30.cti." << endl;
        if (job >= 1) {
            cout << "Generate reaction path diagrams following nitrogen\n"
                 << "as a function of time for constant-pressure ignition of a\n"
                 << "hydrogen/oxygen/nitrogen"
                 " mixture \nbeginning at T = 1001 K and P = 1 atm." << endl;
        }
        if (job < 2) {
            return 0;
        }

        // create an ideal gas mixture that corresponds to GRI-Mech
        // 3.0
        IdealGasMix gas("gri30.cti", "gri30");
        gas.setState_TPX(1001.0, OneAtm, "H2:2.0, O2:1.0, N2:4.0");

        // create a reactor
        Reactor r;

        // create a reservoir to represent the environment
        Reservoir env;

        // specify the thermodynamic property and kinetics managers
        r.setThermoMgr(gas);
        r.setKineticsMgr(gas);
        env.setThermoMgr(gas);

        // create a flexible, insulating wall between the reactor and the
        // environment
        Wall w;
        w.install(r,env);

        // set the "Vdot coefficient" to a large value, in order to
        // approach the constant-pressure limit; see the documentation
        // for class Reactor
        w.setExpansionRateCoeff(1.e9);
        w.setArea(1.0);

        double tm;
        double dt = 1.e-5;    // interval at which output is written
        int nsteps = 100;     // number of intervals

        // create a container object to run the simulation
        // and add the reactor to it
        ReactorNet& sim = *(new ReactorNet());
        sim.addReactor(&r);

        // create a reaction path diagram builder
        ReactionPathBuilder b;
        std::ofstream rplog("rp1.log");   // log file
        std::ofstream rplot("rp1.dot");   // output file
        b.init(rplog, gas);         // initialize

        // main loop
        for (int i = 1; i <= nsteps; i++) {
            tm = i*dt;
            sim.advance(tm);
            writeRxnPathDiagram(tm, b, gas, rplog, rplot);
        }

        // print final temperature
        cout << "Output files:" << endl
             << "  rp1.log    (log file)" << endl
             << "  rp1.dot    (input file for dot)" << endl;
        cout << "To generate the diagrams in Postscript, execute the command" << endl << endl
             << "dot -Tps rp1.dot > rp1.ps" << endl << endl
             << "Get dot for Windows here: http://blue.caltech.edu/dot.exe" << endl;
    } catch (CanteraError& err) {
        // handle exceptions thrown by Cantera
        std::cout << err.what() << std::endl;
        cout << " terminating... " << endl;
        appdelete();
        return -1;
    }
    return 0;
}
Esempio n. 28
0
  void ReactorNet::initialize(doublereal t0) {
    int n, nv;
    char buf[100];
    m_nv = 0;
    m_reactors.clear();
    m_nreactors = 0;
    if (m_verbose) {
      writelog("Initializing reactor network.\n");
    }
    if (m_nr == 0) 
      throw CanteraError("ReactorNet::initialize",
			 "no reactors in network!");
    for (n = 0; n < m_nr; n++) {
      if (m_r[n]->type() >= ReactorType) {
	m_r[n]->initialize(t0);
	Reactor* r = (Reactor*)m_r[n];
	m_reactors.push_back(r);
	nv = r->neq();
	m_size.push_back(nv);
	m_nparams.push_back(r->nSensParams());
	m_ntotpar += r->nSensParams();
	m_nv += nv;
	m_nreactors++;

	if (m_verbose) {
	  sprintf(buf,"Reactor %d: %d variables.\n",n,nv);
	  writelog(buf);
	  sprintf(buf,"            %d sensitivity params.\n",
		  r->nSensParams());
	  writelog(buf);
	}
	if (m_r[n]->type() == FlowReactorType && m_nr > 1) {
	  throw CanteraError("ReactorNet::initialize",
			     "FlowReactors must be used alone.");
	}
      }
    }

    m_connect.resize(m_nr*m_nr,0);
    m_ydot.resize(m_nv,0.0);
    int i, j, nin, nout, nw;
    ReactorBase *r, *rj;
    for (i = 0; i < m_nr; i++) {
      r = m_reactors[i];
      for (j = 0; j < m_nr; j++) {
	if (i == j) connect(i,j);
	else {
	  rj = m_reactors[j];
	  nin = rj->nInlets();
	  for (n = 0; n < nin; n++) {
	    if (&rj->inlet(n).out() == r) connect(i,j);
	  }
	  nout = rj->nOutlets();
	  for (n = 0; n < nout; n++) {
	    if (&rj->outlet(n).in() == r) connect(i,j);
	  }
	  nw = rj->nWalls();
	  for (n = 0; n < nw; n++) {
	    if (&rj->wall(n).left() == rj  
		&& &rj->wall(n).right() == r) connect(i,j);
	    else if (&rj->wall(n).left() == r  
		     && &rj->wall(n).right() == rj) connect(i,j);
	  }
	}
      }
    }

    m_atol.resize(neq());
    fill(m_atol.begin(), m_atol.end(), m_atols);
    m_integ->setTolerances(m_rtol, neq(), DATA_PTR(m_atol));
    m_integ->setSensitivityTolerances(m_rtolsens, m_atolsens);
    m_integ->setMaxStepSize(m_maxstep);
    if (m_verbose) {
      sprintf(buf, "Number of equations: %d\n", neq());
      writelog(buf);
      sprintf(buf, "Maximum time step:   %14.6g\n", m_maxstep);
      writelog(buf);
    }
    m_integ->initialize(t0, *this);
    m_init = true;
  }
Esempio n. 29
0
Acceptor::Acceptor(Reactor& reactor, int flag)
: sp_reactor_impl_(reactor.impl()),
  flag_(flag)
{
}
 ServerSocketHandler(unique_ptr<ServerSocket<T>> sock)
 {
     sock_fd = std::move(sock);
     Reactor *rec = Reactor::getInstance();
     rec->registerHandler(EV_IN, (sock_fd.get())->getSockfd(), this);    
 }