/*******************************************************************************
 (c) 2005-2014 Copyright, Real-Time Innovations, Inc.  All rights reserved.
 RTI grants Licensee a license to use, modify, compile, and create derivative
 works of the Software.  Licensee has the right to distribute object form only
 for use with RTI products.  The Software is provided "as is", with no warranty
 of any type, including any warranty for fitness for any purpose. RTI is under
 no obligation to maintain or support the Software.  RTI shall not be liable for
 any incidental or consequential damages arising out of the use or inability to
 use the software.
 ******************************************************************************/
/* deadline_contentfilter_subscriber.cxx

   A subscription example

   This file is derived from code automatically generated by the rtiddsgen 
   command:

   rtiddsgen -language C++ -example <arch> deadline_contentfilter.idl

   Example subscription of type deadline_contentfilter automatically generated
   by 'rtiddsgen'. To test them follow these steps:

   (1) Compile this file and the example publication.

   (2) Start the subscription on the same domain used for RTI Data Distribution
       Service with the command
       objs/<arch>/deadline_contentfilter_subscriber <domain_id> <sample_count>

   (3) Start the publication on the same domain used for RTI Data Distribution
       with the command
       objs/<arch>/deadline_contentfilter_publisher <domain_id> <sample_count>

   (4) [Optional] Specify the list of discovery initial peers and 
       multicast receive addresses via an environment variable or a file 
       (in the current working directory) called NDDS_DISCOVERY_PEERS. 
       
   You can run any number of publishers and subscribers programs, and can 
   add and remove them dynamically from the domain.
              
                                   
   Example:
        
       To run the example application on domain <domain_id>:
                          
       On Unix: 
       
       objs/<arch>/deadline_contentfilter_publisher <domain_id> 
       objs/<arch>/deadline_contentfilter_subscriber <domain_id> 
                            
       On Windows:
       
       objs\<arch>\deadline_contentfilter_publisher <domain_id>  
       objs\<arch>\deadline_contentfilter_subscriber <domain_id>   
              
       
modification history
------------ -------       
* Create clock to show relative timing of events

* Define listener for requested deadline missed status

* Set deadline QoS

* Create content filter that ignores second instance
  after 5 seconds
*/

/* This example sets the deadline period to 2 seconds to trigger a deadline if
   the DataWriter does not update often enough, or if the content-filter 
   filters out data so there is no data available within 2 seconds. 

   This example starts by filtering out instances >= 2, and changes to later 
   filter out instances >= 1.

*/
#include <stdio.h>
#include <stdlib.h>
#include "ndds/ndds_cpp.h"
#include "deadline_contentfilter.h"
#include "deadline_contentfilterSupport.h"

//// Changes for Deadline
// For timekeeping
#include <time.h>
clock_t init;

class deadline_contentfilterListener : public DDSDataReaderListener {
  public:
    virtual void on_requested_deadline_missed(
        DDSDataReader* /*reader*/,
        const DDS_RequestedDeadlineMissedStatus& /*status*/);
    
    virtual void on_requested_incompatible_qos(
        DDSDataReader* /*reader*/,
        const DDS_RequestedIncompatibleQosStatus& /*status*/) {}
    
    virtual void on_sample_rejected(
        DDSDataReader* /*reader*/,
        const DDS_SampleRejectedStatus& /*status*/) {}

    virtual void on_liveliness_changed(
        DDSDataReader* /*reader*/,
        const DDS_LivelinessChangedStatus& /*status*/) {}

    virtual void on_sample_lost(
        DDSDataReader* /*reader*/,
        const DDS_SampleLostStatus& /*status*/) {}

    virtual void on_subscription_matched(
        DDSDataReader* /*reader*/,
        const DDS_SubscriptionMatchedStatus& /*status*/) {}

    virtual void on_data_available(DDSDataReader* reader);
};

/* Start changes for Deadline */
void deadline_contentfilterListener::on_requested_deadline_missed(
    DDSDataReader* reader, const DDS_RequestedDeadlineMissedStatus& status)
{
    double elapsed_ticks = clock() - init;
    double elapsed_secs = elapsed_ticks/CLOCKS_PER_SEC;
    
	/* Creates a temporary object of our structure "deadline_contentfilter"
	 * in order to find out which instance missed its deadline period.  The
	 * get_key_value call only fills in the values of the key fields inside
	 * the dummy object.
	 */
    deadline_contentfilter dummy;
    DDS_ReturnCode_t retcode =
        ((deadline_contentfilterDataReader*)reader)->get_key_value(
            dummy, status.last_instance_handle);
    
    if (retcode != DDS_RETCODE_OK) {
        printf("get_key_value error %d\n", retcode);
        return;
    }

	/* Print out which instance missed its deadline. */
    printf("Missed deadline @ t=%.2fs on instance code = %d\n",
           elapsed_secs, dummy.code);
}
/* End changes for Deadline */

