Skip to content

Commit

Permalink
#fix REQREPLY-221: Update RPC examples (#724)
Browse files Browse the repository at this point in the history
* REQREPLY-221: Update RPC examples

* REQREPLY-221: Fix precondition error because the participant is stil alive by the time we call finalize factory

* REQREPLY-221: Add logging

* REQREPLY-221: Remove white spaces

* REQREPLY-221: Add timeout to request reply cs example

* REQREPLY-221: Update code to use the new apis to wait for service

* REQREPLY-221: Undo changes in Inventory.py

* REQREPLY-221: Apply PR feedback

* REQREPLY-221: Fix format

* REQREPLY-221: Add test specification and test implementation

* REQREPLY-221: Add makefile for java

* REQREPLY-221: add csproj

* REQREPLY-221: Undo change in script

* REQREPLY-221: Fix tests paths

* REQREPLY-221: Improve test scripts

* Revert "REQREPLY-221: Improve test scripts"

This reverts commit ae0e3c1.

* REQREPLY-221: Fix testing

* REQREPLY-221: Apply PR feedback
  • Loading branch information
albertorobles2000 authored Nov 13, 2024
1 parent 94bd07a commit db7fc05
Show file tree
Hide file tree
Showing 27 changed files with 531 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -81,31 +81,14 @@ class InventoryImpl : public InventoryService {
std::mutex mutex;
};

int main(int argc, char *argv[])
void run_server(int domain_id, unsigned int delay, unsigned int service_timeout)
{
using namespace application;

// Parse arguments
auto arguments = parse_arguments(argc, argv, false);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}

// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);

// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);

// Create a DomainParticipant with default Qos. The Service will communicate
// only with Clients that join the same domain_id
dds::domain::DomainParticipant participant(arguments.domain_id);
dds::domain::DomainParticipant participant(domain_id);

// Create an instance of the service interface
auto service_impl = std::make_shared<InventoryImpl>(arguments.delay);
auto service_impl = std::make_shared<InventoryImpl>(delay);

// A server provides the execution environment (a thread pool) for one or
// more services
Expand All @@ -126,7 +109,38 @@ int main(int argc, char *argv[])
::InventoryServiceService service(service_impl, server, params);

std::cout << "InventoryService running... " << std::endl;
server.run();
server.run(std::chrono::seconds(service_timeout));
}

