static bool send(LocalFrame* frame, int allowance, const KURL& beaconURL, const Beacon& beacon, int& payloadLength) { if (!frame->document()) return false; unsigned long long entitySize = beacon.size(); if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize) return false; ResourceRequest request(beaconURL); request.setRequestContext(WebURLRequest::RequestContextBeacon); request.setHTTPMethod("POST"); request.setHTTPHeaderField("Cache-Control", "max-age=0"); request.setAllowStoredCredentials(true); frame->document()->fetcher()->context().addAdditionalRequestHeaders(request, FetchSubresource); frame->document()->fetcher()->context().setFirstPartyForCookies(request); if (MixedContentChecker::shouldBlockFetch(frame, request, request.url())) return false; payloadLength = entitySize; if (!beacon.serialize(request, allowance, payloadLength)) return false; FetchInitiatorInfo initiatorInfo; initiatorInfo.name = FetchInitiatorTypeNames::beacon; // Leak the loader, since it will kill itself as soon as it receives a response. RefPtrWillBeRawPtr<BeaconLoader> loader = adoptRefWillBeNoop(new BeaconLoader(frame, request, initiatorInfo, AllowStoredCredentials)); loader->ref(); return true; }
void Database::findNearest() { // Optimize - if the tunedBc beacon is already found and preselected keep it, // don't alloc any iterators and only check for distance. If it's out of range it's // time to search again if (tunedBeaconWithinRange()) return; vector<Beacon> shortList; vector<Beacon>::iterator it = begin(); while( it != end() ) { Beacon bc = *it; if( bc.hasCode(selStrobe, selNul) && bc.isInRangeOf(curLat, curLon, curElev)) { shortList.push_back(bc); } it++; } // Bail out if none are found if( 0 == shortList.size()) { isTuned = false; return; } // I know this is a bubble sort but with 3-4 choices and the optimization above this is tolerable. // Finds the beacon with the shortest distance to the aircraft tunedBc = shortList.front(); for (vector<Beacon>::iterator curItem = shortList.begin(); curItem != shortList.end(); ++curItem) { if(tunedBc.distanceFrom(curLat, curLon, curElev) > (*curItem).distanceFrom(curLat, curLon, curElev)) { tunedBc = (*curItem); } } isTuned = true; }
//------------------------------------------------------------------------------ void BeaconVisual::onBeaconStateChanged() { Beacon * beacon = (Beacon*)object_; bool deployed_group = false; bool hover_group = false; bool undeployed_group = false; if (beacon->isDeployed()) { deployed_group = true; } else { if (beacon->isInsideRadius() && beacon->getState() != BS_DISPENSED) { hover_group = true; } else { undeployed_group = true; } } assert(!(deployed_group && hover_group)); assert(!(deployed_group && undeployed_group)); assert(!(hover_group && undeployed_group)); EnableGroupVisitor v1(HOVERING_GROUP_NAME, hover_group); EnableGroupVisitor v2(DEPLOYED_GROUP_NAME, deployed_group); EnableGroupVisitor v3(NOT_DEPLOYED_GROUP_NAME, undeployed_group); osg_wrapper_->getOsgNode()->accept(v1); osg_wrapper_->getOsgNode()->accept(v2); osg_wrapper_->getOsgNode()->accept(v3); }
void BeaconIterator::makeIndex(Beacon *beacon, bool isDFS, bool isFirst) { if (isFirst) { beaconIndex.clear(); curIdx = -1; } beaconIndex.push_back(beacon); if (isDFS) { // DFS. recursive for (size_t i = 0; i < beacon->childrenSize(); i++) { makeIndex(beacon->childAt(i), isDFS, false/*isFirst*/); } } else { // BFS int cur = 0; Beacon *curBeacon; while(cur < (int)beaconIndex.size()) { curBeacon = beaconIndex[cur]; for (size_t i = 0; i < curBeacon->childrenSize(); i++) { beaconIndex.push_back(curBeacon->childAt(i)); } cur++; } } }
int main(int argc, char *argv[]) { QApplication a(argc, argv); Beacon w; w.show(); return a.exec(); }
void NeighbourDiscovery::sendBeacons() { Logger::getInstance()->setThreadName(std::this_thread::get_id(), "Beacon Sender"); LOG(14) << "Creating send beacons thread"; // Get node configuration std::string nodeId = m_config.getNodeId(); std::string nodeAddress = m_config.getNodeAddress(); uint16_t nodePort = m_config.getNodePort(); #ifndef LEPTON // Generate this node address information. LOG(64) << "Starting socket into " << nodeAddress << ":0"; // Create the socket. Socket s = Socket(false); if (!s) { // Stop the application LOG(1) << "Cannot create socket into sendBeacons thread, reason: " << s.getLastError(); g_stop = true; } else { // Bind the socket. if (!s.bind(nodeAddress, 0)) { // Stop the application LOG(1) << "Cannot bind socket to " << nodeAddress << ", reason: " << s.getLastError(); g_stop = true; } else { // Generate the destination address. s.setDestination(m_config.getDiscoveryAddress(), m_config.getDiscoveryPort()); #endif // Create the beacon with our information. LOG(64) << "Sending beacons to " << m_config.getDiscoveryAddress() << ":" << m_config.getDiscoveryPort(); int sleepTime = m_config.getDiscoveryPeriod(); g_startedThread++; while (!g_stop.load()) { std::this_thread::sleep_for(std::chrono::seconds(sleepTime)); Beacon b = Beacon(nodeId, nodeAddress, nodePort, m_listeningEndpointsTable->getValues()); LOG(21) << "Sending beacon from " << nodeId << " " << nodeAddress << ":" << nodePort; std::string rawBeacon = b.getRaw(); if (s.canSend(m_config.getSocketTimeout())) { if (!(s << rawBeacon)) { LOG(4) << "Error sending beacon " << s.getLastError(); } } } s.close(); #ifndef LEPTON } #endif LOG(14) << "Exit Beacon sender thread."; g_stopped++; #ifndef LEPTON } #endif }
int main(int argc, char*argv[]) { MsgPublisherType type = MsgPublisherType::AMQP_QPID; string brokerUrl("192.168.1.107:5672"); string clientID("testQpidFactory"); string userName; string password; if (argc > 1) brokerUrl = argv[1]; printf("Creating QPID MsgPublisher, brokerUrl=%s\n", brokerUrl.c_str()); fflush(stdout); std::unique_ptr<MsgPublisher> qpid(MsgPublisher::create(type, brokerUrl, clientID, userName, password)); printf("Created QPID MsgPublisher, %s\n", qpid->toString()); qpid->setUseTopics(false); qpid->start(false); printf("Started QPID MsgPublisher\n"); // Create a messages Beacon beacon = testBeacon(); vector<Beacon> events; int N = 5; struct timeval start; gettimeofday(&start, nullptr); for (int ix = 0; ix < N; ++ix) { int64_t now = System::currentTimeMillis(); beacon.setTime(now); #ifdef MSG_PROPERTIES qpid->publish("", beacon); printf("Sent properties message #%d\n", ix + 1); #endif #ifdef MSG_PROPERTIES_BATCH events.push_back(beacon); #else vector<byte> data = beacon.toByteMsg(); qpid->publish("", MqttQOS::AT_MOST_ONCE , data.data(), data.size()); //printf("Sent byte message #%d\n", ix + 1); #endif } #ifdef MSG_PROPERTIES_BATCH qpid->publish(events); printf("Sent %d messages in batch\n", N); #endif struct timeval end; gettimeofday(&end, nullptr); printf("Elapsed, %d\n", end.tv_sec - start.tv_sec); qpid->stop(); printf("Stopped QPID MsgPublisher\n"); // Test what happens if stop is called multiple times qpid->stop(); printf("Stop#2 QPID MsgPublisher\n"); qpid->stop(); printf("Stop#3 QPID MsgPublisher\n"); printf("MsgPublisher will be deleted by ~unique_ptr\n"); }
ATCInput::ATCInput (Traffic *Traff_i, Landmarks *Lmarks_i) : //Screen initialisations ATCScreen ( 1, 46, 60, 50, ATC_TEXT_MODE, BLACK, WHITE ), CrntColumn_c (1), Traff_c (Traff_i), Gates_c (True), Airports_c (True), Beacons_c (True), NextProcess_c (&GetPlane), IsCmndToCollect_c (False), LastCmnd_c (NULL) { int GateIx, AirportIx, BeaconIx; Gate *CrntGate; Airport *CrntAirport; Beacon *CrntBeacon; for (GateIx = 0; GateIx < Lmarks_i->NoOfGates(); GateIx++) { CrntGate = Lmarks_i->AllGates() [GateIx]; Gates_c.Add (CrntGate, CrntGate->ID()); } for (AirportIx = 0; AirportIx < Lmarks_i->NoOfAirports(); AirportIx++) { CrntAirport = Lmarks_i->AllAirports() [AirportIx]; Airports_c.Add (CrntAirport, CrntAirport->ID()); } for (BeaconIx = 0; BeaconIx < Lmarks_i->NoOfBeacons(); BeaconIx++) { CrntBeacon = Lmarks_i->AllBeacons() [BeaconIx]; Beacons_c.Add (CrntBeacon, CrntBeacon->ID()); } }
CmndInput::CmndInput ( Landmarks *Lmarks_i, Traffic *Traff_i ) : Traff_c (Traff_i), IsCmndToCollect_c (False), LastCmnd_c (NULL) { int GateIx, AirportIx, BeaconIx; Gate *CrntGate; Airport *CrntAirport; Beacon *CrntBeacon; Out_c.Refresh(); for (GateIx = 0; GateIx < Lmarks_i->NoOfGates(); GateIx++) { CrntGate = Lmarks_i->AllGates() [GateIx]; Landmarks_c.Gates.Add (CrntGate, CrntGate->ID()); } for (AirportIx = 0; AirportIx < Lmarks_i->NoOfAirports(); AirportIx++) { CrntAirport = Lmarks_i->AllAirports() [AirportIx]; Landmarks_c.Airports.Add (CrntAirport, CrntAirport->ID()); } for (BeaconIx = 0; BeaconIx < Lmarks_i->NoOfBeacons(); BeaconIx++) { CrntBeacon = Lmarks_i->AllBeacons() [BeaconIx]; Landmarks_c.Beacons.Add (CrntBeacon, CrntBeacon->ID()); } SetForNewCmnd(); }
//------------------------------------------------------------------------------ void BeaconVisual::onModelChanged() { RigidBodyVisual::onModelChanged(); Beacon * beacon = (Beacon*)object_; // do first-time stuff if (health_billboard_.get() == NULL) { beacon->addObserver(ObserverCallbackFun0(this, &BeaconVisual::onBeaconStateChanged), BE_DEPLOYED_CHANGED, &fp_group_); beacon->addObserver(ObserverCallbackFun0(this, &BeaconVisual::onBeaconStateChanged), BE_HOVERING_CHANGED, &fp_group_); beacon->addObserver(ObserverCallbackFun0(this, &BeaconVisual::onBeaconStateChanged), BE_INSIDE_RADIUS_CHANGED, &fp_group_); beacon->addObserver(ObserverCallbackFun0(this, &BeaconVisual::onBeaconStateChanged), BE_CARRIED_CHANGED, &fp_group_); osg::Vec3 offset(0.0f, beacon->getBodyGeom()->getRadius(), 0.0f ); health_bar_ = new HudBar("beacon_health_bar"); health_bar_->setDrawCallback(new DrawBillboardStyle(offset)); health_billboard_ = new osg::Geode(); health_billboard_->addDrawable(health_bar_.get()); // Disable shader and lighting for text health_billboard_->getOrCreateStateSet()->setAttribute(new osg::Program, osg::StateAttribute::OVERRIDE); health_billboard_->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); health_billboard_->getOrCreateStateSet()->setRenderBinDetails(BN_DEFAULT, "RenderBin"); health_billboard_->setNodeMask(NODE_MASK_INVISIBLE); } osg_wrapper_->getOsgNode()->addChild(health_billboard_.get()); std::vector<osg::Node*> outer_node_v = s_scene_manager.findNode(BEACON_OUTER_NODE_NAME, osg_wrapper_->getOsgNode()); if (outer_node_v.size() != 1) throw Exception("Beacon contains zero or more than one outer nodes"); outer_node_ = s_scene_manager.insertLocalTransformNode(outer_node_v[0]); onBeaconStateChanged(); // static beacons are not updated otherwise (rotation!). osg_wrapper_->getOsgNode()->setUpdateCallback(this); }
void NeighbourDiscovery::receiveBeacons() { // Get node configuration Logger::getInstance()->setThreadName(std::this_thread::get_id(), "Beacon Receiver"); LOG(15) << "Starting receiver beacon thread"; std::string nodeId = m_config.getNodeId(); std::string nodeAddress = m_config.getNodeAddress(); uint16_t discoveryPort = m_config.getDiscoveryPort(); std::string discoveryAddress = m_config.getDiscoveryAddress(); bool testMode = m_config.getNeighbourTestMode(); #ifndef LEPTON // Generate this node address information. LOG(65) << "Starting socket into " << discoveryAddress << ":" << discoveryPort; // Create the socket. Socket s = Socket(false); if (!s) { // Stop the application LOG(1) << "Cannot create socket into receiveBeacons thread reason: " << s.getLastError(); g_stop = true; } else { if (!s.setReuseAddress()) { // Stop the application LOG(1) << "Cannot set flag REUSEADDR to socket, reason: " << s.getLastError(); g_stop = true; } else { // Bind the socket. if (!s.bind(discoveryAddress, discoveryPort)) { // Stop the application LOG(1) << "Cannot bind the socket to " << discoveryAddress << ":" << discoveryPort << " reason: " << s.getLastError(); g_stop = true; } else { // Join the multicast group. if (!s.joinMulticastGroup(nodeAddress)) { // Stop the application LOG(1) << "Cannot join the multicast group, reason: " << s.getLastError(); g_stop = true; } else { // Add a timeout to the recv socket s.setRcvTimeOut(m_config.getSocketTimeout()); #endif g_startedThread++; while (!g_stop.load()) { uint32_t beaconLength = 65507; std::string buffer; StringWithSize sws = StringWithSize(buffer, beaconLength); if (s.canRead(m_config.getSocketTimeout())) { s >> sws; // Create a thread to add the new neighbour and let this // receiving more beacons Beacon b = Beacon(buffer); if (b.getNodeId() != nodeId || testMode) { LOG(21) << "Received beacon from " << b.getNodeId() << " " << b.getNodeAddress() << ":" << b.getNodePort(); std::thread([b, this]() { m_neighbourTable->update(std::make_shared<Neighbour>( b.getNodeId(), b.getNodeAddress(), b.getNodePort(), b.getEndpoints())); }).detach(); } } } // Leave from the multicast group if (false /*!s.leaveMulticastGroup()*/) { LOG(4) << "Cannot leave the multicast group, reason: " << s.getLastError(); } #ifndef LEPTON } } } #endif s.close(); #ifndef LEPTON }
void groupBeacons() { STARTCHRONO unsigned int num_beacons = beaconContainer->getNumBeacons(); unsigned int usedBeacons = 0; std::vector<Beacon *> beacons; bool first; TRACET(DEBUG, DGB, "\ngroupBeacons()-----------\n"); // For each beacon found for (unsigned int currentBeaconIndex = 0; currentBeaconIndex < num_beacons; currentBeaconIndex++) { Beacon& currentBeacon = beaconContainer->getBeacon(currentBeaconIndex); // If the beacon is already grouped skip it! if (currentBeacon.used()) continue; currentBeacon.used(true); TRACET(DEBUG, DGB, "Using beacon %d, closest beacons: ", currentBeacon.getId()); // Clear the indexed beacon group beacons.clear(); // Put the first beacon index in the indexed beacon group beacons.push_back(¤tBeacon); // Unset test flag for the beacons for (unsigned int i = currentBeaconIndex + 1; i < num_beacons; i++) beaconContainer->getBeacon(i).tested(false); // Search closest beacons unsigned int notUsedBeacons = beaconContainer->getNumBeacons() - usedBeacons; unsigned int numToTest = notUsedBeacons < MAX_WAYPOINT_BEACONS ? notUsedBeacons : MAX_WAYPOINT_BEACONS; for (unsigned int i = 1; i < numToTest; i++) { float minDistance = INFINITY; Beacon * closestBeacon = NULL; // Search closest beacon for (unsigned int j = currentBeaconIndex + 1; j < num_beacons; j++) { Beacon & beacon = beaconContainer->getBeacon(j); if (beacon.tested() || beacon.used()) continue; float distance = (currentBeacon - beacon).abs(); if (distance < minDistance) { minDistance = distance; closestBeacon = &beacon; } } if (closestBeacon == NULL) { TRACET(DEBUG, DGB, "CRITICAL ERROR: Closest Point not found!\n"); return; } // Set the closest beacon as tested and put it into the beacon group closestBeacon->tested(true); beacons.push_back(closestBeacon); TRACET(DEBUG, DGB, "%d ", closestBeacon->getId()); } // Search minimum beacon distance float minDistance = INFINITY; for (unsigned int i = 0; i < numToTest; i++) { Beacon & iBeacon = *(beacons[i]); for (unsigned int j = i + 1; j < numToTest; j++) { Beacon & jBeacon = *(beacons[j]); float distance = (iBeacon - jBeacon).abs(); if (distance < minDistance) minDistance = distance; } } bool discardCurrentBeacon = false; for (unsigned int i = 1; i < numToTest; i++) { float distance = (*(beacons[0]) - *(beacons[i])).abs(); TRACET(DEBUG, DGB, "\n Distance %d -> %d: %f (min: %f) (%f, %f, %f)", beacons[0]->getId(), beacons[i]->getId(), distance, minDistance,\ beacons[i]->x, beacons[i]->y, beacons[i]->z); if (distance / minDistance > DISTANCE_FACTOR) { if (i == 1) discardCurrentBeacon = true; TRACET(DEBUG, DGB, " Beacon %d is too far\n", beacons[i]->getId()); // Clean far beacons beacons.resize(i); break; } } if (discardCurrentBeacon || beacons.size() < 3) { TRACET(DEBUG, DGB, " Discarding current beacon\n"); beacons[0]->discard(); beacons[0]->used(true); usedBeacons++; } else { // EUREKA!!! beacon group found, generate beaconGroup and set the beacons in the group as used TRACET(DEBUG, DGB, " Beacon group found (%d beacons)\n", int(beacons.size())); BeaconGroup & beaconGroup = beaconContainer->getCleanBeaconGroup(); beaconGroup.appendBeacons(beacons); beaconGroup.computeBeaconGroup(); usedBeacons += beacons.size(); } } TRACET(DEBUG, DGB, "-%d us---------------------------------------\n", GETCLICK); }
/** * Hover beacons up & down when deployed. */ void BeaconVisual::operator() (osg::Node *node, osg::NodeVisitor *nv) { RigidBodyVisual::operator()(node, nv); float time = (float)nv->getFrameStamp()->getSimulationTime(); Beacon * beacon = (Beacon*)object_; if (beacon->getTeamId() == TEAM_ID_ATTACKER && (beacon->isDeployed() || beacon->getState() == BS_HOVERING)) { Vector pos = beacon->getTarget()->getPosition(); pos.y_ += sin(time*BEACON_HOVER_OMEGA) * BEACON_HOVER_AMPLITUDE; osg_wrapper_->setPosition(pos); } // set health bars value depending on beacons health float health_percentage = (float)beacon->getHitpoints()/(float)beacon->getMaxHitpoints(); health_bar_->setValue(health_percentage); osg::Matrix mat; mat.makeRotate(BEACON_ROTATE_SPEED * time, 0.0f, 1.0f, 0.0f); outer_node_->setMatrix(mat); // make billboard invisible on full health or if beacon is carried if (beacon->getHitpoints() == beacon->getMaxHitpoints() || beacon->getState() == BS_CARRIED) { health_billboard_->setNodeMask(NODE_MASK_INVISIBLE); } else { health_billboard_->setNodeMask(NODE_MASK_VISIBLE); } if (prev_healing_ != beacon->isGainingHealth()) { prev_healing_ = beacon->isGainingHealth(); EnableGroupVisitor g(BEACON_HEAL_EFFECT_GROUP_NAME, prev_healing_); osg_wrapper_->getOsgNode()->accept(g); } }
/* Test sending a message using the message properties using the proton api */ int main(int argc, char **argv) { pn_message_t * message; pn_messenger_t * messenger; pn_data_t * body; //const char *brokerURL = "amqp://192.168.1.107:5672/beaconEvents"; const char *brokerURL = "amqp://192.168.1.107:5672/topic://beaconEvents"; message = pn_message(); messenger = pn_messenger(NULL); pn_messenger_start(messenger); check(messenger); pn_message_set_address(message, brokerURL); body = pn_message_body(message); Beacon beacon = testBeacon(); const char *scannerID = beacon.getScannerID().c_str(); const char *uuid = beacon.getUuid().c_str(); int code = beacon.getCode(); int manufacturer = beacon.getManufacturer(); int major = beacon.getMajor(); int minor = beacon.getMinor(); int power = beacon.getPower(); int rssi = beacon.getRssi(); long time = beacon.getTime(); // Encode the beacon as its properties pn_data_t *properties = pn_message_properties(message); pn_data_put_map(properties); pn_data_enter(properties); pn_data_put_string(properties, pn_bytes(strlen("scannerID"), (char *) "scannerID")); pn_data_put_string(properties, pn_bytes(strlen(scannerID), (char *) scannerID)); pn_data_put_string(properties, pn_bytes(strlen("uuid"), (char *) "uuid")); pn_data_put_string(properties, pn_bytes(strlen(uuid), (char *) uuid)); pn_data_put_string(properties, pn_bytes(strlen("code"), (char *) "code")); pn_data_put_int(properties, code); pn_data_put_string(properties, pn_bytes(strlen("manufacturer"), (char *) "manufacturer")); pn_data_put_int(properties, manufacturer); pn_data_put_string(properties, pn_bytes(strlen("major"), (char *) "major")); pn_data_put_int(properties, major); pn_data_put_string(properties, pn_bytes(strlen("minor"), (char *) "minor")); pn_data_put_int(properties, minor); pn_data_put_string(properties, pn_bytes(strlen("power"), (char *) "power")); pn_data_put_int(properties, power); pn_data_put_string(properties, pn_bytes(strlen("rssi"), (char *) "rssi")); pn_data_put_int(properties, rssi); pn_data_put_string(properties, pn_bytes(strlen("time"), (char *) "time")); pn_data_put_long(properties, time); pn_data_exit(properties); pn_messenger_put(messenger, message); check(messenger); pn_messenger_send(messenger, -1); check(messenger); pn_messenger_stop(messenger); pn_messenger_free(messenger); pn_message_free(message); }
bool Beacon::operator==(const Beacon& entry)const { return strcmp(getId(), entry.getId()) == 0; }