void deadline_contentfilterListener::on_data_available(DDSDataReader* reader)
{
    deadline_contentfilterDataReader *deadline_contentfilter_reader = NULL;
    deadline_contentfilterSeq data_seq;
    DDS_SampleInfoSeq info_seq;
    DDS_ReturnCode_t retcode;
    int i;

    deadline_contentfilter_reader =
            deadline_contentfilterDataReader::narrow(reader);
    if (deadline_contentfilter_reader == NULL) {
        printf("DataReader narrow error\n");
        return;
    }

    retcode = deadline_contentfilter_reader->take(
        data_seq, info_seq, DDS_LENGTH_UNLIMITED,
        DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);

    if (retcode == DDS_RETCODE_NO_DATA) {
        return;
    } else if (retcode != DDS_RETCODE_OK) {
        printf("take error %d\n", retcode);
        return;
    }

    for (i = 0; i < data_seq.length(); ++i) {
        if (info_seq[i].valid_data) {
            /* Start changes for Deadline */
            /* print the time we get each sample. */
            double elapsed_ticks = clock() - init;
            double elapsed_secs = elapsed_ticks/CLOCKS_PER_SEC;
            
            printf("@ t=%.2fs, Instance%d: <%d,%d>\n",
                   elapsed_secs, data_seq[i].code, data_seq[i].x,
                   data_seq[i].y);
            /* deadlineTypeSupport::print_data(&data_seq[i]); */
            /* End changes for Deadline */
        }
    }

    retcode = deadline_contentfilter_reader->return_loan(data_seq, info_seq);
    if (retcode != DDS_RETCODE_OK) {
        printf("return loan error %d\n", retcode);
    }
}

/* Delete all entities */
static int subscriber_shutdown(
    DDSDomainParticipant *participant)
{
    DDS_ReturnCode_t retcode;
    int status = 0;

    if (participant != NULL) {
        retcode = participant->delete_contained_entities();
        if (retcode != DDS_RETCODE_OK) {
            printf("delete_contained_entities error %d\n", retcode);
            status = -1;
        }

        retcode = DDSTheParticipantFactory->delete_participant(participant);
        if (retcode != DDS_RETCODE_OK) {
            printf("delete_participant error %d\n", retcode);
            status = -1;
        }
    }

    /* RTI Data Distribution Service provides finalize_instance() method for
       people who want to release memory used by the participant factory
       singleton. Uncomment the following block of code for clean destruction of
       the participant factory singleton. */
/*
    retcode = DDSDomainParticipantFactory::finalize_instance();
    if (retcode != DDS_RETCODE_OK) {
        printf("finalize_instance error %d\n", retcode);
        status = -1;
    }
*/
    return status;
}