int main(int argc, char *argv[])
{
using namespace application;

// Parse arguments
auto arguments = parse_arguments(argc, argv, false);
if (arguments.parse_result == ParseReturn::exit) {
return EXIT_SUCCESS;
} else if (arguments.parse_result == ParseReturn::failure) {
return EXIT_FAILURE;
}

// Sets Connext verbosity to help debugging
rti::config::Logger::instance().verbosity(arguments.verbosity);

// To turn on additional logging, include <rti/config/Logger.hpp> and
// uncomment the following line:
// rti::config::Logger::instance().verbosity(rti::config::Verbosity::STATUS_ALL);

try {
run_server(
arguments.domain_id,
arguments.delay,
arguments.service_timeout);
} catch (const std::exception &ex) {
// This will catch DDS exceptions
std::cerr << "Exception in run_server(): " << ex.what() << std::endl;
return EXIT_FAILURE;
}

// Releases the memory used by the participant factory. Optional at
// application exit
Expand Down
33 changes: 23 additions & 10 deletions examples/connext_dds/remote_procedure_call/c++11/application.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ struct ApplicationArguments {
std::string item_name;
unsigned int quantity;
unsigned int delay;
unsigned int service_timeout;
rti::config::Verbosity verbosity;

ApplicationArguments(
Expand All @@ -38,13 +39,15 @@ struct ApplicationArguments {
const std::string &item_name_param,
unsigned int quantity_param,
unsigned int delay_param,
unsigned int service_timeout_param,
rti::config::Verbosity verbosity_param)
: parse_result(parse_result_param),
domain_id(domain_id_param),
add(add_param),
item_name(item_name_param),
quantity(quantity_param),
delay(delay_param),
service_timeout(service_timeout_param),
verbosity(verbosity_param)
{
}
Expand Down Expand Up @@ -82,6 +85,7 @@ inline ApplicationArguments parse_arguments(int argc, char *argv[], bool client)
unsigned int domain_id = 0;
unsigned int quantity = 1;
unsigned int delay = 0;
unsigned int service_timeout = INT32_MAX;
std::string item_name = "";
bool add = true;
rti::config::Verbosity verbosity(rti::config::Verbosity::EXCEPTION);
Expand Down Expand Up @@ -131,6 +135,12 @@ inline ApplicationArguments parse_arguments(int argc, char *argv[], bool client)
|| strcmp(argv[arg_processing], "--delay") == 0)) {
delay = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else if (
(argc > arg_processing + 1)
&& (strcmp(argv[arg_processing], "-s") == 0
|| strcmp(argv[arg_processing], "--service-timeout") == 0)) {
service_timeout = atoi(argv[arg_processing + 1]);
arg_processing += 2;
} else {
std::cout << "Bad parameter." << std::endl;
show_usage = true;
Expand All @@ -147,16 +157,18 @@ inline ApplicationArguments parse_arguments(int argc, char *argv[], bool client)

if (show_usage) {
std::cout << "Usage:\n"\
" -d, --domain <int> Domain ID this application will\n" \
" subscribe in. \n"
" Default: 0\n"\
" -a, --add <item_name> Add an item to the inventory\n"\
" -r, --remove <item_name> Remove an item from the inventory\n"\
" -q, --quantity <int> Number of items to add or remove\n"\
" Default: 1\n"
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-3 \n"
" Default: 1"
" -d, --domain <int> Domain ID this application will\n" \
" subscribe in. \n"
" Default: 0\n"\
" -a, --add <item_name> Add an item to the inventory\n"\
" -r, --remove <item_name> Remove an item from the inventory\n"\
" -q, --quantity <int> Number of items to add or remove\n"\
" Default: 1\n"
" -s, --service-timeout <int> Numbers of senconds the service will run\n"\
" Default: infinite\n"
" -v, --verbosity <int> How much debugging output to show.\n"\
" Range: 0-3 \n"
" Default: 1"
<< std::endl;
}

Expand All @@ -167,6 +179,7 @@ inline ApplicationArguments parse_arguments(int argc, char *argv[], bool client)
item_name,
quantity,
delay,
service_timeout,
verbosity);
}

Expand Down
30 changes: 30 additions & 0 deletions examples/connext_dds/remote_procedure_call/py/Inventory.idl
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*******************************************************************************
(c) 2024 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.
******************************************************************************/

struct Item {
string name;
int64 quantity;
};

struct InventoryContents {
sequence<Item> items;
};

exception UnknownItemError {
string name;
};

@service("DDS")
interface InventoryService {
InventoryContents get_inventory();
void add_item(Item item);
void remove_item(Item item) raises (UnknownItemError);
};
11 changes: 11 additions & 0 deletions examples/connext_dds/remote_procedure_call/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,14 @@ Updated inventory: InventoryContents(items=[Item(name='apples', quantity=100),
For a description of the concurrency model, see the
[Remote Procedure Calls](https://community.rti.com/static/documentation/connext-dds/7.2.0/doc/api/connext_dds/api_python/rpc.html#remote-procedure-calls)
section of the Connext Python API Reference.

## Code Generation

If you want to modify the DDS Service in the idl you will have to re-generate
the service code using **rtiddsgen**

```sh
<install dir>/bin/rtiddsgen -language Python -update typefiles Inventory.idl
```

Where `<install dir>` refers to your RTI Connext installation.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ async def run_client(args):
client = InventoryClient(
participant, "Inventory", max_wait_per_call=dds.Duration(20)
)

# For versions 7.4.0 and below:
await wait_for_service(client)
# For newer versions you can use the following:
# await client.wait_for_service_async(dds.Duration(20))

print("Initial inventory: ", await client.get_inventory())

Expand Down
27 changes: 25 additions & 2 deletions examples/connext_dds/remote_procedure_call/py/inventory_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
#

import argparse
import asyncio
import sys
import rti.connextdds as dds
import rti.rpc as rpc
import rti.asyncio
Expand Down Expand Up @@ -60,6 +62,13 @@ async def remove_item(self, item: Item):
del self.inventory[item.name]


async def run_service(service: rpc.Service):
try:
await service.run(close_on_cancel=True)
except asyncio.CancelledError:
pass


async def main():
parser = argparse.ArgumentParser(description="Inventory client")
parser.add_argument(
Expand All @@ -78,16 +87,30 @@ async def main():
help="Delay in seconds for the add and remove operations (default: 0)",
)

parser.add_argument(
"-s",
"--service-timeout",
type=int,
default=sys.maxsize,
help="Numbers of senconds the service will run (default: infinite)",
)

args = parser.parse_args()

participant = dds.DomainParticipant(args.domain)
service = rpc.Service(InventoryImpl(args.delay), participant, "Inventory")

await service.run()
print("InventoryService running...")
service_task = asyncio.create_task(run_service(service))

await asyncio.sleep(args.service_timeout)

service_task.cancel()


if __name__ == "__main__":
dds.Logger.instance.verbosity = dds.Verbosity.WARNING
# Uncomment this to turn on additional logging
# dds.Logger.instance.verbosity = dds.Verbosity.WARNING
try:
# Run the service until Ctrl-C is pressed
rti.asyncio.run(main())
Expand Down
11 changes: 9 additions & 2 deletions examples/connext_dds/request_reply/cs/PrimesProgram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ public static async Task Main(string[] args)
}

// Set up signal handler to Dispose the DDS entities
var cancellationSource = new CancellationTokenSource();
var cancellationSource = arguments.Timeout > 0
? new CancellationTokenSource(TimeSpan.FromSeconds(arguments.Timeout))
: new CancellationTokenSource();
Console.CancelKeyPress += (_, eventArgs) =>
{
Console.WriteLine("Shutting down...");
Expand Down Expand Up @@ -100,6 +102,7 @@ private class Arguments
public int Domain { get; set; }
public int N { get; set; } = int.MaxValue;
public int PrimesPerReply { get; set; }
public int Timeout { get; set; }
}

// Uses the System.CommandLine package to parse the program arguments.
Expand All @@ -124,7 +127,11 @@ private static Arguments ParseArguments(string[] args)
description: "The number to calculate primes up to (only applicable with --requester)"),
new System.CommandLine.Option<int>(
new string[] { "--primes-per-reply", "-p" },
getDefaultValue: () => 5)
getDefaultValue: () => 5),
new System.CommandLine.Option<int>(
new string[] { "--timeout" },
getDefaultValue: () => 0,
description: "Timeout in seconds to wait for the application to finish (default: infinite)"),
};

