IPWorks IoT 2020 Python Edition

Questions / Feedback?

AMQP Class

Properties   Methods   Events   Configuration Settings   Errors  

An easy-to-use AMQP 1.0 client implementation.

Syntax

class ipworksiot.AMQP

Remarks

The AMQP class provides an easy-to-use AMQP 1.0 client implementation. The class supports both plaintext and TLS-enabled connections over TCP.

Connecting

AMQP 1.0's transport protocol has three layers: an overarching connection between two containers, the sessions opened on that connection, and the links (between the containers' nodes) attached to those sessions.

The class implements all three layers of the AMQP 1.0 transport protocol, so the first step is to initiate the overall connection. Set the container_id property and call the connect method, passing it the server's hostname and port number.

Once connected, the next step is to create at least one session, which can be accomplished by using the create_session method. The class allows creating any number of sessions, up to the limit specified by the MaxSessionCount configuration setting.

Connecting and Creating a Session

amqp1.ContainerId = "testClient";
amqp1.Connect("amqp.test-server.com", 5672);
amqp1.CreateSession("TestSession");

After creating a session, the next step is to create one or more links (which are created in the context of a session) so that messages can be sent and/or received. Links are unidirectional, so each one has a sender on one end and a receiver on the other.

The class can function both as a sender node (by opening sender links) and as a receiver node (by opening receiver links). But keep in mind that, since the class is implemented as an AMQP 1.0 client, it must be the one to open links (said another way, the class cannot accept any link requests made by other peers).

As with sessions, the class allows creating any number of links for each session, up to the limit specified by the MaxLinkCountPerSession configuration setting.

Creating Sender Links

To create a sender link, call the create_sender_link method, passing it the name of an existing session, a unique name for the link, and (if necessary in your environment) the name of a target for the receiver to use to ensure messages are routed correctly.

The on_link_ready_to_send event will fire when the newly created sender link is ready to send messages.

Creating a Sender Link

amqp1.OnLinkReadyToSend += (s, e) => {
  Console.WriteLine("Link '" + e.LinkName + "' is ready to send messages!");
};

amqp1.CreateSenderLink("TestSession", "TestSenderLink", "TestTarget");

Sending Messages

To send a message, the first step is to set the Message* properties to the desired values.

At minimum, the message_value and message_value_type properties must be set. All other properties are optional, though specifying a unique value for message_id is recommended. (If the GenerateMessageId configuration setting is enabled, the class will generate one automatically when the message is sent.)

Once the Message* properties have be assigned as desired, call the send_message method, passing it the name of an existing sender link on which the message should be sent.

The on_message_out event will be fired when the message has been sent (and acknowledged, if message_settled was set to false). The on_message_outcome event may also fire, if necessary, once the receiver reports the outcome of the message.

Refer to send_message, on_message_out, and on_message_outcome for more information.

Sending a Message

amqp1.OnMessageOut += (s, e) => {
  Console.WriteLine("Message with Id '" + e.MessageId + "' has been sent on link '" + e.LinkName + "'.");
};

amqp1.Message.MessageId = "TestMessageId";
amqp1.Message.Value = "Hello, world!";
amqp1.Message.ValueType = AMQPValueTypes.mvtString;

amqp1.SendMessage("TestSenderLink");

The reset_message method can be used to reset the Message* properties to their default values.

Sending Composite AMQP Data

The AMQP 1.0 protocol's data model includes the concept of "composite data". Composite data is comprised of one or more type-value pairs (including data structure types), plus a descriptor that describes what the overall data represents.

The class supports sending composite AMQP data in a message through the use of JSON with a well-defined schema. Refer to the send_message method's documentation for more information and examples.

Creating Receiver Links

Receiver links can operate in one of two receive modes: automatic, where the class will work to ensure that messages are received as soon as they are available; and fetch-based, where the class will only "fetch" a new message when explicitly instructed to.

The receive_mode property controls which receive mode newly-created receiver links will use; refer to its documentation for more information.

