std::map<std::string, size_t> Server::conjecture ( const std::string & diverge_out, const std::string & equal_out, size_t max_count) { POMAGMA_ASSERT_LT(0, max_count); crop(); std::vector<float> probs; std::vector<std::string> routes; auto language = load_language(m_language_file); { Router router(m_structure.signature(), language); probs = router.measure_probs(); routes = router.find_routes(); } std::map<std::string, size_t> counts; counts["diverge"] = pomagma::conjecture_diverge( m_structure, probs, routes, diverge_out.c_str()); counts["equal"] = pomagma::conjecture_equal( m_structure, probs, routes, equal_out.c_str(), max_count); return counts; }
SUMOTime MSDevice_Routing::wrappedRerouteCommandExecute(SUMOTime currentTime) throw(ProcessError) { DijkstraRouterTT_ByProxi<MSEdge, SUMOVehicle, prohibited_withRestrictions<MSEdge, SUMOVehicle>, MSDevice_Routing> router(MSEdge::dictSize(), true, this, &MSDevice_Routing::getEffort); myHolder.reroute(currentTime, router); return myPeriod; }
int main() { Herbs::LogWriterDefault logwriter; SyZmO::LogfileOut logfile("syzmo_log_client_studio"); try { SyZmO::Client::Parameters params; params.port_in=49152; params.port_out=49153; if(SyZmO::ConfigFileIn::exists("syzmo_config_client.txt")) { SyZmO::ConfigFileIn config("syzmo_config_client.txt"); SyZmO::Buffer key(16); SyZmO::Buffer value(16); while(config.paramGet(key,value)) { if(strcmp(key.begin(),"port_in")==0) {params.port_in=atol(value.begin());} else if(strcmp(key.begin(),"port_out")==0) {params.port_out=atol(value.begin());} } } params.flags=SyZmO::Client::Parameters::SERVER_ANY; SyZmO::ClientStudio::MidiRouter router(logwriter); SyZmO::ClientStudio::EventHandler handler(router); int status; do { SyZmO::Client client(params,handler); router.pumpClientSet(client); router.pumpStart(); status=client.run(); router.pumpStop(); SyZmO::ConfigFileOut config("syzmo_config_client.txt"); char buff[16]; sprintf(buff,"%u",params.port_in); config.paramSet("port_in",buff); sprintf(buff,"%u",params.port_out); config.paramSet("port_out",buff); } while(status==SyZmO::Client::RUN_STATUS_CONTINUE); } catch(const SyZmO::ExceptionMissing& e) { e.print(logfile); } return 0; }
unique_ptr<routing::IRouter> CreateRouter(string const & name) { auto getter = [&](m2::PointD const & pt) { return m_cig->GetRegionCountryId(pt); }; unique_ptr<routing::IRoutingAlgorithm> algorithm(new Algorithm()); unique_ptr<routing::IRouter> router( new routing::RoadGraphRouter(name, m_index, getter, m_mode, CreateModelFactory(), move(algorithm), CreateDirectionsEngine())); return router; }
int main(int argc, char *argv[]) { char buf[80]; pthread_attr_t attr; char *in_dev, *out_dev; int status; if (argc != 3) { fprintf(stderr, "usage: vrouter <in_dev> <out_dev>\n"); return 1; } in_dev = argv[1]; out_dev = argv[2]; inet_aton(next_router_s, &next_router); debug_printf("NextRouter=%s\n", _inet_ntoa_r(&next_router, buf, sizeof(buf))); if (get_device_info(in_dev, device[0].hwaddr, &device[0].addr, &device[0].subnet, &device[0].netmask) == -1) { debug_printf("GetDeviceInfo:error:%s\n", in_dev); return -1; } if ((device[0].soc = init_raw_socket(in_dev, 1, 0)) == -1) { debug_printf("InitRawSocket:error:%s\n",in_dev); return -1; } if (get_device_info(out_dev, device[1].hwaddr, &device[1].addr, &device[1].subnet, &device[1].netmask) == -1) { debug_printf("GetDeviceInfo:error:%s\n", out_dev); return -1; } if ((device[1].soc = init_raw_socket(out_dev, 1, 0)) == -1) { debug_printf("InitRawSocket:error:%s\n",out_dev); return -1; } disable_ip_forward(); pthread_attr_init(&attr); if ((status = pthread_create(&buf_tid, &attr, buffer_thread, NULL)) != 0) { debug_printf("pthread_create:%s\n", strerror(status)); } signal(SIGPIPE, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGTTOU, SIG_IGN); IP2MAC *ip2mac = ip_2_mac(get_opposite_dev(0), next_router.s_addr, NULL); debug_printf("router start\n"); router(); debug_printf("router end\n"); close(device[0].soc); close(device[1].soc); return 0; }
void Router::run(void) { for (unsigned sz = 0; sz < max(size[2], 1); sz++) for (unsigned sy = 0; sy < max(size[1], 1); sy++) for (unsigned sx = 0; sx < max(size[0], 1); sx++) for (unsigned dz = 0; dz < max(size[2], 1); dz++) for (unsigned dy = 0; dy < max(size[1], 1); dy++) for (unsigned dx = 0; dx < max(size[0], 1); dx++) router(SCI(sx, sy, sz), SCI(dx, dy, dz)); }
/** GetObjectPropsSupported request handler. Obtains a list of all the data providers that support the request, then starts an active object to send it to them all. */ void CMTPGetObjectPropsSupported::ServiceL() { iObjectPropsSupported.Reset(); iTargetDps.Reset(); CMTPParserRouter& router(iSingletons.Router()); CMTPParserRouter::TRoutingParameters params(*iRequest, iConnection); router.ParseOperationRequestL(params); router.RouteOperationRequestL(params, iTargetDps); iCurrentTarget = 0; Schedule(KErrNone); }
size_t conjecture_diverge(Structure& structure, const char* language_file, const char* conjectures_file) { std::vector<float> probs; std::vector<std::string> routes; auto language = load_language(language_file); { Router router(structure.signature(), language); probs = router.measure_probs(); routes = router.find_routes(); } return conjecture_diverge(structure, probs, routes, conjectures_file); }
main() { int foo; oneHop testPath[NUMSEGMENTS]; int genPath[NUMSEGMENTS]; init_schedular(); testPath[0].thisNode.module = A; testPath[0].thisNode.sensorNum = 1; testPath[0].distance = 200; testPath[1].thisNode.module = C; testPath[1].thisNode.sensorNum = 13; testPath[1].distance = 400; testPath[2].thisNode.module = E; testPath[2].thisNode.sensorNum = 7; testPath[2].distance = NIL; init('a'); foo = router(genPath, 52, testPath); if (foo > 0) { foo = router(genPath, 55, testPath); foo = isWorking(testPath[0].thisNode); foo = isWorking(testPath[1].thisNode); foo = isWorking(testPath[2].thisNode); } }
void MSDevice_Routing::enterLaneAtEmit() { if (myLastPreEmitReroute == -1) { DijkstraRouterTT_ByProxi<MSEdge, SUMOVehicle, prohibited_withRestrictions<MSEdge, SUMOVehicle>, MSDevice_Routing> router(MSEdge::dictSize(), true, this, &MSDevice_Routing::getEffort); myHolder.reroute(MSNet::getInstance()->getCurrentTimeStep(), router); } // build repetition trigger if routing shall be done more often if (myPeriod>0&&myRerouteCommand==0) { myRerouteCommand = new WrappingCommand< MSDevice_Routing >(this, &MSDevice_Routing::wrappedRerouteCommandExecute); MSNet::getInstance()->getBeginOfTimestepEvents().addEvent( myRerouteCommand, myPeriod+MSNet::getInstance()->getCurrentTimeStep(), MSEventControl::ADAPT_AFTER_EXECUTION); } }
std::unordered_map<std::string, float> Server::fit_language( const Corpus::Histogram& histogram) { Router router(m_structure.signature(), m_language); router.fit_language(histogram.symbols, histogram.obs); m_language = router.get_language(); POMAGMA_DEBUG("Language:") std::map<std::string, float> language(m_language.begin(), m_language.end()); for (auto pair : language) { POMAGMA_DEBUG("\t" << pair.first << "\t" << pair.second); } m_probs = router.measure_probs(); m_routes = router.find_routes(); return m_language; }
int main(int argc, char* argv[]){ if(argc != 2){ std::cout << "Wrong argv; <Router ID>\n"; exit(1); } Router router((char)(*argv[1]), (char*)"sample_network.txt"); //router.wait_for_all_threads(); string input = ""; //cout << "Please enter a valid sentence (with spaces):\n>"; getline(cin, input); return 0; }
Server::Server ( const char * structure_file, const char * language_file) : m_structure(structure_file), m_approximator(m_structure), m_probs(), m_routes(), m_simplifier(m_structure.signature(), m_routes) { if (POMAGMA_DEBUG_LEVEL > 1) { m_structure.validate(); } auto language = load_language(language_file); Router router(m_structure.signature(), language); m_probs = router.measure_probs(); m_routes = router.find_routes(); }
int main(int argc, char** argv) { // Input validation if(argc < 4) { std::cerr << "Usage: " << argv[0] << " <routing_table> <ip_packets> <out_file>\n"; exit(2); } // Create instance of router class. IpRouter router(argv[1], argv[2], argv[3]); router.getPackets(); router.getResults(); router.writePackets(); return 0; }
int main(int argc, char *argv[]) { welcome(); if ( argc != 4 ) { fprintf(stderr, "!! arguments errors\n!! read README.txt for more information\n"); return -1; } char ip[17]; char login[50]; char name_file[50]; strcpy(ip, argv[1]); strcpy(login, argv[2]); strcpy(name_file, argv[3]); if ( router(ip, login, name_file) == -1 ) return -1; return 0; }
/** * Computes the routes saving them */ void computeRoutes(RONet &net, ROLoader &loader, OptionsCont &oc) { // initialise the loader loader.openRoutes(net); // prepare the output try { net.openOutput(oc.getString("output"), false); } catch (IOError &e) { throw e; } // build the router ROJTRRouter router(net, oc.getBool("continue-on-unbuild"), oc.getBool("accept-all-destinations")); // the routes are sorted - process stepwise if (!oc.getBool("unsorted")) { loader.processRoutesStepWise(string2time(oc.getString("begin")), string2time(oc.getString("end")), net, router); } // the routes are not sorted: load all and process else { loader.processAllRoutes(string2time(oc.getString("begin")), string2time(oc.getString("end")), net, router); } // end the processing net.closeOutput(); }
Server::Server(const char* structure_file, const char* language_file) : m_language(load_language(language_file)), m_structure(structure_file), m_return(m_structure.carrier()), m_nreturn(m_structure.carrier()), m_dense_set_store(m_structure.carrier().item_dim()), m_worker_pool(), m_intervals_approximator(m_structure, m_dense_set_store, m_worker_pool), m_approximator(m_structure), m_approximate_parser(m_approximator), m_probs(), m_routes(), m_simplifier(m_structure.signature(), m_routes, m_error_log), m_corpus(m_structure.signature()), m_validator(m_approximator), m_parser(), m_virtual_machine() { // parser and virtual_machine must be loaded after RETURN is delclared. Signature& signature = m_structure.signature(); POMAGMA_ASSERT(not signature.unary_relation("RETURN"), "reserved name RETURN is defined in loaded structure"); POMAGMA_ASSERT(not signature.unary_relation("NRETURN"), "reserved name NRETURN is defined in loaded structure"); signature.declare("RETURN", m_return); signature.declare("NRETURN", m_nreturn); m_parser.load(signature); m_virtual_machine.load(signature); if (POMAGMA_DEBUG_LEVEL > 1) { m_structure.validate(); } Router router(m_structure.signature(), m_language); m_probs = router.measure_probs(); m_routes = router.find_routes(); }
void MSDevice_Routing::onTryEmit() { if (myWithTaz) { const SUMOTime now = MSNet::getInstance()->getCurrentTimeStep(); if (myLastPreEmitReroute == -1 || (myPreEmitPeriod > 0 && myLastPreEmitReroute + myPreEmitPeriod <= now)) { const MSEdge* source = MSEdge::dictionary(myHolder.getParameter().fromTaz+"-source"); const MSEdge* dest = MSEdge::dictionary(myHolder.getParameter().toTaz+"-sink"); if (source && dest) { const std::pair<const MSEdge*, const MSEdge*> key = std::make_pair(source, dest); if (myCachedRoutes.find(key) == myCachedRoutes.end()) { DijkstraRouterTT_ByProxi<MSEdge, SUMOVehicle, prohibited_withRestrictions<MSEdge, SUMOVehicle>, MSDevice_Routing> router(MSEdge::dictSize(), true, this, &MSDevice_Routing::getEffort); myHolder.reroute(MSNet::getInstance()->getCurrentTimeStep(), router, true); myCachedRoutes[key] = &myHolder.getRoute(); myHolder.getRoute().addReference(); } else { myHolder.replaceRoute(myCachedRoutes[key], now, true); } myLastPreEmitReroute = now; } } } }
// received a character from UART void GSwifi::parseByte(uint8_t dat) { static uint8_t next_token; // split each byte into tokens (cid,ip,port,length,data) static bool escape = false; char temp[GS_MAX_PATH_LENGTH+1]; if (dat == ESCAPE) { // 0x1B : Escape GSLOG_PRINT("e< "); } else { // if (next_token != NEXT_TOKEN_DATA) { GSLOG_WRITE(dat); } if (gs_mode_ == GSMODE_COMMAND) { if (escape) { // esc switch (dat) { case 'O': case 'F': // ignore break; case 'Z': case 'H': gs_mode_ = GSMODE_DATA_RX_BULK; next_token = NEXT_TOKEN_CID; break; default: // GSLOG_PRINT("!E1 "); GSLOG_PRINTLN2(dat,HEX); break; } escape = false; } else { if (dat == ESCAPE) { escape = true; } else if (dat == '\n') { // end of line parseLine(); } else if (dat != '\r') { if ( ! ring_isfull(_buf_cmd) ) { ring_put(_buf_cmd, dat); } else { GSLOG_PRINTLN("!E2"); } } } return; } else if (gs_mode_ != GSMODE_DATA_RX_BULK) { return; } static uint16_t len; static char len_chars[5]; static int8_t current_cid; static GSREQUESTSTATE request_state; if (next_token == NEXT_TOKEN_CID) { // dat is cid current_cid = x2i(dat); ASSERT((0 <= current_cid) && (current_cid <= 16)); next_token = NEXT_TOKEN_LENGTH; len = 0; } else if (next_token == NEXT_TOKEN_LENGTH) { // Data Length is 4 ascii char represents decimal value i.e. 1400 byte (0x31 0x34 0x30 0x30) len_chars[ len ++ ] = dat; if (len >= 4) { len_chars[ len ] = 0; len = atoi(len_chars); // length of data next_token = NEXT_TOKEN_DATA; if (content_lengths_[ current_cid ] > 0) { // this is our 2nd bulk message from GS for this response // we already swallowed HTTP response headers, // following should be body request_state = GSREQUESTSTATE_BODY; } else { request_state = GSREQUESTSTATE_HEAD1; } ring_clear( _buf_cmd ); // reuse _buf_cmd to store HTTP request } } else if (next_token == NEXT_TOKEN_DATA) { len --; if (cidIsRequest(current_cid)) { // request against us static uint16_t error_code; static int8_t routeid; switch (request_state) { case GSREQUESTSTATE_HEAD1: if (dat != '\n') { if ( ! ring_isfull(_buf_cmd) ) { ring_put( _buf_cmd, dat ); } // ignore overflowed } else { // end of request line // reuse "temp" buffer to parse method and path int8_t result = parseRequestLine((char*)temp, 7); GSMETHOD method = GSMETHOD_UNKNOWN; if ( result == 0 ) { method = x2method(temp); result = parseRequestLine((char*)temp, GS_MAX_PATH_LENGTH); } if ( result != 0 ) { // couldn't detect method or path request_state = GSREQUESTSTATE_ERROR; error_code = 400; ring_clear(_buf_cmd); break; } routeid = router(method, temp); if ( routeid < 0 ) { request_state = GSREQUESTSTATE_ERROR; error_code = 404; ring_clear(_buf_cmd); break; } request_state = GSREQUESTSTATE_HEAD2; continuous_newlines_ = 0; content_lengths_[ current_cid ] = 0; has_requested_with_ = false; ring_clear(_buf_cmd); } break; case GSREQUESTSTATE_HEAD2: if(0 == parseHead2(dat, current_cid)) { request_state = GSREQUESTSTATE_BODY; // dispatched once, at start of body dispatchRequestHandler(current_cid, routeid, GSREQUESTSTATE_BODY_START); } break; case GSREQUESTSTATE_BODY: if (content_lengths_[ current_cid ] > 0) { content_lengths_[ current_cid ] --; } if (ring_isfull(_buf_cmd)) { dispatchRequestHandler(current_cid, routeid, request_state); // POST, user callback should write() } ring_put(_buf_cmd, dat); break; case GSREQUESTSTATE_ERROR: // skip until received whole request break; case GSREQUESTSTATE_RECEIVED: default: break; } // end of bulk transfered data if (len == 0) { gs_mode_ = GSMODE_COMMAND; if ( request_state == GSREQUESTSTATE_ERROR ) { writeHead( current_cid, error_code ); writeEnd(); ring_put( &commands, COMMAND_CLOSE ); ring_put( &commands, current_cid ); } else { if (content_lengths_[ current_cid ] == 0) { // if Content-Length header was longer than <ESC>Z length, // we wait til next bulk transfer request_state = GSREQUESTSTATE_RECEIVED; } // user callback should write(), writeEnd() and close() dispatchRequestHandler(current_cid, routeid, request_state); } ring_clear(_buf_cmd); } } else { // is request from us static uint16_t status_code; switch (request_state) { case GSREQUESTSTATE_HEAD1: if (dat != '\n') { if ( ! ring_isfull(_buf_cmd) ) { // ignore if overflowed ring_put( _buf_cmd, dat ); } } else { uint8_t i=0; // skip 9 characters "HTTP/1.1 " while (i++ < 9) { ring_get( _buf_cmd, &temp[0], 1 ); } // copy 3 numbers representing status code into temp buffer temp[ 3 ] = 0; int8_t count = ring_get( _buf_cmd, temp, 3 ); if (count != 3) { // protocol error // we should receive something like: "200 OK", "401 Unauthorized" status_code = 999; request_state = GSREQUESTSTATE_ERROR; break; } status_code = atoi(temp); request_state = GSREQUESTSTATE_HEAD2; continuous_newlines_ = 0; content_lengths_[ current_cid ] = 0; ring_clear(_buf_cmd); } break; case GSREQUESTSTATE_HEAD2: if(0 == parseHead2(dat, current_cid)) { request_state = GSREQUESTSTATE_BODY; // dispatched once, at start of body dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY_START); } break; case GSREQUESTSTATE_BODY: if (content_lengths_[ current_cid ] > 0) { content_lengths_[ current_cid ] --; } if (ring_isfull(_buf_cmd)) { dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY); } ring_put(_buf_cmd, dat); break; case GSREQUESTSTATE_ERROR: case GSREQUESTSTATE_RECEIVED: default: break; } if (len == 0) { gs_mode_ = GSMODE_COMMAND; if ( request_state == GSREQUESTSTATE_ERROR ) { dispatchResponseHandler(current_cid, status_code, request_state); } else { if (content_lengths_[ current_cid ] == 0) { // if Content-Length header was longer than <ESC>Z length, // we wait til all response body received. // we need to close our clientRequest before handling it. // GS often locks when closing 2 connections in a row // ex: POST /keys from iPhone (cid:1) -> POST /keys to server (cid:2) // response from server arrives -> close(1) -> close(2) -> lock!! // the other way around: close(2) -> close(1) doesn't lock :( request_state = GSREQUESTSTATE_RECEIVED; } dispatchResponseHandler(current_cid, status_code, request_state); } ring_clear( _buf_cmd ); } } // is response } // (next_token == NEXT_TOKEN_DATA) }
int main(int argc, char* argv[]) { osmscout::Vehicle vehicle=osmscout::vehicleCar; osmscout::FastestPathRoutingProfile routingProfile; std::string map; double startLat; double startLon; double targetLat; double targetLon; osmscout::ObjectFileRef startObject; size_t startNodeIndex; osmscout::ObjectFileRef targetObject; size_t targetNodeIndex; bool outputGPX = false; int currentArg=1; while (currentArg<argc) { if (strcmp(argv[currentArg],"--foot")==0) { vehicle=osmscout::vehicleFoot; currentArg++; } else if (strcmp(argv[currentArg],"--bicycle")==0) { vehicle=osmscout::vehicleBicycle; currentArg++; } else if (strcmp(argv[currentArg],"--car")==0) { vehicle=osmscout::vehicleCar; currentArg++; } else if (strcmp(argv[currentArg],"--gpx")==0) { outputGPX=true; currentArg++; } else { // No more "special" arguments break; } } if (argc-currentArg!=5) { std::cout << "Routing <map directory>" <<std::endl; std::cout << " <start lat> <start lon>" << std::endl; std::cout << " <target lat> <target lon>" << std::endl; return 1; } map=argv[currentArg]; currentArg++; if (sscanf(argv[currentArg],"%lf",&startLat)!=1) { std::cerr << "lat is not numeric!" << std::endl; return 1; } currentArg++; if (sscanf(argv[currentArg],"%lf",&startLon)!=1) { std::cerr << "lon is not numeric!" << std::endl; return 1; } currentArg++; if (sscanf(argv[currentArg],"%lf",&targetLat)!=1) { std::cerr << "lat is not numeric!" << std::endl; return 1; } currentArg++; if (sscanf(argv[currentArg],"%lf",&targetLon)!=1) { std::cerr << "lon is not numeric!" << std::endl; return 1; } currentArg++; double tlat; double tlon; osmscout::GetEllipsoidalDistance(startLat, startLon, 45, 1000, tlat, tlon); if (!outputGPX) { std::cout << "[" << startLat << "," << startLon << "] => [" << tlat << "," << tlon << "]" << std::endl; } osmscout::DatabaseParameter databaseParameter; osmscout::Database database(databaseParameter); if (!database.Open(map.c_str())) { std::cerr << "Cannot open database" << std::endl; return 1; } osmscout::RouterParameter routerParameter; if (!outputGPX) { routerParameter.SetDebugPerformance(true); } osmscout::Router router(routerParameter, vehicle); if (!router.Open(map.c_str())) { std::cerr << "Cannot open routing database" << std::endl; return 1; } osmscout::TypeConfig *typeConfig=router.GetTypeConfig(); //osmscout::ShortestPathRoutingProfile routingProfile; osmscout::RouteData data; osmscout::RouteDescription description; std::map<std::string,double> carSpeedTable; switch (vehicle) { case osmscout::vehicleFoot: routingProfile.ParametrizeForFoot(*typeConfig, 5.0); break; case osmscout::vehicleBicycle: routingProfile.ParametrizeForBicycle(*typeConfig, 20.0); break; case osmscout::vehicleCar: GetCarSpeedTable(carSpeedTable); routingProfile.ParametrizeForCar(*typeConfig, carSpeedTable, 160.0); break; } if (!outputGPX) { std::cout << "Searching for routing node for start location..." << std::endl; } if (!database.GetClosestRoutableNode(startLat, startLon, vehicle, 1000, startObject, startNodeIndex)) { std::cerr << "Error while searching for routing node near start location!" << std::endl; return 1; } if (startObject.Invalid() || startObject.GetType()==osmscout::refNode) { std::cerr << "Cannot find start node for start location!" << std::endl; } if (!outputGPX) { std::cout << "Searching for routing node for target location..." << std::endl; } if (!database.GetClosestRoutableNode(targetLat, targetLon, vehicle, 1000, targetObject, targetNodeIndex)) { std::cerr << "Error while searching for routing node near target location!" << std::endl; return 1; } if (targetObject.Invalid() || targetObject.GetType()==osmscout::refNode) { std::cerr << "Cannot find start node for target location!" << std::endl; } if (!router.CalculateRoute(routingProfile, startObject, startNodeIndex, targetObject, targetNodeIndex, data)) { std::cerr << "There was an error while calculating the route!" << std::endl; router.Close(); return 1; } if (data.IsEmpty()) { std::cout << "No Route found!" << std::endl; router.Close(); return 0; } router.TransformRouteDataToRouteDescription(data,description); std::list<osmscout::RoutePostprocessor::PostprocessorRef> postprocessors; postprocessors.push_back(new osmscout::RoutePostprocessor::DistanceAndTimePostprocessor()); postprocessors.push_back(new osmscout::RoutePostprocessor::StartPostprocessor("Start")); postprocessors.push_back(new osmscout::RoutePostprocessor::TargetPostprocessor("Target")); postprocessors.push_back(new osmscout::RoutePostprocessor::WayNamePostprocessor()); postprocessors.push_back(new osmscout::RoutePostprocessor::CrossingWaysPostprocessor()); postprocessors.push_back(new osmscout::RoutePostprocessor::DirectionPostprocessor()); osmscout::RoutePostprocessor::InstructionPostprocessor *instructionProcessor=new osmscout::RoutePostprocessor::InstructionPostprocessor(); instructionProcessor->AddMotorwayType(typeConfig->GetWayTypeId("highway_motorway")); instructionProcessor->AddMotorwayLinkType(typeConfig->GetWayTypeId("highway_motorway_link")); instructionProcessor->AddMotorwayType(typeConfig->GetWayTypeId("highway_motorway_trunk")); instructionProcessor->AddMotorwayType(typeConfig->GetWayTypeId("highway_motorway_primary")); instructionProcessor->AddMotorwayType(typeConfig->GetWayTypeId("highway_trunk")); instructionProcessor->AddMotorwayLinkType(typeConfig->GetWayTypeId("highway_trunk_link")); postprocessors.push_back(instructionProcessor); osmscout::RoutePostprocessor postprocessor; size_t roundaboutCrossingCounter=0; #if defined(POINTS_DEBUG) std::list<osmscout::Point> points; if (!router.TransformRouteDataToPoints(data,points)) { std::cerr << "Error during route conversion" << std::endl; } std::cout << points.size() << " point(s)" << std::endl; for (std::list<osmscout::Point>::const_iterator point=points.begin(); point!=points.end(); ++point) { std::cout << "Point " << point->GetId() << " " << point->GetLat() << "," << point->GetLon() << std::endl; } #endif std::list<osmscout::Point> points; if(outputGPX) { if (!router.TransformRouteDataToPoints(data,points)) { std::cerr << "Error during route conversion" << std::endl; } std::cout.precision(8); std::cout << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n<gpx xmlns=\"http://www.topografix.com/GPX/1/1\" creator=\"bin2gpx\" version=\"1.1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n\t<trk>" << std::endl; std::cout << "\t\t<trkseg>" << std::endl; for (std::list<osmscout::Point>::const_iterator point=points.begin(); point!=points.end(); ++point) { std::cout << "\t\t\t<trkpt lat=\""<< point->GetLat() << "\" lon=\""<< point->GetLon() <<"\">\n\t\t\t\t</trkpt><fix>2d</fix>" << std::endl; } std::cout << "\t\t</trkseg>" << std::endl; std::cout << "\t</trk>" << std::endl; std::cout << "</gpx>" << std::endl; return 0; } if (!postprocessor.PostprocessRouteDescription(description, routingProfile, database, postprocessors)) { std::cerr << "Error during route postprocessing" << std::endl; } std::cout << "----------------------------------------------------" << std::endl; std::cout << " At| After| Time| After|" << std::endl; std::cout << "----------------------------------------------------" << std::endl; std::list<osmscout::RouteDescription::Node>::const_iterator prevNode=description.Nodes().end(); for (std::list<osmscout::RouteDescription::Node>::const_iterator node=description.Nodes().begin(); node!=description.Nodes().end(); ++node) { osmscout::RouteDescription::DescriptionRef desc; osmscout::RouteDescription::NameDescriptionRef nameDescription; osmscout::RouteDescription::DirectionDescriptionRef directionDescription; osmscout::RouteDescription::NameChangedDescriptionRef nameChangedDescription; osmscout::RouteDescription::CrossingWaysDescriptionRef crossingWaysDescription; osmscout::RouteDescription::StartDescriptionRef startDescription; osmscout::RouteDescription::TargetDescriptionRef targetDescription; osmscout::RouteDescription::TurnDescriptionRef turnDescription; osmscout::RouteDescription::RoundaboutEnterDescriptionRef roundaboutEnterDescription; osmscout::RouteDescription::RoundaboutLeaveDescriptionRef roundaboutLeaveDescription; osmscout::RouteDescription::MotorwayEnterDescriptionRef motorwayEnterDescription; osmscout::RouteDescription::MotorwayChangeDescriptionRef motorwayChangeDescription; osmscout::RouteDescription::MotorwayLeaveDescriptionRef motorwayLeaveDescription; desc=node->GetDescription(osmscout::RouteDescription::WAY_NAME_DESC); if (desc.Valid()) { nameDescription=dynamic_cast<osmscout::RouteDescription::NameDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::DIRECTION_DESC); if (desc.Valid()) { directionDescription=dynamic_cast<osmscout::RouteDescription::DirectionDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::WAY_NAME_CHANGED_DESC); if (desc.Valid()) { nameChangedDescription=dynamic_cast<osmscout::RouteDescription::NameChangedDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::CROSSING_WAYS_DESC); if (desc.Valid()) { crossingWaysDescription=dynamic_cast<osmscout::RouteDescription::CrossingWaysDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::NODE_START_DESC); if (desc.Valid()) { startDescription=dynamic_cast<osmscout::RouteDescription::StartDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::NODE_TARGET_DESC); if (desc.Valid()) { targetDescription=dynamic_cast<osmscout::RouteDescription::TargetDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::TURN_DESC); if (desc.Valid()) { turnDescription=dynamic_cast<osmscout::RouteDescription::TurnDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::ROUNDABOUT_ENTER_DESC); if (desc.Valid()) { roundaboutEnterDescription=dynamic_cast<osmscout::RouteDescription::RoundaboutEnterDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::ROUNDABOUT_LEAVE_DESC); if (desc.Valid()) { roundaboutLeaveDescription=dynamic_cast<osmscout::RouteDescription::RoundaboutLeaveDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::MOTORWAY_ENTER_DESC); if (desc.Valid()) { motorwayEnterDescription=dynamic_cast<osmscout::RouteDescription::MotorwayEnterDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::MOTORWAY_CHANGE_DESC); if (desc.Valid()) { motorwayChangeDescription=dynamic_cast<osmscout::RouteDescription::MotorwayChangeDescription*>(desc.Get()); } desc=node->GetDescription(osmscout::RouteDescription::MOTORWAY_LEAVE_DESC); if (desc.Valid()) { motorwayLeaveDescription=dynamic_cast<osmscout::RouteDescription::MotorwayLeaveDescription*>(desc.Get()); } if (crossingWaysDescription.Valid() && roundaboutCrossingCounter>0 && crossingWaysDescription->GetExitCount()>1) { roundaboutCrossingCounter+=crossingWaysDescription->GetExitCount()-1; } if (!HasRelevantDescriptions(*node)) { continue; } #if defined(HTML) std::cout << "<tr><td>"; #endif std::cout << std::setfill(' ') << std::setw(5) << std::fixed << std::setprecision(1); std::cout << node->GetDistance() << "km "; #if defined(HTML) std::cout <<"</td><td>"; #endif if (prevNode!=description.Nodes().end() && node->GetDistance()-prevNode->GetDistance()!=0.0) { std::cout << std::setfill(' ') << std::setw(4) << std::fixed << std::setprecision(1); std::cout << node->GetDistance()-prevNode->GetDistance() << "km "; } else { std::cout << " "; } #if defined(HTML) std::cout << "<tr><td>"; #endif std::cout << TimeToString(node->GetTime()) << "h "; #if defined(HTML) std::cout <<"</td><td>"; #endif if (prevNode!=description.Nodes().end() && node->GetTime()-prevNode->GetTime()!=0.0) { std::cout << TimeToString(node->GetTime()-prevNode->GetTime()) << "h "; } else { std::cout << " "; } #if defined(HTML) std::cout <<"</td><td>"; #endif size_t lineCount=0; #if defined(ROUTE_DEBUG) || defined(NODE_DEBUG) NextLine(lineCount); std::cout << "// " << node->GetTime() << "h " << std::setw(0) << std::setprecision(3) << node->GetDistance() << "km "; if (node->GetPathObject().Valid()) { std::cout << node->GetPathObject().GetTypeName() << " " << node->GetPathObject().GetFileOffset() << "[" << node->GetCurrentNodeIndex() << "] => " << node->GetPathObject().GetTypeName() << " " << node->GetPathObject().GetFileOffset() << "[" << node->GetTargetNodeIndex() << "]"; } std::cout << std::endl; for (std::list<osmscout::RouteDescription::DescriptionRef>::const_iterator d=node->GetDescriptions().begin(); d!=node->GetDescriptions().end(); ++d) { osmscout::RouteDescription::DescriptionRef desc=*d; NextLine(lineCount); std::cout << "// " << desc->GetDebugString() << std::endl; } #endif if (startDescription.Valid()) { DumpStartDescription(lineCount, startDescription, nameDescription); } else if (targetDescription.Valid()) { DumpTargetDescription(lineCount,targetDescription); } else if (turnDescription.Valid()) { DumpTurnDescription(lineCount, turnDescription, crossingWaysDescription, directionDescription, nameDescription); } else if (roundaboutEnterDescription.Valid()) { DumpRoundaboutEnterDescription(lineCount, roundaboutEnterDescription, crossingWaysDescription); roundaboutCrossingCounter=1; } else if (roundaboutLeaveDescription.Valid()) { DumpRoundaboutLeaveDescription(lineCount, roundaboutLeaveDescription, nameDescription); roundaboutCrossingCounter=0; } else if (motorwayEnterDescription.Valid()) { DumpMotorwayEnterDescription(lineCount, motorwayEnterDescription, crossingWaysDescription); } else if (motorwayChangeDescription.Valid()) { DumpMotorwayChangeDescription(lineCount, motorwayChangeDescription); } else if (motorwayLeaveDescription.Valid()) { DumpMotorwayLeaveDescription(lineCount, motorwayLeaveDescription, directionDescription, nameDescription); } else if (nameChangedDescription.Valid()) { DumpNameChangedDescription(lineCount, nameChangedDescription); } if (lineCount==0) { std::cout << std::endl; } #if defined(HTML) std::cout << "</td></tr>"; #endif prevNode=node; } router.Close(); return 0; }
int main (int argc, char * const argv[]) { char* config_file = NULL; // bool debug_mode = false; // bool daemon_mode = false; // bool check_mode = false; Config conf_params; Router router(&conf_params); /* * Initialisation * * Read the config file (-f option): * - bind_address * - bind_port (default: 555) * - data_path (default: /var/lib/ows) * - etc_path (default: /etc/ows) */ if ( argc < 3 ) { usage(); return EXIT_FAILURE; } for ( int i = 1 ; i < argc ; i++ ) { if ( strcmp(argv[i], "-f" ) == 0 && i < argc ) { config_file = argv[i+1]; continue; } /* if ( strcmp(argv[i], "-v" ) == 0 ) { debug_mode = true; continue; } if ( strcmp(argv[i], "-d" ) == 0 ) { daemon_mode = true; continue; } */ } if ( config_file == NULL ) { std::cerr << "No config file given" << std::endl; usage(); return EXIT_FAILURE; } if ( conf_params.parse_file(config_file) == false ) { std::cout << "Cannot parse " << config_file << std::endl; return EXIT_FAILURE; } // if (daemon_mode == true) // daemonize(); /* * Peers Discovery * * - Get the (host, public key) list * - Call Router.reach_master() : if true -> continue, else waiting loop (30 seconds and retry) * */ router.update_peers_list(); while ( router.get_reachable_peers_number() < 1 ) { std::cout << "Cannot reach any peer" << std::endl; router.update_peers_list(); sleep(30); } while ( router.reach_master() == false ) { std::cout << "Cannot reach the master" << std::endl; sleep(30); } /* * Planning loading * * - Call Rpc_Client.get_planning() until it succeeds * - Create the domain * - Call Domain.load_planning(); */ rpc::t_node node; Domain domain(&conf_params); switch (conf_params.get_running_mode()) { case P2P: { /* * Check if the domain contains data * Or ask the direct peers for data */ if ( domain.contains_data(conf_params.get_param("node_name")->c_str()) == false ) { p_m_host_keys_iter iters = router.get_direct_peers(); rpc::t_node node; node.name = conf_params.get_param("node_name")->c_str(); for ( auto iter = iters.first ; iter != iters.second ; iter++ ) { if ( router.get_node(*conf_params.get_param("domain_name"), node, iter->second.c_str()) == true ) break; } if ( domain.add_node(conf_params.get_param("domain_name")->c_str(), node) == false ) { std::cerr << "Cannot load the planning" << std::endl; return EXIT_FAILURE; } } break; } case ACTIVE: { while ( router.get_node(conf_params.get_param("domain_name")->c_str(), node, router.get_master_node()->c_str()) == false ) { std::cout << "Cannot get the planning" << std::endl; sleep(30); } if ( domain.add_node(conf_params.get_param("domain_name")->c_str(), node) == false ) { std::cerr << "Cannot load the planning" << std::endl; return EXIT_FAILURE; } break; } case PASSIVE: { /* * Nothing is done. The master gives orders */ break; } } /* * Ports listening * * - create a Rpc_Server object * - create a dedicated thread */ Rpc_Server server(&domain, &conf_params, &router); boost::thread server_thread(boost::bind(&Rpc_Server::run, &server)); /* * Domain preparation * * - Try to reach the node needed by the planning : build the routing table */ /* * Domain routine * * - Check for ready jobs every minute * - Or wait master's orders */ v_jobs jobs; boost::thread_group running_jobs; switch (conf_params.get_running_mode()) { case (P2P): {break;}; case (ACTIVE): { while (1) { domain.get_ready_jobs(jobs, conf_params.get_param("node_name")->c_str()); std::cout << "jobs size: " << jobs.size() << std::endl; // TODO: remove it BOOST_FOREACH(Job j, jobs) { running_jobs.create_thread(boost::bind(&Job::run, &j)); } sleep(60); } break; } case (PASSIVE): { break; } }
static void *doit(int id, Config &conf) { FCGX_Request request; if(FCGX_InitRequest(&request, socketId.load(), 0) != 0) { //ошибка при инициализации структуры запроса printf("Can not init request\n"); return NULL; } Router router(&request, &conf); router.addHandler("OPTIONS", "/users/login", &OptUsersLogin); router.addHandler("GET", "/users/login", &UsersInfo); router.addHandler("POST", "/users/login", &PostUsersLogin); router.addHandler("OPTIONS", "/users/add", &OptUsersAdd); router.addHandler("POST", "/users/add", &PostUsersAdd); router.addHandler("OPTIONS", ".*", &OptDirs); router.addHandler("OPTIONS", "/dirs/(?<id>\\d+)", &OptDirs); router.addHandler("POST", "/dirs", &PostCreateDir); router.addHandler("GET", "/dirs/(\\d+)", &GetDir); router.addHandler("DELETE", "/dirs/(\\d+)", &DelDir); router.addHandler("POST", "/files/(\\d+)/(.+)", &PutFile); router.addHandler("GET", "/files/(\\d+)", &GetFile); router.addHandler("DELETE", "/files/(\\d+)", &DelFile); for(;;) { static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&accept_mutex); int rc = FCGX_Accept_r(&request); pthread_mutex_unlock(&accept_mutex); if(rc < 0) { //ошибка при получении запроса printf("Can not accept new request\n"); break; } std::streambuf * cin_streambuf = std::cin.rdbuf(); std::streambuf * cout_streambuf = std::cout.rdbuf(); std::streambuf * cerr_streambuf = std::cerr.rdbuf(); fcgi_streambuf cin_fcgi_streambuf(request.in); fcgi_streambuf cout_fcgi_streambuf(request.out); fcgi_streambuf cerr_fcgi_streambuf(request.err); std::cin.rdbuf(&cin_fcgi_streambuf); std::cout.rdbuf(&cout_fcgi_streambuf); std::cerr.rdbuf(&cerr_fcgi_streambuf); try { router.Run(); } catch (Error &e) { router.SetStatus(e.http_code()); router.AddHeader("Content-Type", "application/json; charset=utf-8"); router.AddContent(e.what()); router.AcceptContent(); } catch (std::exception &e) { std::cerr << e.what(); router.SetStatus(Httpstatus::InternalServerError); router.AddHeader("Content-Type", "text/plain; charset=utf-8"); router.AddContent(e.what()); router.AcceptContent(); } FCGX_Finish_r(&request); //завершающие действия - запись статистики, логгирование ошибок и т.п. router.Cleanup(); std::cin.rdbuf(cin_streambuf); std::cout.rdbuf(cout_streambuf); std::cerr.rdbuf(cerr_streambuf); } return NULL; }
void DeviceMonitor::processReceivedAnnouncement(std::string receivingInterfaceName, const std::string &message) { Json::Value announcement; try { if ( ! Json::Reader().parse(message, announcement)) { callErrorCb(cb_t::DATA_DROPPED | cb_t::ERROR_PARSE, "JSON parser failed", message); return; } if ( ! (announcement[hbm::jsonrpc::METHOD].asString()==TAG_Announce) ) { callErrorCb(cb_t::DATA_DROPPED | cb_t::ERROR_METHOD, "Missing \"announcement\" in JSON-document", message); return; } const Json::Value& params = announcement[hbm::jsonrpc::PARAMS]; // this is an announcement! std::string sendingInterfaceName = params[TAG_NetSettings][TAG_Interface][TAG_Name].asString(); if (sendingInterfaceName.empty()) { callErrorCb(cb_t::DATA_DROPPED | cb_t::ERROR_IPADDR, "Missing interface name in JSON-document", message); return; } std::string sendingUuid(params[TAG_Device][TAG_Uuid].asString()); if (sendingUuid.empty()) { callErrorCb(cb_t::DATA_DROPPED | cb_t::ERROR_UUID, "Missing uuid in JSON-document", message); return; } std::string router(params[TAG_Router][TAG_Uuid].asString()); std::string key(receivingInterfaceName+":"+sendingInterfaceName+":"+sendingUuid+":"+router); std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); std::chrono::seconds expire(params[TAG_Expiration].asUInt()); if (expire.count() == 0 ) { callErrorCb(cb_t::DATA_DROPPED | cb_t::ERROR_EXPIRE, "Missing expiration in JSON-document", message); return; } // callErrorCb(0, "received", message); announcements_t::iterator iter = m_announcements.find(key); if (iter!=m_announcements.end()) { // update existing entry expiringEntry& currentEntry = iter->second; currentEntry.timeOfExpiry = now + expire; if (message!=currentEntry.announcement) { // something has changed currentEntry.announcement = message; if (m_announceCb) { m_announceCb(sendingUuid, receivingInterfaceName, sendingInterfaceName, router, message); } } } else { // new entry expiringEntry entry; entry.announcement = message; entry.timeOfExpiry = now + expire; m_announcements[key] = entry; if (m_announceCb) { m_announceCb(sendingUuid, receivingInterfaceName, sendingInterfaceName, router, message); } } } catch(std::exception &) { callErrorCb(cb_t::DATA_DROPPED | cb_t::E_EXCEPTION1, "Receiving error 1", message); } catch(...) { callErrorCb(cb_t::DATA_DROPPED | cb_t::E_EXCEPTION2, "Receiving error 2", message); } }
/** does the actual write */ template<class msg_type> void operator()(msg_type & msg) const { router().template write<apply_format_and_write_type>(msg); }
void MSTriggeredRerouter::reroute(SUMOVehicle &veh, const MSEdge &src) { // check whether the vehicle shall be rerouted SUMOTime time = MSNet::getInstance()->getCurrentTimeStep(); if (!hasCurrentReroute(time, veh)) { return; } SUMOReal prob = myAmInUserMode ? myUserProbability : myProbability; if (RandHelper::rand() > prob) { return; } // get vehicle params const MSRoute &route = veh.getRoute(); const MSEdge *lastEdge = route.getLastEdge(); // get rerouting params const MSTriggeredRerouter::RerouteInterval &rerouteDef = getCurrentReroute(time, veh); const MSRoute *newRoute = rerouteDef.routeProbs.getOverallProb()>0 ? rerouteDef.routeProbs.get() : 0; // we will use the route if given rather than calling our own dijsktra... if (newRoute!=0) { veh.replaceRoute(newRoute->getEdges(), time); return; } // ok, try using a new destination const MSEdge *newEdge = rerouteDef.edgeProbs.getOverallProb()>0 ? rerouteDef.edgeProbs.get() : route.getLastEdge(); if (newEdge==0) { newEdge = lastEdge; } // we have a new destination, let's replace the vehicle route MSEdgeWeightsStorage empty; MSNet::EdgeWeightsProxi proxi(empty, MSNet::getInstance()->getWeightsStorage()); DijkstraRouterTT_ByProxi<MSEdge, SUMOVehicle, prohibited_withRestrictions<MSEdge, SUMOVehicle>, MSNet::EdgeWeightsProxi> router(MSEdge::dictSize(), true, &proxi, &MSNet::EdgeWeightsProxi::getTravelTime); router.prohibit(rerouteDef.closed); std::vector<const MSEdge*> edges; router.compute(&src, newEdge, &veh, MSNet::getInstance()->getCurrentTimeStep(), edges); veh.replaceRoute(edges, MSNet::getInstance()->getCurrentTimeStep()); }