rootCommand.Description = "Example RTI Connext Requester and Replier";
Expand Down
2 changes: 2 additions & 0 deletions tests/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
!*/java/makefile*
!*.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/bash
cd ${BaseExamplePath}/java
java -Djava.library.path=$NDDSHOME/lib/x64Linux4gcc7.3.0 -cp ".:$NDDSHOME/lib/java/nddsjava.jar" DynamicDataNestedStruct $@
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
######################################################################
#
# (c) Copyright, Real-Time Innovations, 2024.
# All rights reserved.
# No duplications, whole or partial, manual or electronic, may be made
# without express written permission. Any such copies, or
# revisions thereof, must display this notice unaltered.
# This code contains trade secrets of Real-Time Innovations, Inc.
#
######################################################################

# RTI_JAVA_OPTION=-d64

SOURCE_DIR =

TARGET_ARCH=x64Linux4gcc7.3.0

ifndef DEBUG
DEBUG=0
endif
ifeq ($(DEBUG),1)
DEBUG_FLAGS += -g
else
DEBUG_FLAGS =
endif

JAVA_PATH = java
JAVAC_PATH = javac

JAVA_SOURCES = $(SOURCE_DIR)./DynamicDataNestedStruct.java
CLASS_FILES = $(JAVA_SOURCES:%.java=%.class)

RTI_CLASSPATH := $(NDDSHOME)/lib/java/nddsjava.jar

%.class : %.java
$(JAVAC_PATH) $(DEBUG_FLAGS) -classpath ".:$(RTI_CLASSPATH)" $<

all: $(CLASS_FILES)
Loading

0 comments on commit db7fc05

Please sign in to comment.