After ensuring that receive_mode is set as desired, call create_receiver_link, passing it the name of an existing session, a unique name for the link, and (if necessary in your environment) the name of a source for the sender to route the link creation request to.

Creating a Receiver Link

// Creating an automatic receiver link.
amqp1.ReceiveMode = AmqpReceiveModes.rmAutomatic;
amqp1.CreateReceiverLink("TestSession", "TestAutoReceiverLink", "TestSource1");

// Creating a fetch-based receiver link.
amqp1.ReceiveMode = AmqpReceiveModes.rmFetch;
amqp1.CreateReceiverLink("TestSession", "TestFetchReceiverLink", "TestSource2");

Receiving Messages

For receiver links created in automatic receive mode (the default), messages are received automatically.

For receiver links created in fetch-based mode, the class will attempt to "fetch" a message each time the fetch_message method is called (optionally timing out after a time, if fetch_timeout is non-zero). When calling fetch_message, pass it the name of a fetch-based receiver link.

Regardless of whether a messages is received automatically or fetched, any incoming message will cause the class to fire the on_message_in event and update the ReceivedMessage* properties.

When the on_message_in event fires, its State event parameter can be used to specify the outcome of the message, which the class will then transmit back to the sender (as well as self-report by firing the on_message_outcome event). Refer to on_message_in for more information.

Receiving a Message

// For automatic receiver links, only the event handler is necessary.
amqp1.OnMessageIn += (s, e) => {
  Console.WriteLine("Message with Id '" + e.MessageId + "' has been received on link '" + e.LinkName + "'. Value:");
  Console.WriteLine(amqp1.ReceivedMessage.Value);

  // The message state is already set to the "Accepted" outcome by default, but we'll set it again
  // for the purpose of this example.
  e.State = 0; // 0 = Accepted.
};

// For fetch-based links, it's also necessary to call FetchMessage(). It is recommended that the
// FetchTimeout property be set to a non-zero value (60 seconds is the default) so that the fetch
// request will eventually time out if the sender doesn't have any messages available to deliver.
amqp1.FetchTimeout = 60;
amqp1.FetchMessage("TestFetchReceiverLink");

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

