async def process_bus(route, vehicle, num_stops, time_between_stops): connector = rti.Connector("MyParticipantLibrary::Participant", "busNetwork.xml") position = connector.getOutput("Publisher::PositionWriter") accident = connector.getOutput("Publisher::AccidentWriter") loops = 0 while loops < 3: current_stop = 1 while current_stop <= num_stops: # Generate traffic traffic = random.choices( [["Normal", 1.0], ["Light", .75], ["Heavy", 1.5]], [.65, .25, .1]) await asyncio.sleep(time_between_stops * traffic[0][1]) # Report position position.instance.set_string("timestamp", str(datetime.datetime.now())) position.instance.set_string("route", route) position.instance.set_string("vehicle", vehicle) position.instance.set_number("stopNumber", current_stop) position.instance.set_number("numStops", num_stops) position.instance.set_number("timeBetweenStops", time_between_stops) position.instance.set_string("trafficConditions", traffic[0][0]) position.instance.set_number("fillInRatio", random.randint(0, 101)) position.write() print("{0} is on route {1} at stop {2} at {3}".format( vehicle, route, current_stop, str(datetime.datetime.now()))) # Check for accident if random.choices([True, False], [.1, .9])[0]: accident.instance.set_string("timestamp", str(datetime.datetime.now())) accident.instance.set_string("route", route) accident.instance.set_string("vehicle", vehicle) accident.instance.set_number("stopNumber", current_stop) accident.write() print("{0} reported an accident on route {1} before " "stop {2} at {3}".format(vehicle, route, current_stop, str(datetime.datetime.now()))) current_stop += 1 loops += 1
def __init__(self, config_path, **kwargs): super(DDSAgent, self).__init__(**kwargs) self.reader = {} self.writer = {} config = utils.load_config(config_path) for typename, type_config in config.iteritems(): participant_name = type_config['participant_name'] xml_config_path = type_config['xml_config_path'] publisher_name = type_config['publisher_name'] subscriber_name = type_config['subscriber_name'] connector = rti.Connector(participant_name, xml_config_path) self.writer[typename] = connector.getOutput(publisher_name) self.reader[typename] = connector.getInput(subscriber_name)
def writer(): """A writer is going to start sending samples.""" print("Running writer...") connector = rti.Connector("MyParticipantLibrary::Zero", "/usr/local/bin/PingConfiguration.xml") outputDDS = connector.getOutput("MyPublisher::PingWriter") i = 0 while True: print("Sending ping message number " + str(i)) outputDDS.instance.setNumber("number", i) i += 1 outputDDS.write() sleep(1)
def reader(): """A reader is going to start receiving samples.""" print("Running reader...") connector = rti.Connector("MyParticipantLibrary::Zero", "/bin/PingConfiguration.xml") inputDDS = connector.getInput("MySubscriber::PingReader") timeout = 2000 # 2 seconds while True: ret = connector.wait(timeout) if ret == 0: inputDDS.take() numOfSamples = inputDDS.samples.getLength() for j in range(1, numOfSamples + 1): if inputDDS.infos.isValid(j): pingID = int(inputDDS.samples.getNumber(j, "number")) # Print the sample print("Received ping message number " + str(pingID)) else: print("No ping was received")
############################################################################## # Copyright (c) 2005-2015 Real-Time Innovations, Inc. All rights reserved. # Permission to modify and use for internal purposes granted. # This software is provided "as is", without warranty, express or implied. ############################################################################## """Samples's writer.""" from sys import path as sysPath from os import path as osPath from time import sleep filepath = osPath.dirname(osPath.realpath(__file__)) sysPath.append(filepath) import rticonnextdds_connector as rti connector = rti.Connector("MyParticipantLibrary::Zero", filepath + "/ShapeExample.xml") outputDDS = connector.getOutput("MyPublisher::MySquareWriter") for i in range(1, 5): outputDDS.instance.setNumber("x", i) outputDDS.instance.setNumber("y", i * 2) outputDDS.instance.setNumber("shapesize", 30) outputDDS.instance.setString("color", "BLUE") outputDDS.write() sleep(0.2)
# 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. # ############################################################################### """Samples's reader.""" from __future__ import print_function from sys import path as sysPath from os import path as osPath from time import sleep filepath = osPath.dirname(osPath.realpath(__file__)) sysPath.append(filepath + "/../../../") import rticonnextdds_connector as rti connector = rti.Connector( "MyParticipantLibrary::DashBoard", #loading the same app as the writer filepath + "/DDS.xml") temperatures_DDS = connector.getInput("MySubscriber::MyTempReader") #StartStopDDS = connector.getInput("MySubscriber::MyStartStopReader") actuators_DDS = connector.getInput("MySubscriber::MyActuatorReader") while True: temperatures_DDS.take() numOfSamples = temperatures_DDS.samples.getLength() for j in range(0, numOfSamples): if temperatures_DDS.infos.isValid(j): temp = temperatures_DDS.samples.getNumber(j, "Temp") toPrint = "Received Temp: " + repr(temp) print(toPrint) #for checking the start and stop buttom #StartStopDDS.take()
"""Samples's reader.""" from __future__ import print_function from sys import path as sysPath from os import path as osPath from time import sleep filepath = osPath.dirname(osPath.realpath(__file__)) sysPath.append((filepath + "/../")) import rticonnextdds_connector as rti connector = rti.Connector("MyParticipantLibrary::Infinity", filepath + "/../XML/robot.xml") inputDDS = connector.getInput("MySubscriber::MyRobotReader") for i in range(1, 500): inputDDS.read() numOfSamples = inputDDS.samples.getLength() for j in range(1, numOfSamples + 1): if inputDDS.infos.isValid(j): # Or you can just access the field directly cam = inputDDS.samples.getBoolean(j, "cam") temperature = inputDDS.samples.getNumber(j, "temperature") humidity = inputDDS.samples.getNumber(j, "humidity") robot_id = inputDDS.samples.getNumber(j, "robot_id") servo_angle_position = inputDDS.samples.getNumber( j, "servo_angle_position") toPrint = "Camera: " + repr(cam) + " ID: " + repr( int(robot_id)) + " Received temperature: " + repr( temperature) + " humidity: " + repr(
self.timestamp = time.time() return self.value if __name__ == '__main__': import rticonnextdds_connector as rti import time import argparse cliparser = argparse.ArgumentParser(description="Connect Sensor simulator") cliparser.add_argument("--id", help="sensor identifier", default=0) args = cliparser.parse_args() connector = rti.Connector("MyParticipantLibrary::Sensor", 'Tutorial.xml') writer = connector.getOutput("TempPublisher::TempWriter") # Create a sensor sensor = Sensor("SENSOR#{}".format(args.id)) while 1: sensor.readvalue() writer.instance.setString('id', sensor.id) writer.instance.setNumber('value', sensor.value) writer.instance.setNumber('timestamp', sensor.timestamp) print "[{ts}] Updating sensor {id} value: {value}".format( ts=sensor.timestamp, id=sensor.id, value=sensor.value) writer.write()
############################################################################## # Copyright (c) 2005-2015 Real-Time Innovations, Inc. All rights reserved. # Permission to modify and use for internal purposes granted. # This software is provided "as is", without warranty, express or implied. ############################################################################## """Reader using the wait call.""" from __future__ import print_function from sys import path as sysPath from os import path as osPath from time import sleep filepath = osPath.dirname(osPath.realpath(__file__)) sysPath.append(filepath + "/../../../") import rticonnextdds_connector as rti connector = rti.Connector("MyParticipantLibrary::Zero", filepath + "/../Mixed.xml") inputDDS = connector.getInput("MySubscriber::MySquareReader") for i in range(1, 500): timeout = -1 print("Calling wait with a timeout of " + repr(timeout)) ret = connector.wait(timeout) print("The wait returned " + repr(ret)) inputDDS.take() numOfSamples = inputDDS.samples.getLength() for j in range(1, numOfSamples+1): if inputDDS.infos.isValid(j): """There are two alternative way to access the sample... 1) get it as a dictionary and then access the field in the standard python way:""" sample = inputDDS.samples.getDictionary(j)
#!/usr/bin/env python import rticonnextdds_connector as rti import time import os def print_header(): os.system("clear") print "{0: <10} {1: <10} {2: <10}".format("ID", "VALUE", "TIMESTAMP") print "-" * 80 conn = rti.Connector("MyParticipantLibrary::Console", 'Tutorial.xml') reader = conn.getInput("TempSubscriber::TempReader") while 1: reader.wait(5000) reader.read() print_header() nsamples = reader.samples.getLength() for i in range(1, nsamples + 1): if reader.infos.isValid(i): s = reader.samples.getDictionary(i) print "{id: <10} {val: <10} {ts: <10}".format(id=s["id"], val=s["value"], ts=s["timestamp"])
############################################################################### # (c) 2005-2015 Copyright, Real-Time Innovations. 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. # ############################################################################### """Samples's writer.""" from sys import path as sysPath from os import path as osPath from time import sleep import random filepath = osPath.dirname(osPath.realpath(__file__)) sysPath.append(filepath + "/../../../") import rticonnextdds_connector as rti connector = rti.Connector("MyParticipantLibrary::Temperature", filepath + "/DDS.xml") outputDDS = connector.getOutput("MyPublisher::MyTempWriter") while(True): randomTemp = random.randint(10,61) outputDDS.instance.setNumber("Temp", randomTemp) outputDDS.write() sleep(0.1)
from sys import path as sysPath import rticonnextdds_connector as rti from os import path as osPath from time import sleep import random filepath = osPath.dirname(osPath.realpath(__file__)) connector = rti.Connector("MyParticipantLibrary::Ars_pub", filepath + "/DDS.xml") outputDDS = connector.getOutput("MyPublisher::MyWriter") while True: randomTemp = random.randint(0, 10) outputDDS.instance.setNumber("Temp", randomTemp) outputDDS.write() sleep(0.1) print(f'published: {randomTemp}')
import rticonnextdds_connector as rti import time import sys connector = rti.Connector("MyParticipantLibrary::Zero", "position.xml") positionSubscription = connector.getInput( "Subscriber::P2464_EECS_Bumjin_Park_POS") accidentSubscription = connector.getInput( "Subscriber::P2464_EECS_Bumjin_Park_ACC") #print("MessageType {: >12}{: >6}{: >10}{: >3}{: >15}{: >20}{: >10}{: >15}".format("Route", "Vehicle", "Traffic", "Stop#", "#Stops", "TimeBetweenStops", "Fill%", "Timestamp")) print("Waiting for the bus...") expressName = sys.argv[1] startStop = int(sys.argv[2]) endStop = int(sys.argv[3]) print(expressName) print(startStop) print(endStop) foundName = "null" switch = 0 stopper = 0 howManyLeft = 0 getOnSwitch = 0 timeTem = "null" trafficTem = "null" storedname = "null" leftstops = 0
############################################################################### # (c) 2005-2015 Copyright, Real-Time Innovations. 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. # ############################################################################### """Samples's writer.""" from sys import path as sysPath from os import path as osPath from time import sleep filepath = osPath.dirname(osPath.realpath(__file__)) sysPath.append(filepath + "/../../../") import rticonnextdds_connector as rti connector = rti.Connector("MyParticipantLibrary::StartStop", filepath + "/DDS.xml") StartStopDDS = connector.getOutput("MyPublisher::MyStartStopWriter") while (True): StartStopDDS.instance.setNumber("Start", 1) StartStopDDS.write() sleep(20) StartStopDDS.instance.setNumber("Start", 0) StartStopDDS.write() sleep(5)
) from pkg_resources import get_distribution, parse_version try: import rticonnextdds_connector as rti except Exception as e: raise ImportError( "\nYou haven't installed a needed RTI DDS library. \n\nFirst, ensure you have" + " pip installed:\n\n\tsudo apt-get install python-pip\n\n" + "Then install the library:\n\n\tpip install rticonnextdds-connector\n") import math import threading filepath = osPath.dirname(osPath.realpath(__file__)) connector = rti.Connector("MyParticipantLibrary::Zero", filepath + "/dds_types/CurrentDDSProfile.xml") rti_version = get_distribution("rticonnextdds-connector").version is_old_version = parse_version(rti_version) < parse_version("0.4.1") def is_shutdown(): return False class DdsSubscriberManager: subscribers = dict() sem = None def __init__(self): self.sem = threading.Semaphore()
from __future__ import print_function import sys import os import logging from sys import path as sysPath from os import path as osPath from time import sleep filepath = osPath.dirname(osPath.realpath(__file__)) sysPath.append(filepath + "/../rticonnextdds-connector/") import rticonnextdds_connector as rti connector = rti.Connector("MyParticipantLibrary::Zero", filepath + "\\PythonDDSPlayhouse.xml") inputDDS = connector.getInput("MySubscriber::MySampleReader") instanceNumber = '0' if len(sys.argv) > 1: instanceNumber = sys.argv[1] logging.basicConfig( filename='EndProcessor_DDSTest_' + instanceNumber + '.log', level=logging.DEBUG, format='%(asctime)-15s - %(levelname)8s - %(lineno)d - %(message)s') logging.info('------------------Logging started------------------') print('logging started to EndProcessor_DDSTest_' + instanceNumber + '.log') # 'default.topic.config': {'auto.offset.reset': 'smallest'} #c = Consumer({'bootstrap.servers': 'localhost:9092', 'group.id': 'python_ends_client'})
g={1: g1, 2: g2, 3: g3, 4: g4, 5: g5,}; #len(sys.argv) to get the entire length of the argument list xml_file=sys.argv[1]; # gets the first argument with open(xml_file) as file1: #xml file should be in the same root folder as this file else provide full path name doc = xmltodict.parse(file1.read()); domain_participant_library=doc['dds']['domain_participant_library']['@name']; domain_participant_name=doc['dds']['domain_participant_library']['domain_participant']['@name']; #protect connector calls via threads connector = rti.Connector(domain_participant_library+ "::" + domain_participant_name,"./"+xml_file); publisher=doc['dds']['domain_participant_library']['domain_participant']['publisher']['@name']; subscriber=doc['dds']['domain_participant_library']['domain_participant']['subscriber']['@name']; no_of_topics=len(doc['dds']['domain_participant_library']['domain_participant']['publisher']['data_writer']); no_of_register_types=len(doc['dds']['domain_library']['domain']['register_type']); no_of_data_types=len(doc['dds']['types']['struct']); def printData(input,topics): while 1: for k in range(0,len(input)): input[k].take(); numberOfSamples = input[k].samples.getLength(); for j in range(1,numberOfSamples+1):
############################################################################## # Copyright (c) 2005-2015 Real-Time Innovations, Inc. All rights reserved. # Permission to modify and use for internal purposes granted. # This software is provided "as is", without warranty, express or implied. ############################################################################## """Samples's writer.""" from sys import path as sysPath from os import path as osPath from time import sleep filepath = osPath.dirname(osPath.realpath(__file__)) sysPath.append(filepath + "../") import rticonnextdds_connector as rti connector = rti.Connector("MyParticipantLibrary::Zero", filepath + "/PositionTest.xml") outputDDS = connector.getOutput("MyPublisher::MyTextWriter") for i in range(1, 500): outputDDS.instance.setString("frameName", "Example Name") outputDDS.instance.setNumber("valueKeys", 12345) outputDDS.write() sleep(2)
from time import sleep import rticonnextdds_connector as rti connector = rti.Connector("MyParticipantLibrary::Zero", "Bus.xml") position_subscription = connector.getInput("Subscriber::P2464_EECS_YUKALANGBUANA_POS") accident_subscription = connector.getInput("Subscriber::P2464_EECS_YUKALANGBUANA_ACC") print("MessageType {: >10}{: >18}{: >15}{: >15}{: >15}{: >20}{: >10}{: >15}".format("Route", "Vehicle", "Traffic", "Stop#", "#Stops", "TimeBetweenStops", "Fill%", "Timestamp")) while True: position_subscription.take() accident_subscription.take() num_of_busses_positions = position_subscription.samples.getLength() num_of_accidents = accident_subscription.samples.getLength() if num_of_accidents > 0: for j in range(0, num_of_accidents): if accident_subscription.infos.isValid(j): bus_route = accident_subscription.samples.getString(j, "route") vehicle = accident_subscription.samples.getString(j, "vehicle") stop_number = accident_subscription.samples.getNumber(j, "stopNumber") timestamp = accident_subscription.samples.getString(j, "timestamp") print("Accident {: >15}{: >15}{: >30}{: >60}".format(bus_route, vehicle, int(stop_number), timestamp)) if num_of_busses_positions > 0: for j in range(0, num_of_busses_positions): if position_subscription.infos.isValid(j): bus_route = position_subscription.samples.getString(j, "route") vehicle = position_subscription.samples.getString(j, "vehicle") traffic_condition = position_subscription.samples.getString(j, "trafficConditions") stop_number = position_subscription.samples.getNumber(j, "stopNumber")