extern "C" int subscriber_main(int domainId, int sample_count)
{
    DDSDomainParticipant *participant = NULL;
    DDSSubscriber *subscriber = NULL;
    DDSTopic *topic = NULL;
    deadline_contentfilterListener *reader_listener = NULL; 
    DDSDataReader *reader = NULL;
    DDS_ReturnCode_t retcode;
    const char *type_name = NULL;
    int count = 0;
    struct DDS_Duration_t receive_period = {1,0};
    int status = 0;

    /* Changes for Deadline */
    /* for timekeeping */
    init = clock();

    /* To customize participant QoS, use 
       DDSTheParticipantFactory->get_default_participant_qos() */
    participant = DDSTheParticipantFactory->create_participant(
        domainId, DDS_PARTICIPANT_QOS_DEFAULT, 
        NULL /* listener */, DDS_STATUS_MASK_NONE);
    if (participant == NULL) {
        printf("create_participant error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* To customize subscriber QoS, use
       participant->get_default_subscriber_qos() */
    subscriber = participant->create_subscriber(
        DDS_SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, DDS_STATUS_MASK_NONE);
    if (subscriber == NULL) {
        printf("create_subscriber error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* Register type before creating topic */
    type_name = deadline_contentfilterTypeSupport::get_type_name();
    retcode = deadline_contentfilterTypeSupport::register_type(
        participant, type_name);
    if (retcode != DDS_RETCODE_OK) {
        printf("register_type error %d\n", retcode);
        subscriber_shutdown(participant);
        return -1;
    }

    /* To customize topic QoS, use
       participant->get_default_topic_qos() */
    topic = participant->create_topic(
        "Example deadline_contentfilter",
        type_name, DDS_TOPIC_QOS_DEFAULT, NULL /* listener */,
        DDS_STATUS_MASK_NONE);
    if (topic == NULL) {
        printf("create_topic error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* Create data reader listener */
    reader_listener = new deadline_contentfilterListener();
    if (reader_listener ==  NULL) {
        printf("listener instantiation error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* Start changes for Deadline */
    /* Set up content filtered topic to show interaction with deadline */
    DDS_StringSeq parameters(1);
    const char* param_list[] = {"2"};
    parameters.from_array(param_list, 1);

    DDSContentFilteredTopic *cft = NULL;
    cft = participant->create_contentfilteredtopic(
        "ContentFilteredTopic", topic, "code < %0", parameters);

    /* Get default datareader QoS to customize */
    DDS_DataReaderQos datareader_qos;
    retcode = subscriber->get_default_datareader_qos(datareader_qos);
    if (retcode != DDS_RETCODE_OK) {
        printf("get_default_datareader_qos error\n");
        return -1;
    }

    reader = subscriber->create_datareader(
        cft, DDS_DATAREADER_QOS_DEFAULT, 
        reader_listener,
        DDS_STATUS_MASK_ALL);
    if (reader == NULL) {
        printf("create_datareader error\n");
        subscriber_shutdown(participant);
        delete reader_listener;
        return -1;
    }
    /* If you want to change the DataReader's QoS programmatically rather than
     * using the XML file, you will need to add the following lines to your
     * code and comment out the create_datareader call above.
     *
     * In this case, we set the deadline period to 2 seconds to trigger
     * a deadline if the DataWriter does not update often enough, or if
     * the content-filter filters out data so there is no data available
     * with 2 seconds.
     */


    /* Set deadline QoS */
/*    DDS_Duration_t deadline_period = {2, 0};
    datareader_qos.deadline.period = deadline_period;

    reader = subscriber->create_datareader(
        cft, datareader_qos, reader_listener,
        DDS_STATUS_MASK_ALL);
    if (reader == NULL) {
        printf("create_datareader error\n");
        subscriber_shutdown(participant);
        delete reader_listener;
        return -1;
    }
*/

    /* Main loop */
    for (count=0; (sample_count == 0) || (count < sample_count); ++count) {

/*        printf("deadline_contentfilter subscriber sleeping for %d sec...\n",
               receive_period.sec);
*/

        /* After 10 seconds, change content filter to accept only instance 0 */
        if (count == 10) {
            printf("Starting to filter out instance1\n");
            parameters[0] = DDS_String_dup("1");
            cft->set_expression_parameters(parameters);
        }
        NDDSUtility::sleep(receive_period);
    }

    /* End changes for Deadline */

    /* Delete all entities */
    status = subscriber_shutdown(participant);
    delete reader_listener;

    return status;
}

#if defined(RTI_WINCE)
int wmain(int argc, wchar_t** argv)
{
    int domainId = 0;
    int sample_count = 0; /* infinite loop */ 
    
    if (argc >= 2) {
        domainId = _wtoi(argv[1]);
    }
    if (argc >= 3) {
        sample_count = _wtoi(argv[2]);
    }
    
    /* Uncomment this to turn on additional logging
    NDDSConfigLogger::get_instance()->
        set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, 
                                  NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
    */
                                  
    return subscriber_main(domainId, sample_count);
}

#elif !(defined(RTI_VXWORKS) && !defined(__RTP__)) && !defined(RTI_PSOS)
int main(int argc, char *argv[])
{
    int domainId = 0;
    int sample_count = 0; /* infinite loop */

    if (argc >= 2) {
        domainId = atoi(argv[1]);
    }
    if (argc >= 3) {
        sample_count = atoi(argv[2]);
    }


    /* Uncomment this to turn on additional logging
    NDDSConfigLogger::get_instance()->
        set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API, 
                                  NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
    */
                                  
    return subscriber_main(domainId, sample_count);
}
#endif