auth_schemeThe authentication scheme to use when connecting.
connectedTriggers a connection or disconnection.
container_idThe container Id the class should advertise when connecting.
fetch_timeoutHow long the class should wait for a message to be received after FetchMessage is called.
firewall_auto_detectThis property tells the class whether or not to automatically detect and use firewall system settings, if available.
firewall_typeThis property determines the type of firewall to connect through.
firewall_hostThis property contains the name or IP address of firewall (optional).
firewall_passwordThis property contains a password if authentication is to be used when connecting through the firewall.
firewall_portThis property contains the TCP port for the firewall Host .
firewall_userThis property contains a user name if authentication is to be used connecting through a firewall.
idle_timeoutThe maximum period of inactivity the class will allow before disconnecting.
incoming_message_countThe number of records in the IncomingMessage arrays.
incoming_message_absolute_expiry_timeThe absolute time at which this message should be considered expired.
incoming_message_content_encodingThe content encoding of this message's data.
incoming_message_content_typeThe content type of this message's data.
incoming_message_correlation_idThe correlation Id of this message.
incoming_message_creation_timeThe creation time of this message.
incoming_message_delivery_countHow many previous attempts there have been to deliver this message.
incoming_message_durableWhether this message is durable.
incoming_message_first_acquirerWhether this message may have been acquired by other links previously.
incoming_message_group_idThe Id of the group this message belongs to.
incoming_message_group_sequenceThe position of this message within its group.
incoming_message_link_nameThe name of the link this message is associated with.
incoming_message_idThe unique Id of this message.
incoming_message_priorityThe priority of this message.
incoming_message_reply_toThe address of the node to send replies to for this message.
incoming_message_reply_to_group_idThe Id of the group to send replies to for this message.
incoming_message_settledWhether this message is settled.
incoming_message_subjectThe subject of this message.
incoming_message_toThe address of the node which this message is intended for.
incoming_message_ttlThe time-to-live value for this message.
incoming_message_user_idThe identity of the user responsible for producing this message.
incoming_message_valueThis message's value.
incoming_message_value_typeThis message's value data type.
link_countThe number of records in the Link arrays.
link_availableThe number of messages which this link's sender could send if it had credit for them.
link_channel_nameThe channel name this link is using.
link_creditThe amount of credit currently available to this link's sender.
link_delivery_countThe current delivery count value for this link.
link_nameThis link's name.
link_ready_to_sendWhether this link is ready to send a message.
link_receive_modeThe receive mode this link is operating in.
link_roleThe class's role on this link.
local_hostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
local_portThe TCP port in the local host where the class binds.
message_absolute_expiry_timeThe absolute time at which this message should be considered expired.
message_content_encodingThe content encoding of this message's data.
message_content_typeThe content type of this message's data.
message_correlation_idThe correlation Id of this message.
message_creation_timeThe creation time of this message.
message_delivery_countHow many previous attempts there have been to deliver this message.
message_durableWhether this message is durable.
message_first_acquirerWhether this message may have been acquired by other links previously.
message_group_idThe Id of the group this message belongs to.
message_group_sequenceThe position of this message within its group.
message_link_nameThe name of the link this message is associated with.
message_idThe unique Id of this message.
message_priorityThe priority of this message.
message_reply_toThe address of the node to send replies to for this message.
message_reply_to_group_idThe Id of the group to send replies to for this message.
message_settledWhether this message is settled.
message_subjectThe subject of this message.
message_toThe address of the node which this message is intended for.
message_ttlThe time-to-live value for this message.
message_user_idThe identity of the user responsible for producing this message.
message_valueThis message's value.
message_value_typeThis message's value data type.
outgoing_message_countThe number of records in the OutgoingMessage arrays.
outgoing_message_absolute_expiry_timeThe absolute time at which this message should be considered expired.
outgoing_message_content_encodingThe content encoding of this message's data.
outgoing_message_content_typeThe content type of this message's data.
outgoing_message_correlation_idThe correlation Id of this message.
outgoing_message_creation_timeThe creation time of this message.
outgoing_message_delivery_countHow many previous attempts there have been to deliver this message.
outgoing_message_durableWhether this message is durable.
outgoing_message_first_acquirerWhether this message may have been acquired by other links previously.
outgoing_message_group_idThe Id of the group this message belongs to.
outgoing_message_group_sequenceThe position of this message within its group.
outgoing_message_link_nameThe name of the link this message is associated with.
outgoing_message_idThe unique Id of this message.
outgoing_message_priorityThe priority of this message.
outgoing_message_reply_toThe address of the node to send replies to for this message.
outgoing_message_reply_to_group_idThe Id of the group to send replies to for this message.
outgoing_message_settledWhether this message is settled.
outgoing_message_subjectThe subject of this message.
outgoing_message_toThe address of the node which this message is intended for.
outgoing_message_ttlThe time-to-live value for this message.
outgoing_message_user_idThe identity of the user responsible for producing this message.
outgoing_message_valueThis message's value.
outgoing_message_value_typeThis message's value data type.
passwordA password to use for SASL authentication.
ready_to_sendIndicates whether the class is ready to send data.
received_message_absolute_expiry_timeThe absolute time at which this message should be considered expired.
received_message_content_encodingThe content encoding of this message's data.
received_message_content_typeThe content type of this message's data.
received_message_correlation_idThe correlation Id of this message.
received_message_creation_timeThe creation time of this message.
received_message_delivery_countHow many previous attempts there have been to deliver this message.
received_message_durableWhether this message is durable.
received_message_first_acquirerWhether this message may have been acquired by other links previously.
received_message_group_idThe Id of the group this message belongs to.
received_message_group_sequenceThe position of this message within its group.
received_message_link_nameThe name of the link this message is associated with.
received_message_idThe unique Id of this message.
received_message_priorityThe priority of this message.
received_message_reply_toThe address of the node to send replies to for this message.
received_message_reply_to_group_idThe Id of the group to send replies to for this message.
received_message_settledWhether this message is settled.
received_message_subjectThe subject of this message.
received_message_toThe address of the node which this message is intended for.
received_message_ttlThe time-to-live value for this message.
received_message_user_idThe identity of the user responsible for producing this message.
received_message_valueThis message's value.
received_message_value_typeThis message's value data type.
receive_modeControls what mode new receiver links are created with.
remote_hostThe address of the remote host. Domain names are resolved to IP addresses.
remote_portThe port of the AQMP server (default is 5672). The default port for SSL is 5671.
session_countThe number of records in the Session arrays.
session_incoming_windowThe incoming window size of this session.
session_nameThe name of this session.
session_outgoing_windowThe outgoing window size of this session.
ssl_accept_server_cert_encodedThe certificate (PEM/base64 encoded).
ssl_cert_encodedThe certificate (PEM/base64 encoded).
ssl_cert_storeThe name of the certificate store for the client certificate.
ssl_cert_store_passwordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
ssl_cert_store_typeThe type of certificate store for this certificate.
ssl_cert_subjectThe subject of the certificate used for client authentication.
ssl_enabledWhether TLS/SSL is enabled.
ssl_server_cert_encodedThe certificate (PEM/base64 encoded).
timeoutA timeout for the class.
userA username to use for SASL authentication.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

