Pub Sub C++ Notification Example

NetAcquire Publish/Subscribe C++ Notification Example

Remote temperature data acquisition

NetAcquire Pub Sub Example Code

The example below uses the event-driven variant of the NetAcquire Publish/Subscribe API. Instead of explicitly calling the subscription to obtain its latest value as was done in the simpler examples, here the flow of control is reversed and the subscription calls a user-defined callback method whenever the subscription’s value changes.

#include
#include "naps.hpp"

// callback object
class TemperatureListener : public NA_SubscriptionListener
{
public:
virtual void subscriptionReceived(const NA_SubscriptionEvent& event,
NA_Subscription& sourceSubscription)
{
cout << event.getTimestamp() << ": " << event.asReal32 << endl; } }; int main() { TemperatureListener listener; NA_Connection netacquire1("na1"); NA_Subscription reactor_temperature(netacquire1, "reactor_temperature"); reactor_temperature.addListener(&listener); cin.get(); // wait until user presses
}

The user declares a customized callback class, here called TemperatureListener, as a subclass of the abstract class NA_SubscriptionListener, and overrides the subscriptionReceived method.

Note, how the callback method accesses the event’s timestamp. Note, also, that an explicit accessor is used to retrieve the subscription’s value in the form of a 32 bit float. Instead, one can also insert the event directly into an output stream, in which case the implementation picks the most suitable type.

In the main function an instance of the callback class is instantiated. In the second and third lines of main objects that represent a data publisher and a specific data subscription are created exactly as in the simpler examples. Then the previously created callback object, here called listener, is registered with the subscription. From this point on the subscriptionReceived method of this object will be called whenever the physical quantity that corresponds to the subscription changes. The application’s main thread can now continue with other chores, in this example it simply waits for the user to press the key.

Is NetAcquire a good fit for your project?

Our applications engineers will discuss your needs and offer advice and pricing for the solutions we can provide.
NetAcquire provides quick responses to phone and email queries during Pacific Time business hours.

Call us toll free: 888-675-1122 or email [email protected]

For Employment, Business Affairs and other NetAcquire Contacts, CONTACT US

NetAcquire Corporation