def onMessage(self, connMgr, message): try: # Display the XML representation of the received message libgmsec_python.logInfo("[ExampleCallback:onMessage] Received:\n" + message.toXML()) # Construct Reply subject. component = "" try: component = message.getStringField("COMPONENT").getValue() except Exception as e: libgmsec_python.logWarning( "COMPONENT field is not available: " + e.what()) # Set Status Code to indicate Successful Completion. # The GMSEC Interface Specification Document defines 6 # unique STATUS-CODE values: # 1 - Acknowledgement # 2 - Working/keep alive # 3 - Successful completion # 4 - Failed completion # 5 - Invalid request # 6 - Final message # If an asynchronous requestor is awaiting a reply, the # ReplyCallback in use will remain active for multiple # messages, so long as the messages it receives contain # a STATUS-CODE of either 1 or 2. status_code = "3" # Create the reply subject. # See API Interface Specificaiton Document for # more information on Reply Message subjects. # Generally speaking, they are composed # accordingly: # [Spec].[Mission].[Satellite ID]. # [Message Type].[Component Name].[Status Code] reply_subject = "GMSEC.MISSION.SAT_ID.RESP.REPLY_ASYNC." + status_code reply = libgmsec_python.Message(reply_subject, libgmsec_python.Message.REPLY) # Add fields to the reply message reply.addField("COMPONENT", component) reply.addField("ANSWER", "Sure looks like it!") # Display XML representation of reply message libgmsec_python.logInfo("Prepared Reply:\n" + reply.toXML()) # Send Reply connMgr.reply(message, reply) self.replySent = True except libgmsec_python.Exception as e: libgmsec_python.logError("[ExampleCallback::onMessage] " + e.what())
def onMessage(self, connection, message): try: libgmsec_python.logInfo("Received a message with subject: " + message.getSubject()) libgmsec_python.logInfo("Field Name (Field Type): Field Value") iter = message.getFieldIterator() while (iter.hasNext()): field = iter.next() # Extract the Field Name, Type, and Value (As # a string, to print) # # Note: 'getter' functions are also defined for # Integer, Unsigned Integer, and Double values. libgmsec_python.logInfo(field.getName() + " (" + typeToString(field.getType()) + "): " + field.getStringValue()) # Field objects can also be converted to # specific Field types prior to retrieval of # the value contained in the Field. This is # useful for ensuring that data types do not # lose any level of precision, but requires # a more intricate implementation. # # See the getFieldValue() function (commented # out at the bottom of this example program) # for an example of how field can be done. except libgmsec_python.Exception as e: libgmsec_python.logError(e.what())
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[ 0] + " <config-file>" + "\nPlease see the GMSEC_API/example/cpp/message_field_container directory for an example xml configuration file." print usageMessage return -1 # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging() try: # Demonstration of setting the configuration options via # configuration file createMsgUsingConfigFile(sys.argv[1]) # Demonstration of hard-coding the configuration options # using a Config object createMsgUsingConfigObject() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def onMessage(self, connMgr, message): try: # Run the message through the GMSEC API-supplied validation connMgr.getSpecification().validateMessage(message) # In this example scenario, we are expecting to receive a # GMSEC PROD message containing a URI to a location on the disk # where a product file has been placed for retrieval. In this # case, we want to validate that the location on the disk is # in an area which we would expect (i.e. Something that the # team has agreed upon prior to operational deployment). # # By validating this URI, we ensure that no malicious users # have infiltrated the system and somehow modified the messages # to cause us to retrieve a file from an unknown location. # Start by checking to ensure that this is a PROD message if (isProdMsg(message)): prodMessage = libgmsec_python.ProductFileMessage( message.toXML()) # Determine how many product files this message # contains numFiles = prodMessage.getNumProductFiles() # Extract the Product File URI location(s) from the # message # # Note: Not all Product Files will be transferred by # URI. If implementing something like this, add some # error handling. for i in xrange(0, numFiles): # TODO (MIST Note): When using getProductFile(size_t), the number does not correspond to the number in the Field name. # e.g. If the Message contains 1 ProductFile, using getProductFile(1) will return an error, whereas getProductFile(0) will not. prodUri = prodMessage.getProductFile(i).getURI() # Check to ensure that the URI contains "//hostname/dir" if (prodUri.find("//hostname/dir") == -1): errorMsg = "Received an invalid PROD Message (bad URI):\n" + message.toXML( ) raise libgmsec_python.Exception( libgmsec_python.MIST_ERROR, libgmsec_python.MESSAGE_FAILED_VALIDATION, errorMsg) libgmsec_python.logInfo("Received a valid message:\n" + message.toXML()) except libgmsec_python.Exception as e: libgmsec_python.logError(e.what())
def onMessage(self, connMgr, message): try: # Run the message through the GMSEC API-supplied validation connMgr.getSpecification().validateMessage(message) # In this example scenario, we are expecting to receive a # GMSEC PROD message containing a URI to a location on the disk # where a product file has been placed for retrieval. In this # case, we want to validate that the location on the disk is # in an area which we would expect (i.e. Something that the # team has agreed upon prior to operational deployment). # # By validating this URI, we ensure that no malicious users # have infiltrated the system and somehow modified the messages # to cause us to retrieve a file from an unknown location. # Start by checking to ensure that this is a PROD message if (isProdMsg(message)): prodMessage = libgmsec_python.ProductFileMessage(connMgr.getSpecification(), message.toXML()) # Get the iterator so that we can analyze each Product File within the message prodFileIter = prodMessage.getProductFileIterator() # For each Product File available... while prodFileIter.hasNext(): # Get the next Product File prodFile = prodFileIter.next() # Extract the URI from the Product File prodUri = prodFile.getURI() # Check to ensure that the URI contains "//hostname/dir"; if not, report an error if (prodUri.find("//hostname/dir") == -1): errorMsg = "This error is expected; received an invalid PROD Message (bad URI):\n" + prodMessage.toXML() raise libgmsec_python.Exception(libgmsec_python.MIST_ERROR, libgmsec_python.MESSAGE_FAILED_VALIDATION, errorMsg) libgmsec_python.logInfo("Received a valid message:\n" + prodMessage.toXML()) except libgmsec_python.Exception as e: libgmsec_python.logError(e.what())
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Enable Message validation. This parameter is "false" by default. config.addValue("GMSEC-MSG-CONTENT-VALIDATE", "true") # Tell the API that there is an additional layer of message schema to # validate (The 'EXAMPLE' message definitions). This value is set to # 0 (Only 'GMSEC' specification validation) by default. # Note: These levels for validation are determined by the "LEVEL-X" # attributes defined in the .DIRECTORY.xml file contained in the XML # templates directory. In thise case, Level-0 means GMSEC and Level-1 # means EXAMPLE. # Note: The GMSEC team envisions using message specifications in a # layered hierarchical fashion. For example, the "GMSEC" message # specification would be 'layer 0', followed by an organization-level # message specification at 'layer 1' which builds upon the message # specification outlined in the GMSEC ISD. This would be followed by # a mission-level message specification at 'layer 2' and so on. config.addValue("GMSEC-SCHEMA-LEVEL", "1") # Tell the API where to find all of the schema files. # Note: This example only demonstrates a simple usage case of this # functionality. When using this functionality, if the intent is # to use any of the GMSEC message definitions, then ALL of the XML # template files must be contained in the same directory. # e.g. GMSEC_API/templates/2016.00 (Or the location defined in # GMSEC-SCHEMA-PATH) config.addValue("GMSEC-SCHEMA-PATH", "templates") libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: connMgr = libgmsec_python.ConnectionManager(config) libgmsec_python.logInfo( "Opening the connection to the middleware server") connMgr.initialize() libgmsec_python.logInfo(connMgr.getLibraryVersion()) definedFields = libgmsec_python.FieldList() missionField = libgmsec_python.StringField("MISSION-ID", "MISSION") satIdField = libgmsec_python.StringField("SAT-ID-PHYSICAL", "SPACECRAFT") facilityField = libgmsec_python.StringField("FACILITY", "GMSEC Lab") componentField = libgmsec_python.StringField("COMPONENT", "log_message") definedFields.append(missionField) definedFields.append(satIdField) definedFields.append(facilityField) definedFields.append(componentField) connMgr.setStandardFields(definedFields) # Create a Message using a subject defined in the XML template # outlining our example addendum message definitions message = libgmsec_python.MistMessage(EXAMPLE_MESSAGE_SUBJECT, "MSG.LOG", connMgr.getSpecification()) # Add all of the necessary Fields to our message message.addField(libgmsec_python.U16Field("NUM-OF-EVENTS", 2)) message.setValue("EVENT.1", addTimeToString("AOS occurred at: ")) message.setValue("EVENT.2", addTimeToString("Telemetry downlink began at: ")) connMgr.addStandardFields(message) # Publish the message to the middleware bus connMgr.publish(message) # Display the XML string representation of the Message for # the sake of review libgmsec_python.logInfo("Published message:\n" + message.toXML()) # Setup a new message without some of the Required Fields and # attempt to publish it (i.e. Trigger a validation failure) badMessage = libgmsec_python.MistMessage(EXAMPLE_MESSAGE_SUBJECT, "MSG.LOG", connMgr.getSpecification()) try: connMgr.publish(badMessage) except libgmsec_python.Exception as e: libgmsec_python.logError("This is an expected error:\n" + e.what()) # Disconnect from the middleware and clean up the Connection connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if(len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object connManager = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo("Opening the connection to the middleware server") connManager.initialize() # Output middleware client library version libgmsec_python.logInfo(connManager.getLibraryVersion()) # Create all of the GMSEC Message header Fields which will # be used by all GMSEC Messages # Note: Since these Fields contain variable values which are # based on the context in which they are used, they cannot be # automatically populated using MistMessage. definedFields = libgmsec_python.FieldList() missionField = libgmsec_python.StringField("MISSION-ID", "MISSION") # Note: SAT-ID-PHYSICAL is an optional header Field, according satIdField = libgmsec_python.StringField("SAT-ID-PHYSICAL", "SPACECRAFT") facilityField = libgmsec_python.StringField("FACILITY", "GMSEC Lab") componentField = libgmsec_python.StringField("COMPONENT", "product_message") definedFields.append(missionField) definedFields.append(satIdField) definedFields.append(facilityField) definedFields.append(componentField) # Use setStandardFields to define a set of header fields for # all messages which are created or published on the # ConnectionManager using the following functions: # createLogMessage, publishLog, createHeartbeatMessage, # startHeartbeatService, createResourceMessage, # publishResourceMessage, or startResourceMessageService connManager.setStandardFields(definedFields) # Create a ProductFile object with the product name, # description, version, file format, and the URI externalFile = libgmsec_python.ProductFile("External File", "External File Description", "1.0.0", "TXT", "//hostname/dir/filename") filePayload = bytearray() for i in range(0, 256): filePayload.append(i) # Create a ProductFile object with the product name, # description, version, format, binary array, and file size binaryFile = libgmsec_python.ProductFile("File as Binary", "Binary File Description", "1.0.0", "BIN", filePayload, len(filePayload)) # Create a Product File Message with the subject, # RESPONSE-STATUS Field value, Message type (publish, request, # or reply), PROD-TYPE Field value, PROD-SUBTYPE Field value, # and pass it the Specification object from the Connection # Manager productMessage = libgmsec_python.ProductFileMessage(PROD_MESSAGE_SUBJECT, libgmsec_python.ResponseStatus.SUCCESSFUL_COMPLETION, libgmsec_python.Message.PUBLISH, "AUTO", "DM", connManager.getSpecification()) productMessage.addProductFile(externalFile) productMessage.addProductFile(binaryFile) connManager.addStandardFields(productMessage) libgmsec_python.logInfo("Publishing DEV message:\n" + productMessage.toXML()) connManager.publish(productMessage) except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object # This is the linchpin for all communications between the # GMSEC API and the middleware server connMgr = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo( "Opening the connection to the middleware server") connMgr.initialize() # Output middleware client library version libgmsec_python.logInfo(connMgr.getLibraryVersion()) # Set up a subscription to listen for Messages with the topic # "GMSEC.TEST.PUBLISH" which are published to the middleware # bus # Subscription subject wildcard syntax: # * - Matches any one token separated by periods in a subject # > - Reading left to right, matches everything up to and ONE # or more tokens in a subject # + - Reading left to right, matches everything up to and ZERO # or more tokens in a subject # For more information on wildcards, please see the GMSEC API # User's Guide libgmsec_python.logInfo("Subscribing to the topic: " + EXAMPLE_SUBSCRIPTION_SUBJECT) connMgr.subscribe(EXAMPLE_SUBSCRIPTION_SUBJECT) # Add a specific message subject to the Connection's exclusion # filter libgmsec_python.logInfo("Adding a filter rule for the topic: " + FILTERED_MESSAGE_SUBJECT) connMgr.excludeSubject(FILTERED_MESSAGE_SUBJECT) # Call receive() to synchronously retrieve a message that has # been received by the middleware client libraries # Timeout periods: # -1 - Wait forever # 0 - Return immediately # >0 - Time in milliseconds before timing out libgmsec_python.logInfo("Waiting to receive a Message") message = connMgr.receive(-1) # Example error handling for calling receive() with a timeout if (message != None): libgmsec_python.logInfo("Received message:\n" + message.toXML()) libgmsec_python.logInfo( "Waiting 5 seconds to demonstrate that a second message will not be received" ) message = connMgr.receive(5000) if (message != None): libgmsec_python.logError( "Unexpectedly received a filtered message:\n" + message.toXML()) # Disconnect from the middleware and clean up the Connection connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 cb = AsyncStatusCheckCallback() # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Since this example program uses an invalid message, we ensure the # validation check is disabled. config.addValue("gmsec-msg-content-validate-all", "false") # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Toggle the WebSphere MQ client libraries-level asynchronous publish # functionality on config.addValue("MW-ASYNC-PUBLISH", "true") # Toggle the periodic WebSphere MQ asynchronous publish status report # functionality on. The GMSEC API Connection will periodically fire # off an Event which will trigger the onEvent function of an # EventCallback registered to the event labeled, # Connection::WSMQ_ASYNC_STATUS_CHECK_EVENT config.addValue("MW-ASYNC-STATUS-CHECK", "true") # Additionally, the "MW-ASYNC-STATUS-CHECK-MESSAGE-INTERVAL" # configuration option can be used to instruct the GMSEC Connection # on how frequently (in number of publish operations) it should # periodically fire the WSMQ_ASYNC_STATUS_CHECK_EVENT. By default, it # will fire once every 100 messages. # For the sake of this example, we will use 500 messages. config.addValue("MW-ASYNC-STATUS-CHECK-MESSAGE-INTERVAL", "500") # Print the GMSEC API version number using the GMSEC Logging # interface libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create the Connection connMgr = libgmsec_python.ConnectionManager(config) # Connect connMgr.initialize() # Register the event callback with the connection to catch # the WebSphere asynchronous publish status events which are # eminated from the API connMgr.registerEventCallback( libgmsec_python.Connection.WSMQ_ASYNC_STATUS_CHECK_EVENT, cb) # Output middleware version libgmsec_python.logInfo("Middleware version = " + connMgr.getLibraryVersion()) libgmsec_python.logInfo("Publishing messages using the subject: " + EXAMPLE_MESSAGE_SUBJECT) # Create a GMSEC Message object message = libgmsec_python.Message(EXAMPLE_MESSAGE_SUBJECT, libgmsec_python.Message.PUBLISH) # Publish message as quickly as possible # (i.e. No sleep operation between each publish operation) count = 0 while (not cb.eventFired): # Populate the Message with fields, increment a # counter so that a publisher can track how many # messages were published (if they are interested) count += 1 populateMessage(message, count) # Publish the message to the middleware bus connMgr.publish(message) # Note: We do not recommend printing the output of a # message when publishing it while using the WebSphere # async publish functionality, as it is # counter-intuitive to take take up CPU resources # performing I/O operations when attempting to achieve # high message throughput rates. As such, if you want # to analyze the messages published by this program, # we recommend you execute GMSEC_API/bin/gmsub to # receive the messages. libgmsec_python.logInfo("Event detected, ending example demonstration") # Clean up the ConnectionManager before exiting the program connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if(len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Since this example program uses an invalid message, we ensure the # validation check is disabled. config.addValue("gmsec-msg-content-validate-all", "false") # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Output GMSEC API version libgmsec_python.logInfo(libgmsec_python.Connection.getAPIVersion()) try: # Create the Connection connMgr = libgmsec_python.ConnectionManager(config) # Connect connMgr.initialize() # output connection middleware version libgmsec_python.logInfo(connMgr.getLibraryVersion()) # Create request message requestMsg = libgmsec_python.Message(DEFAULT_REQUEST_SUBJECT, libgmsec_python.Message.REQUEST) # Add fields to request message requestMsg.addField("QUESTION", "Does the request/reply functionality still work?") requestMsg.addField("COMPONENT", "request_async") # Display XML representation of request message libgmsec_python.logInfo("Requesting:\n" + requestMsg.toXML()) cb = ExampleReplyCallback() connMgr.request(requestMsg, -1, cb) libgmsec_python.logInfo("Waiting for response...") # Loop while waiting for the asynchronous response until done while (cb.receivedReply == 0): libgmsec_python.TimeUtil.millisleep(100) if (cb.receivedReply): libgmsec_python.logInfo("Response Received!") else: libgmsec_python.logWarning("No response received") connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): print("Usage: " + sys.argv[0] + " mw-id=<middleware ID>") return -1 # Setup configuration with the supplied command line arguments config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Unless otherwise configured, setup configuration that allows us to # log messages to stderr. initializeLogging(config) # Display the version number of the GMSEC API libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) # Obtain the specification version that we are running with; if not provided, default to GMSEC_ISD_CURRENT specVersion = config.getIntegerValue("gmsec-specification-version", libgmsec_python.GMSEC_ISD_CURRENT) # Define standard fields that will be included with the heartbeat messages standardFields = libgmsec_python.FieldList() component = libgmsec_python.StringField("COMPONENT", "HEARTBEAT-GENERATOR") mission = libgmsec_python.StringField("MISSION-ID", "MY-MISSION") satellite = libgmsec_python.StringField("SAT-ID-PHYSICAL", "MY-SAT-ID") facility = libgmsec_python.StringField("FACILITY", "MY-FACILITY") standardFields.push_back(component) standardFields.push_back(mission) standardFields.push_back(satellite) standardFields.push_back(facility) if specVersion == libgmsec_python.GMSEC_ISD_2014_00: msgID = libgmsec_python.StringField("MSG-ID", "MY-MSG-ID") standardFields.push_back(msgID) elif specVersion >= libgmsec_python.GMSEC_ISD_2018_00: domain1 = libgmsec_python.StringField("DOMAIN1", "MY-DOMAIN-1") domain2 = libgmsec_python.StringField("DOMAIN2", "MY-DOMAIN-2") standardFields.push_back(domain1) standardFields.push_back(domain2) try: # Instantiate the heartbeat generator hbgen = libgmsec_python.HeartbeatGenerator(config, HB_MESSAGE_SUBJECT, HB_PUBLISH_RATE, standardFields) # Start the heartbeat generator hbgen.start() libgmsec_python.logInfo( "Heartbeat Generator is running; use gmsub or other utility to monitor messages." ) # Wait for input from user to stop the heartbeat generator libgmsec_python.logInfo( "Press <enter> to stop the heartbeat generator") raw_input("") # Stop the heartbeat generator hbgen.stop() libgmsec_python.logInfo("Heartbeat Generator has been stopped.") except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if(len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object connManager = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo("Opening the connection to the middleware server") connManager.initialize() # Output middleware client library version libgmsec_python.logInfo(connManager.getLibraryVersion()) # Begin the steps necessary to create a GMSEC-compliant LOG # message using the ConnectionManager # Create all of the GMSEC Message header Fields which will # be used by all GMSEC Messages # Note: Since these Fields contain variable values which are # based on the context in which they are used, they cannot be # automatically populated using MistMessage. definedFields = libgmsec_python.FieldList() missionField = libgmsec_python.StringField("MISSION-ID", "MISSION") # Note: SAT-ID-PHYSICAL is an optional header Field, according # to the GMSEC ISD. satIdField = libgmsec_python.StringField("SAT-ID-PHYSICAL", "SPACECRAFT") facilityField = libgmsec_python.StringField("FACILITY", "GMSEC Lab") componentField = libgmsec_python.StringField("COMPONENT", "log_message") definedFields.append(missionField) definedFields.append(satIdField) definedFields.append(facilityField) definedFields.append(componentField) # Use setStandardFields to define a set of header fields for # all messages which are created or published on the # ConnectionManager using the following functions: # createLogMessage, publishLog, createHeartbeatMessage, # startHeartbeatService, createResourceMessage, # publishResourceMessage, or startResourceMessageService connManager.setStandardFields(definedFields) # Use MistMessage to construct a GMSEC LOG message based off # of the latest XML templates provided with the GMSEC API. # This will automatically populate the Message with all of the # Fields which have specific values defined for them in the XML # template files. For more information on which Fields have # values defined for them, please review the XML template files # located in GMSEC_API/templates. # Note: The second parameter is an identifier for the type of # message to construct. logMsg = libgmsec_python.MistMessage(LOG_MESSAGE_SUBJECT, "MSG.LOG", connManager.getSpecification()) # Add the LOG-specific fields to the LOG message # Note: Since these Fields contain variable values which are # based on the context in which they are used, they cannot be # automatically populated using MistMessage. eventTime = "YYYY-DDD-HH:MM:SS.sss" libgmsec_python.TimeUtil.formatTime(libgmsec_python.TimeUtil.getCurrentTime(), eventTime); logMsg.addField(libgmsec_python.I16Field("SEVERITY",1)) logMsg.setValue("MSG-TEXT", "Creating an example GMSEC LOG Message") logMsg.setValue("OCCURRENCE-TYPE", "SYS") logMsg.setValue("SUBCLASS", "AST") logMsg.setValue("EVENT-TIME", eventTime) # Add the standard fields to the LOG message connManager.addStandardFields(logMsg) libgmsec_python.logInfo("Publishing LOG message:\n" + logMsg.toXML()) connManager.publish(logMsg) except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if(len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config); # Enable Message validation. This parameter is "false" by default. config.addValue("GMSEC-MSG-CONTENT-VALIDATE", "true") libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: connMgr = libgmsec_python.ConnectionManager(config) libgmsec_python.logInfo("Opening the connection to the middleware server") connMgr.initialize() connMgr.getLibraryVersion() # Set up the ValidationCallback and subscribe vc = ValidationCallback() connMgr.subscribe(PROD_MESSAGE_SUBJECT, vc) # Start the AutoDispatcher connMgr.startAutoDispatch() # Create and publish a simple Product File Message setupStandardFields(connMgr) productMessage = createProductFileMessage(connMgr, "//hostname/dir/filename") # Publish the message to the middleware bus connMgr.publish(productMessage) productMessage = createProductFileMessage(connMgr, "//badhost/dir/filename") connMgr.publish(productMessage) # Disconnect from the middleware and clean up the Connection connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(argv=None): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object connManager = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo( "Opening the connection to the middleware server") connManager.initialize() # Output middleware client library version libgmsec_python.logInfo(connManager.getLibraryVersion()) # Create all of the GMSEC Message header Fields which will # be used by all GMSEC Messages headerFields = libgmsec_python.FieldList() missionField = libgmsec_python.StringField("MISSION-ID", "GMSEC") facilityField = libgmsec_python.StringField("FACILITY", "GMSEC Lab") componentField = libgmsec_python.StringField("COMPONENT", "heartbeat_service") headerFields.append(missionField) headerFields.append(facilityField) headerFields.append(componentField) # Use setStandardFields to define a set of header fields for # all messages which are created or published on the # ConnectionManager using the following functions: # createLogMessage, publishLog, createHeartbeatMessage, # startHeartbeatService, createResourceMessage, # publishResourceMessage, or startResourceMessageService connManager.setStandardFields(headerFields) # Note: Fields are immutable, so plan appropriately if you wish # to re-use variable names! # Create all of the GMSEC Message header Fields which # will be used by all GMSEC HB Messages hbStandardFields = libgmsec_python.FieldList() pubRateField = libgmsec_python.U16Field("PUB-RATE", 30) counterField = libgmsec_python.U16Field("COUNTER", 1) # Note: COMPONENT-STATUS is an optional field used to # denote the operating status of the component, the # values are as follows: # 0 - Debug # 1 - Normal / Green # 2 - Warning / Yellow # 3 - Orange # 4 - Error / Red componentStatusField = libgmsec_python.I16Field("COMPONENT-STATUS", 0) hbStandardFields.append(pubRateField) hbStandardFields.append(counterField) hbStandardFields.append(componentStatusField) # Create and publish a Heartbeat message using # createLogMessage() and publish() # Note: This is useful for applications which may need # to create proxy heartbeats on behalf of a subsystem, # as creating multiple ConnectionManagers can consume # more memory than necessary. In this case, extra # logic would need to be added to handle the timing of # the publications. hbMsg = connManager.createHeartbeatMessage(HB_MESSAGE_SUBJECT, hbStandardFields) libgmsec_python.logInfo( "Publishing the GMSEC C2CX HB message which was just created using createHeartbeatMessage():\n" + hbMsg.toXML()) connManager.publish(hbMsg) # Kick off the Heartbeat Service -- This will publish # heartbeat messages automatically every X seconds, # where Xis the value which was provided for PUB-RATE # Note: If PUB-RATE was not provided, it will default # to 30 seconds per automatic Heartbeat publication libgmsec_python.logInfo( "Starting the Heartbeat service, a message will be published every " + pubRateField.getStringValue() + " seconds") connManager.startHeartbeatService(HB_MESSAGE_SUBJECT, hbStandardFields) # Use setHeartbeatServiceField to change the state of the # COMPONENT-STATUS Field to indicate that the component has # transitioned from a startup/debug state to a running/green # state. componentStatusField = libgmsec_python.I16Field("COMPONENT-STATUS", 1) connManager.setHeartbeatServiceField(componentStatusField) libgmsec_python.logInfo( "Publishing C2CX Heartbeat Messages indefinitely, press <enter> to exit the program" ) raw_input("") # Stop the Heartbeat Service connManager.stopHeartbeatService() # Cleanup connManager.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Since this example program uses an invalid message, we ensure the # validation check is disabled. config.addValue("gmsec-msg-content-validate-all", "false") # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Output GMSEC API version libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create the Connection connMgr = libgmsec_python.ConnectionManager(config) # Connect connMgr.initialize() # output connection middleware version libgmsec_python.logInfo(connMgr.getLibraryVersion()) # Subscribe cb = ExampleCallback() connMgr.subscribe(DEFAULT_REQUEST_SUBJECT, cb) # Start the AutoDispatcher to begin async message receipt connMgr.startAutoDispatch() # Loop while waiting for the asynchronous response until done while (cb.replySent == False): libgmsec_python.TimeUtil.millisleep(100) # Clean up connMgr.stopAutoDispatch() connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Enable Message Binning config.addValue("GMSEC-USE-MESSAGE-BINS", "true") # Specify the number of messages to be aggregated prior to publishing # the aggregate message to the middleware server (This applies to all # of the messages which match the subject(s) provided in the # GMSEC-MSG-BIN-SUBJECT-N configuration parameters # Note: The aggregate message will be sent to the middleware server # immediately upon this many messages being published, regardless of # the value supplied for GMSEC-MSG-BIN-TIMEOUT. config.addValue("GMSEC-MSG-BIN-SIZE", "5") # Specify a timeout (in milliseconds) for the aggregate message to be # sent to the middleware server # Note: The aggregate message will be sent to the middleware server # after this period of time if the message bin does not fill up (per # the value provided for GMSEC-MSG-BIN-SIZE) prior to this timeout config.addValue("GMSEC-MSG-BIN-TIMEOUT", "5000") # Specify the subjects to aggreate messages for. # Note: Subscription wildcard syntax can be used here, and has been # supported since GMSEC API version 4.3. config.addValue("GMSEC-MSG-BIN-SUBJECT-1", "GMSEC.*.PUBLISH") # Specify any subjects that should be excluded from being aggregated # This is useful if a wildcard subscription is provided in one of the # GMSEC-MSG-BIN-SUBJECT-N parameters. config.addValue("GMSEC-MSG-BIN-EXCLUDE-SUBJECT-1", EXAMPLE_BIN_EXCLUDE_SUBJECT) # Since this example program uses an invalid message, we ensure the # validation check is disabled. config.addValue("gmsec-msg-content-validate-all", "false") # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object # This is the linchpin for all communications between the # GMSEC API and the middleware server connMgr = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo( "Opening the connection to the middleware server") connMgr.initialize() # Output middleware client library version libgmsec_python.logInfo(connMgr.getLibraryVersion()) # Create a message message = libgmsec_python.Message(EXAMPLE_MESSAGE_SUBJECT, libgmsec_python.Message.PUBLISH) for i in range(0, 5): populateMessage(message, i + 1) # Publish the message to the middleware bus connMgr.publish(message) # Display the XML string representation of the Message for # the sake of review libgmsec_python.logInfo("Published message: " + message.toXML()) # Create another message message = libgmsec_python.Message(EXAMPLE_BIN_EXCLUDE_SUBJECT, libgmsec_python.Message.PUBLISH) populateMessage(message, 1) # Publish the message to the middleware bus # Note: When calling publish(), if a message does NOT match # one of the subjects to be aggregated, it will be immediately # published connMgr.publish(message) # Display the XML string representation of the Message for # the sake of review libgmsec_python.logInfo("Published message: " + message.toXML()) # Disconnect from the middleware and clean up the Connection connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def onEvent(self, connection, status, event): if (status.isError()): libgmsec_python.logError("[ExampleReplyCallback::onError] " + status.get() + ", event=" + event)
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object connManager = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo( "Opening the connection to the middleware server") connManager.initialize() # Output middleware client library version libgmsec_python.logInfo(connManager.getLibraryVersion()) # Create all of the GMSEC Message header Fields which will # be used by all GMSEC Messages headerFields = libgmsec_python.FieldList() version = connManager.getSpecification().getVersion() missionField = libgmsec_python.StringField("MISSION-ID", "MY-MISSION") facilityField = libgmsec_python.StringField("FACILITY", "MY-FACILITY") componentField = libgmsec_python.StringField("COMPONENT", "RESOURCE-SERVICE") domain1Field = libgmsec_python.StringField("DOMAIN1", "MY-DOMAIN-1") domain2Field = libgmsec_python.StringField("DOMAIN2", "MY-DOMAIN-2") msgID = libgmsec_python.StringField("MSG-ID", "MY-MSG-ID") headerFields.append(missionField) headerFields.append(facilityField) headerFields.append(componentField) if (version == 201400): headerFields.append(msgID) elif (version >= 201800): headerFields.append(domain1Field) headerFields.append(domain2Field) # Use setStandardFields to define a set of header fields for # all messages which are created or published on the # ConnectionManager using the following functions: # createLogMessage, publishLog, createHeartbeatMessage, # startHeartbeatService, createResourceMessage, # publishResourceMessage, or startResourceMessageService connManager.setStandardFields(headerFields) # Create and publish a Resource message using # createResourceMessage() and publish() # Note: This is useful for applications which may need to add # additional Fields to the Resource Messages which are not # currently added by the GMSEC API rsrcMsg = connManager.createResourceMessage(RSRC_MESSAGE_SUBJECT) libgmsec_python.logInfo( "Publishing the GMSEC C2CX RSRC message which was created using createResourceMessage():\n" + rsrcMsg.toXML()) connManager.publish(rsrcMsg) # Kick off the Resource Service -- This will publish resource # messages automatically every X seconds, where X is the second # parameter provided to the startResourceMessageService() function. # If an interval is not provided, the service will default to # publishing a message every 60 seconds. libgmsec_python.logInfo( "Starting the Resource Message service, a message will be published every " + str(RSRC_PUBLISH_RATE) + " seconds") connManager.startResourceMessageService(RSRC_MESSAGE_SUBJECT, RSRC_PUBLISH_RATE) # Wait for user input to end the program libgmsec_python.logInfo( "Publishing C2CX Resource Messages indefinitely, press <enter> to exit the program" ) raw_input("") # Stop the Heartbeat Service connManager.stopResourceMessageService() # Cleanup connManager.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(agrv=None): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Create and register log handlers errorHandler = ErrorHandler() warningHandler = WarningHandler() infoHandler = InfoHandler() verboseHandler = VerboseHandler() debugHandler = DebugHandler() anyHandler = AnyHandler() libgmsec_python.Log.registerHandler(libgmsec_python.logERROR, errorHandler) libgmsec_python.Log.registerHandler(libgmsec_python.logWARNING, warningHandler) libgmsec_python.Log.registerHandler(libgmsec_python.logINFO, infoHandler) libgmsec_python.Log.registerHandler(libgmsec_python.logVERBOSE, verboseHandler) libgmsec_python.Log.registerHandler(libgmsec_python.logDEBUG, debugHandler) # Set logging reporting level libgmsec_python.Log.setReportingLevel(libgmsec_python.logVERBOSE) libgmsec_python.logVerbose("The log reporting level is now set to: " + str(libgmsec_python.Log.getReportingLevel())) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create the ConnectionManager connMgr = libgmsec_python.ConnectionManager(config) # Connect connMgr.initialize() # Output middleware client library version libgmsec_python.logInfo(connMgr.getLibraryVersion()) # Publish a message publishTestMessage(connMgr, "GMSEC.TEST.PUBLISH") # Disconnect from the middleware and clean up the Connection connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 # Unregister log handlers libgmsec_python.Log.registerHandler(None) # Set log stream to stderr config.addValue("LOGFILE", "STDERR") libgmsec_python.logInfo("This message should go to stderr, not stdout. " + "For example, in bash test by running as:\n" + "./logging mw-id=bolt 2> testfile.txt\n" + "... and then check the contents of testfile.txt") # Reset log stream to stdout config.addValue("LOGFILE", "STDOUT") libgmsec_python.logError("This is an example error message.") libgmsec_python.logWarning("This is an example warning message.") libgmsec_python.logVerbose("This is an example \"verbose\" message.") libgmsec_python.logDebug( "This is an example debug message which should not show.") # This last message cannot be shown right now because # Log::setReportingLevel(logVERBOSE), used above, does not # allow DEBUG messages to come out. libgmsec_python.logVerbose("This is another example \"verbose\" message.") # Set logging reporting level to now allow DEBUG messages to be shown libgmsec_python.Log.setReportingLevel(libgmsec_python.logDEBUG) if (libgmsec_python.Log.getReportingLevel() == libgmsec_python.logDEBUG): libgmsec_python.logInfo("Changed reporting level to logDEBUG") else: libgmsec_python.logError( "Failed to change reporting level to logDEBUG") # The DEBUG message below will be shown successfully, unlike the last # debug message. libgmsec_python.logDebug( "This is an example debug message which should show.") libgmsec_python.logDebug("NONE reporting level, numerically, is " + str(libgmsec_python.Log.fromString("NONE"))) libgmsec_python.logDebug("ERROR reporting level, numerically, is " + str(libgmsec_python.Log.fromString("ERROR"))) libgmsec_python.logDebug("SECURE reporting level, numerically, is " + str(libgmsec_python.Log.fromString("SECURE"))) libgmsec_python.logDebug("WARNING reporting level, numerically, is " + str(libgmsec_python.Log.fromString("WARNING"))) libgmsec_python.logDebug("INFO reporting level, numerically, is " + str(libgmsec_python.Log.fromString("INFO"))) libgmsec_python.logDebug("VERBOSE reporting level, numerically, is " + str(libgmsec_python.Log.fromString("VERBOSE"))) libgmsec_python.logDebug("DEBUG reporting level, numerically, is " + str(libgmsec_python.Log.fromString("DEBUG"))) # Register general-purpose handler and test try: libgmsec_python.Log.registerHandler(anyHandler) except libgmsec_python.Exception as e: print e.what() libgmsec_python.logError("NONE reporting level, numerically, is " + str(libgmsec_python.Log.fromString("NONE"))) libgmsec_python.logError("ERROR reporting level, numerically, is " + str(libgmsec_python.Log.fromString("ERROR"))) libgmsec_python.logWarning("WARNING reporting level, numerically, is " + str(libgmsec_python.Log.fromString("WARNING"))) libgmsec_python.logInfo("INFO reporting level, numerically, is " + str(libgmsec_python.Log.fromString("INFO"))) libgmsec_python.logVerbose("VERBOSE reporting level, numerically, is " + str(libgmsec_python.Log.fromString("VERBOSE"))) libgmsec_python.logDebug("DEBUG reporting level, numerically, is " + str(libgmsec_python.Log.fromString("DEBUG"))) # Unregister log handlers libgmsec_python.Log.registerHandler(None) return 0
def main(): if(len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Since this example program uses an invalid message, we ensure the # validation check is disabled. config.addValue("gmsec-msg-content-validate-all", "false") # Ensure that the open-response is enabled # Note: Other subscribing applications should set the configuration # option 'mw-expose-resp' to 'true' in order to receive exposed replies # By setting the configuration option 'GMSEC-REQ-RESP' to 'open-resp' # here, it automatically enables the 'mw-expose-resp' option. config.addValue("GMSEC-REQ-RESP", "OPEN-RESP") # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create the ConnectionManager connMgr = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware connMgr.initialize() # Output middleware client library version libgmsec_python.logInfo(connMgr.getLibraryVersion()) # Subscribe to the bus in preparation to receive the # open-response message (Because it will not be routed # to the reqeust() call) reply_subject = OPEN_RESP_REPLY_SUBJECT + ".*" connMgr.subscribe(reply_subject) # Output information libgmsec_python.logInfo("Issuing a request using the subject '" + OPEN_RESP_REQUEST_SUBJECT + "'") # Create message requestMsg = libgmsec_python.Message(OPEN_RESP_REQUEST_SUBJECT, libgmsec_python.Message.REQUEST) # Add fields to message requestMsg.addField("QUESTION", "Is there anyone out there?") requestMsg.addField("COMPONENT", "request") # Display XML representation of request message libgmsec_python.logInfo("Sending request message:\n" + requestMsg.toXML()) # Send Request Message # Timeout periods: # -1 - Wait forever # 0 - Return immediately # >0 - Time in milliseconds before timing out replyMsg = connMgr.request(requestMsg, 1000, libgmsec_python.GMSEC_REQUEST_REPUBLISH_NEVER) # Example error handling for calling request() with a timeout if (replyMsg): # Display the XML string representation of the reply libgmsec_python.logInfo("Received replyMsg:\n" + replyMsg.toXML()) # Destroy the replyMsg message connMgr.release(replyMsg) # Disconnect from the middleware and clean up the Connection connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if(len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Since this example program uses an invalid message, we ensure the # validation check is disabled. config.addValue("gmsec-msg-content-validate-all", "false") # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object # This is the linchpin for all communications between the # GMSEC API and the middleware server connMgr = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo("Opening the connection to the middleware server") connMgr.initialize() # Output middleware client library version libgmsec_python.logInfo(connMgr.getLibraryVersion()) libgmsec_python.logInfo("Publishing two messages -- One will be received by the subscriber the other will be filtered out") # Create a message which will be received by the subscriber # in this set of example programs message = libgmsec_python.Message(EXAMPLE_MESSAGE_SUBJECT, libgmsec_python.Message.PUBLISH) populateMessage(message) # Publish the message to the middleware bus connMgr.publish(message) # Display the XML string representation of the Message for # the sake of review libgmsec_python.logInfo("Published message: " + message.toXML()) # Create a message which will NOT be received by the subscriber # in this set of example programs message = libgmsec_python.Message(FILTERED_MESSAGE_SUBJECT, libgmsec_python.Message.PUBLISH) populateMessage(message) # Publish the message to the middleware bus connMgr.publish(message) # Display the XML string representation of the Message for # the sake of review libgmsec_python.logInfo("Published message: " + message.toXML()) # Disconnect from the middleware and clean up the Connection connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object connManager = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo( "Opening the connection to the middleware server") connManager.initialize() # Output middleware client library version libgmsec_python.logInfo(connManager.getLibraryVersion()) # Create all of the GMSEC Message header Fields which will # be used by all GMSEC Messages # Note: Since these Fields contain variable values which are # based on the context in which they are used, they cannot be # automatically populated using MistMessage. definedFields = libgmsec_python.FieldList() missionField = libgmsec_python.StringField("MISSION-ID", "MISSION") # Note: SAT-ID-PHYSICAL is an optional header Field, according # to the GMSEC ISD. satIdField = libgmsec_python.StringField("SAT-ID-PHYSICAL", "SPACECRAFT") facilityField = libgmsec_python.StringField("FACILITY", "GMSEC Lab") componentField = libgmsec_python.StringField("COMPONENT", "device_message") definedFields.append(missionField) definedFields.append(satIdField) definedFields.append(facilityField) definedFields.append(componentField) # Use setStandardFields to define a set of header fields for # all messages which are created or published on the # ConnectionManager using the following functions: # createLogMessage, publishLog, createHeartbeatMessage, # startHeartbeatService, createResourceMessage, # publishResourceMessage, or startResourceMessageService connManager.setStandardFields(definedFields) paramVal = libgmsec_python.I32Field("DEVICE.1.PARAM.1.VALUE", 79) param = libgmsec_python.DeviceParam("DEV parameter 1", "parameter 1 timestamp", paramVal) device1 = libgmsec_python.Device("device 1", libgmsec_python.Device.RED) device1.setGroup("group") device1.setRole("role") device1.setModel("model") device1.setSerial("1138") device1.setVersion("1.4.5.2.3.4.5") devInfo = libgmsec_python.I16Field("info", 5) device1.setInfo(devInfo) devNum = libgmsec_python.I16Field("num", 5) device1.setNumber(devNum) device1.addParam(param) # Construct an DEV Message and add the Device values to it devMessage = libgmsec_python.DeviceMessage( DEV_MESSAGE_SUBJECT, connManager.getSpecification()) devMessage.addDevice(device1) connManager.addStandardFields(devMessage) libgmsec_python.logInfo("Publishing DEV message:\n" + devMessage.toXML()) connManager.publish(devMessage) except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(argv=None): if (len(sys.argv) <= 1): usageMessage = ("\nUsage: configfile <filename>\n") print usageMessage return -1 try: initializeLogging() # load configuration file cfgFile = libgmsec_python.ConfigFile() cfgFilename = sys.argv[1] cfgFile.load(cfgFilename) # retrieve config objects from the Config file c1 = cfgFile.lookupConfig("config1") c2 = cfgFile.lookupConfig("config2") # Display log of XML representation of Config objects libgmsec_python.logInfo("Config 1:\n" + c1.toXML()) libgmsec_python.logInfo("Config 2:\n" + c2.toXML()) # lookup subscription topic from configuration file, including excluded topics subEntry = cfgFile.lookupSubscriptionEntry("events") libgmsec_python.logInfo("Subscription pattern: " + subEntry.getPattern()) while (subEntry.hasNextExcludedPattern()): libgmsec_python.logInfo("Subscription excluded pattern: " + subEntry.nextExcludedPattern()) # lookup a Message from the configuration file message = cfgFile.lookupMessage("msg1") # Display XML representation of the message libgmsec_python.logInfo("Message:\n" + message.toXML()) # Obtain ConfigFile Iterator to examine all of the various # entries defined in the ConfigFile iterator = cfgFile.getIterator() # Acquire and display all Config entries while (iterator.hasNextConfig()): entry = iterator.nextConfig() libgmsec_python.logInfo("\nConfig Name: " + entry.getName() + "\nConfig:\n" + entry.getConfig().toXML()) # Acquire and display all Message entries while (iterator.hasNextMessage()): entry = iterator.nextMessage() libgmsec_python.logInfo("\nMessage Name: " + entry.getName() + "\nMessage:\n" + entry.getMessage().toXML()) # Acquire and display all subscription entries while (iterator.hasNextSubscription()): entry = iterator.nextSubscription() libgmsec_python.logInfo("\nSubscription Name: " + entry.getName() + "\nSubscription Topic: " + entry.getPattern()) while (entry.hasNextExcludedPattern()): libgmsec_python.logInfo("\nExcluded Pattern: " + entry.nextExcludedPattern()) # Acquire and display all custom XML entries while (iterator.hasNextCustomElement()): element = iterator.nextCustomElement() libgmsec_python.logInfo("\nCustom XML Element:\n" + element) except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) initializeLogging(config) #Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object # This is the linchpin for all communications between the # GMSEC API and the middleware server connMgr = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo( "Opening the connection to the middleware server") connMgr.initialize() # Output middleware client library version libgmsec_python.logInfo(connMgr.getLibraryVersion()) # Set up a subscription to listen for Messages with the topic # "GMSEC.TEST.PUBLISH" which are published to the middleware # bus and register the callback object to the subscription # Subscription subject wildcard syntax: # * - Matches any one token separated by periods in a subject # > - Reading left to right, matches everything up to and ONE # or more tokens in a subject # + - Reading left to right, matches everything up to and ZERO # or more tokens in a subject # For more information on wildcards, please see the GMSEC API # User's Guide libgmsec_python.logInfo("Subscribing to the topic: " + DEFAULT_SUBSCRIPTION_SUBJECT) cb = ExampleCallback() connMgr.subscribe(DEFAULT_SUBSCRIPTION_SUBJECT, cb) # Start the AutoDispatcher to begin asynchronously processing # messages connMgr.startAutoDispatch() # Because the handling of messages is occurring asynchronously # in another thread, we will need to 'busy wait' here until a # message is received while (cb.receivedMessage == 0): libgmsec_python.TimeUtil.millisleep(100) # Clean up connMgr.stopAutoDispatch() connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Since this example program uses an invalid message, we ensure the # validation check is disabled. config.addValue("gmsec-msg-content-validate-all", "false") # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Output GMSEC API version libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create the Connection connMgr = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo( "Opening the connection to the middleware server") connMgr.initialize() # Output middleware client/wrapper version libgmsec_python.logInfo(connMgr.getLibraryVersion()) connMgr.subscribe(DEFAULT_REQUEST_SUBJECT) # Call receive() to synchronously retrieve a message that has # been received by the middleware client libraries # Timeout periods: # -1 - Wait forever # 0 - Return immediately # >0 - Time in milliseconds before timing out requestMsg = connMgr.receive(-1) # Example error handling for calling receive() with a timeout if (requestMsg): # Display the XML representation of the received message libgmsec_python.logInfo("Received a message\n" + requestMsg.toXML()) # Double-check the Message type to ensure that it is a request if (requestMsg.getKind() == libgmsec_python.Message.REQUEST): # Get the name of the component who issued the request component = 0 # Construct a Reply message try: compField = requestMsg.getStringField("COMPONENT") component = compField.getValue() except Exception as e: libgmsec_python.logError(e.what()) # Set Status Code to indicate Successful Completion. # The GMSEC Interface Specification Document defines 6 # unique STATUS-CODE values: # 1 - Acknowledgement # 2 - Working/keep alive # 3 - Successful completion # 4 - Failed completion # 5 - Invalid request # 6 - Final message # If an asynchronous requestor is awaiting a reply, the # ReplyCallback in use will remain active for multiple # messages, so long as the messages it receives contain # a STATUS-CODE of either 1 or 2. status_code = "3" # Set the reply subject. # See API Interface Specificaiton Document for # more information on Reply Message subjects. # Generally speaking, they are composed # accordingly: # [Spec].[Mission].[Satellite ID]. # [Message Type].[Component Name].[Status Code] reply_subject = "GMSEC.MISSION.SAT_ID.RESP.REPLY." + status_code # Create reply message replyMsg = libgmsec_python.Message( reply_subject, libgmsec_python.Message.REPLY) # Add fields to the reply message replyMsg.addField("ANSWER", "Yup, I'm here!") replyMsg.addField("COMPONENT", component) # Display XML representation of the reply message libgmsec_python.logInfo("Prepared Reply:\n" + replyMsg.toXML()) # Send Reply connMgr.reply(requestMsg, replyMsg) # Destroy request message to release its memory connMgr.release(requestMsg) connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object connManager = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo( "Opening the connection to the middleware server") connManager.initialize() # Output middleware client library version libgmsec_python.logInfo(connManager.getLibraryVersion()) # Create all of the GMSEC Message header Fields which will # be used by all GMSEC Messages # Note: Since these Fields contain variable values which are # based on the context in which they are used, they cannot be # automatically populated using MistMessage. definedFields = libgmsec_python.FieldList() missionField = libgmsec_python.StringField("MISSION-ID", "MISSION") # Note: SAT-ID-PHYSICAL is an optional header Field, according # to the GMSEC ISD. satIdField = libgmsec_python.StringField("SAT-ID-PHYSICAL", "SPACECRAFT") facilityField = libgmsec_python.StringField("FACILITY", "GMSEC Lab") componentField = libgmsec_python.StringField("COMPONENT", "mnemonic_message") definedFields.append(missionField) definedFields.append(satIdField) definedFields.append(facilityField) definedFields.append(componentField) # Use setStandardFields to define a set of header fields for # all messages which are created or published on the # ConnectionManager using the following functions: # createLogMessage, publishLog, createHeartbeatMessage, # startHeartbeatService, createResourceMessage, # publishResourceMessage, or startResourceMessageService connManager.setStandardFields(definedFields) # Populate the Mnemonic Sample(s) mSample = libgmsec_python.MnemonicSample( "MS1", libgmsec_python.I32Field("MS1", 15)) mSample.setEUValue(libgmsec_python.F32Field("My EU", 15.0)) mSample.setFlags(1) mSample.setLimit(libgmsec_python.MnemonicSample.RED_HIGH) # Implicitly set limit enable/disable with setting of limit mSample.setQuality(True) mSample.setStalenessStatus(False) mSample.setTextValue("15") mnemonic_samples = libgmsec_python.MnemonicSampleList() mnemonic_samples.append(mSample) # Add the Mnemonic values to a Mnemonic object mnemonic = libgmsec_python.Mnemonic("M1", mnemonic_samples) statusField = libgmsec_python.I16Field("status", 5) mnemonic.setStatus(statusField) mnemonic.setUnits("units") # Build up the Schema ID -- This is used to identify the # specific type of MVAL message to construct schemaId = GMSEC_SPEC_VERSION + ".GMSEC.MSG.MVAL" # Construct an MVAL Message and add the Mnemonic values to it mvalMessage = libgmsec_python.MnemonicMessage( MVAL_MESSAGE_SUBJECT, schemaId, connManager.getSpecification()) mvalMessage.addMnemonic(mnemonic) # Add the header fields to the MVAL message connManager.addStandardFields(mvalMessage) libgmsec_python.logInfo("Publishing MVAL message:\n" + mvalMessage.toXML()) connManager.publish(mvalMessage) except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 # Load the command-line input into a GMSEC Config object # A Config object is basically a key-value pair map which is used to # pass configuration options into objects such as Connections, # ConnectionManagers, Subscribe and Publish function calls, Messages, # etc. config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # Since this example program uses an invalid message, we ensure the # validation check is disabled. config.addValue("gmsec-msg-content-validate-all", "false") # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface # This is useful for determining which version of the API is # configured within the environment libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create a ConnectionManager object # This is the linchpin for all communications between the # GMSEC API and the middleware server connMgr = libgmsec_python.ConnectionManager(config) # Open the connection to the middleware libgmsec_python.logInfo( "Opening the connection to the middleware server") connMgr.initialize() # Output middleware client library version libgmsec_python.logInfo(connMgr.getLibraryVersion()) # Create a message # Disclaimer: This message is not based off of a Message # Definition outlined by the GMSEC Interface # Specification Document (ISD). It is meant to be an example # to demonstrate the various capabilities of the GMSEC Message # and Field classes. The GMSEC Team recommends that you map # your data into the Messages defined in the GMSEC ISD, as # doing so will make your software "GMSEC Compliant" resulting # in plug-and-play type functionality with other GMSEC # compliant software. message = libgmsec_python.Message(EXAMPLE_MESSAGE_SUBJECT, libgmsec_python.Message.PUBLISH) populateMessage(message) # Publish the message to the middleware bus connMgr.publish(message) # Display the XML string representation of the Message for # the sake of review libgmsec_python.logInfo("Published message: " + message.toXML()) # Disconnect from the middleware and clean up the Connection connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0
def main(): if (len(sys.argv) <= 1): usageMessage = "usage: " + sys.argv[0] + " mw-id=<middleware ID>" print usageMessage return -1 cb = ConnectionStateCallback() # Load the command-line input into a GMSEC Config object config = libgmsec_python.Config() for arg in sys.argv[1:]: value = arg.split('=') config.addValue(value[0], value[1]) # If it was not specified in the command-line arguments, set LOGLEVEL # to 'INFO' and LOGFILE to 'stdout' to allow the program report output # on the terminal/command line initializeLogging(config) # Print the GMSEC API version number using the GMSEC Logging # interface libgmsec_python.logInfo(libgmsec_python.ConnectionManager.getAPIVersion()) try: # Create the Connection connMgr = libgmsec_python.ConnectionManager(config) # Register the event callback with the connection to catch # connection state changes, including: # 1. Connection successfully established to middleware # 2. Connection broken from middleware # 3. Reconnecting to the middleware connMgr.registerEventCallback( libgmsec_python.Connection.CONNECTION_SUCCESSFUL_EVENT, cb) connMgr.registerEventCallback( libgmsec_python.Connection.CONNECTION_BROKEN_EVENT, cb) connMgr.registerEventCallback( libgmsec_python.Connection.CONNECTION_RECONNECT_EVENT, cb) # Connect connMgr.initialize() # Output middleware version libgmsec_python.logInfo("Middleware version = " + connMgr.getLibraryVersion()) # Assuming that the user provided proper reconnection syntax # for the corresponding middleware they are using, one could # kill the middleware server at this point, then start it back # up to demonstrate the EventCallback.onEvent() function # triggering # Wait for user input to end the program libgmsec_python.logInfo( "Waiting for Connection events to occur, press <enter> to exit the program" ) raw_input("") # Clean up the ConnectionManager before exiting the program connMgr.cleanup() except libgmsec_python.Exception as e: libgmsec_python.logError(e.what()) return -1 return 0