close_linkCloses a link.
close_sessionCloses a session.
configSets or retrieves a configuration setting.
connectConnects to a remote host.
create_receiver_linkCreates a new receiver link with the given name on the specified session.
create_sender_linkCreates a new sender link with the given name on the specified session.
create_sessionCreates a new session with the given name.
disconnectDisconnects from the remote host.
do_eventsProcesses events from the internal message queue.
fetch_messageFetches a single message over the specified receiver link.
interruptInterrupts the current action.
resetReset the class.
reset_messageResets the Message properties.
send_messageSends a message on the specified link.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

on_connectedFired immediately after a connection completes (or fails).
on_connection_statusFired to indicate changes in connection state.
on_disconnectedFired when a connection is closed.
on_errorInformation about errors during data delivery.
on_link_ready_to_sendFires when a sender link is ready to send messages.
on_logFires once for each log message.
on_message_inFires when the class receives a message.
on_message_outFires when the class sends a message.
on_message_outcomeFires when a message's outcome is available.
on_ssl_server_authenticationFired after the server presents its certificate to the client.
on_ssl_statusShows the progress of the secure connection.

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

AuthorizationIdentityThe value to use as the authorization identity when SASL authentication is used.
DefaultCreditThe amount of credit to create new receiver links with.
DefaultCreditThresholdThe credit threshold to create new receiver links with.
DefaultIncomingWindowThe incoming window size to create new sessions with.
DefaultOutgoingWindowThe outgoing window size to create new sessions with.
DefaultSenderSettleModeThe sender settle mode to create new links with.
GenerateMessageIdWhether a unique message Id should be automatically generated when sending a message.
LogLevelThe level of detail that is logged.
MaxFrameSizeThe maximum frame size.
MaxLinkCountPerSessionThe maximum number of links to restrict new sessions to.
MaxMessageSizeThe maximum message size to restrict new links to.
MaxSessionCountThe maximum number of sessions.
ModifiedDeliveryFailedWhether the sender should treat this transfer as an unsuccessful delivery attempt.
ModifiedMessageAnnotationsThe message annotations that the sender should merge into those already on the message.
ModifiedUndeliverableHereWhether the receiver has indicated that the sender should not attempt to redeliver the message.
ProtocolVersionThe AMQP protocol version to conform to.
RejectErrorConditionThe error condition included with a 'Rejected' delivery outcome.
RejectErrorDescriptionThe error description included with a 'Rejected' delivery outcome.
SenderSettleMode[LinkName]Retrieves the negotiated sender settle mode for the specified link.
SimplifiedJSONFormatWhether to output simplified JSON where possible.
ConnectionTimeoutSets a separate timeout value for establishing a connection.
FirewallAutoDetectTells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallHostName or IP address of firewall (optional).
FirewallPasswordPassword to be used if authentication is to be used when connecting through the firewall.
FirewallPortThe TCP port for the FirewallHost;.
FirewallTypeDetermines the type of firewall to connect through.
FirewallUserA user name if authentication is to be used connecting through a firewall.
KeepAliveIntervalThe retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received.
KeepAliveTimeThe inactivity time in milliseconds before a TCP keep-alive packet is sent.
LingerWhen set to True, connections are terminated gracefully.
LingerTimeTime in seconds to have the connection linger.
LocalHostThe name of the local host through which connections are initiated or accepted.
LocalPortThe port in the local host where the class binds.
MaxLineLengthThe maximum amount of data to accumulate when no EOL is found.
MaxTransferRateThe transfer rate limit in bytes per second.
ProxyExceptionsListA semicolon separated list of hosts and IPs to bypass when using a proxy.
TCPKeepAliveDetermines whether or not the keep alive socket option is enabled.
TcpNoDelayWhether or not to delay when sending packets.
UseIPv6Whether to use IPv6.
LogSSLPacketsControls whether SSL packets are logged when using the internal security API.
OpenSSLCADirThe path to a directory containing CA certificates.
OpenSSLCAFileName of the file containing the list of CA's trusted by your application.
OpenSSLCipherListA string that controls the ciphers to be used by SSL.
OpenSSLPrngSeedDataThe data to seed the pseudo random number generator (PRNG).
ReuseSSLSessionDetermines if the SSL session is reused.
SSLCACertFilePathsThe paths to CA certificate files on Unix/Linux.
SSLCACertsA newline separated list of CA certificate to use during SSL client authentication.
SSLCheckCRLWhether to check the Certificate Revocation List for the server certificate.
SSLCipherStrengthThe minimum cipher strength used for bulk encryption.
SSLEnabledCipherSuitesThe cipher suite to be used in an SSL negotiation.
SSLEnabledProtocolsUsed to enable/disable the supported security protocols.
SSLEnableRenegotiationWhether the renegotiation_info SSL extension is supported.
SSLIncludeCertChainWhether the entire certificate chain is included in the SSLServerAuthentication event.
SSLNegotiatedCipherReturns the negotiated ciphersuite.
SSLNegotiatedCipherStrengthReturns the negotiated ciphersuite strength.
SSLNegotiatedCipherSuiteReturns the negotiated ciphersuite.
SSLNegotiatedKeyExchangeReturns the negotiated key exchange algorithm.
SSLNegotiatedKeyExchangeStrengthReturns the negotiated key exchange algorithm strength.
SSLNegotiatedVersionReturns the negotiated protocol version.
SSLProviderThe name of the security provider to use.
SSLSecurityFlagsFlags that control certificate verification.
SSLServerCACertsA newline separated list of CA certificate to use during SSL server certificate validation.
TLS12SignatureAlgorithmsDefines the allowed TLS 1.2 signature algorithms when UseInternalSecurityAPI is True.
TLS12SupportedGroupsThe supported groups for ECC.
TLS13KeyShareGroupsThe groups for which to pregenerate key shares.
TLS13SignatureAlgorithmsThe allowed certificate signature algorithms.
TLS13SupportedGroupsThe supported groups for (EC)DHE key exchange.
AbsoluteTimeoutDetermines whether timeouts are inactivity timeouts or absolute timeouts.
FirewallDataUsed to send extra data to the firewall.
InBufferSizeThe size in bytes of the incoming queue of the socket.
OutBufferSizeThe size in bytes of the outgoing queue of the socket.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks IoT 2020 Python Edition - Version 20.0 [Build 8265]