IPWorks IoT 2020 Python Edition

Questions / Feedback?

AMQPClassic Class

Properties   Methods   Events   Configuration Settings   Errors  

An easy-to-use AMQP 0.9.1 client implementation, with support for RabbitMQ extensions.

Syntax

class ipworksiot.AMQPClassic

Remarks

The AMQPClassic class provides an easy-to-use AMQP 0.9.1 client implementation, and it also supports certain RabbitMQ extensions to the AMQP 0.9.1 specification. The class supports both plaintext and TLS-enabled connections over TCP.

Connecting

The AMQP 0.9.1 transport protocol has two layers: an overall connection between the client and server, and one or more channels running over that connection.

The class implements both layers, so the first step is to initiate the overall connection. Set the auth_scheme, user, password, ssl_enabled, and virtual_host properties if necessary, then call the connect method, passing it the server's hostname and port number. (If the server in question is not running RabbitMQ, disabling the RabbitMQCompatible configuration setting before connecting is also recommended.)

The next step is to create at least one channel, which can be accomplished by using the create_channel method. The class allows creating any number of channels, up to the limit specified by the MaxChannelCount configuration setting.

Connecting and Creating a Channel

// The examples in this documentation use a RabbitMQ server, which requires SASL Plain auth.
amqpc1.AuthScheme = AmqpclassicAuthSchemes.smSASLPlain;
amqpc1.User = "guest";
amqpc1.Password = "guest";
amqpc1.SSLEnabled = true;
amqpc1.Connect("amqpclassic.test-server.com", 5671);
amqpc1.CreateChannel("channel");

Once the class has connected to the server, and one or more channels have been opened, the class can begin manipulating exchanges and queues, publishing messages, and creating consumers.

Note that most AMQP 0.9.1 operations can themselves vary in their complexity. The examples below are intentionally simple for the sake of clarity and brevity, but links are provided for many other parts of the class's API where more detail can be found.

Declaring Exchanges

The declare_exchange method is used to declare (i.e., create, or verify the existence of) exchanges on the server. While all AMQP servers provide a default, direct-type exchange that all queues are bound to automatically (using their name as the routing key), more complex use-cases will often require creating additional exchanges of varying types.

Declaring an Exchange

// Declare a direct-type exchange.
amqpc1.DeclareExchange("channel", "MyExchange", "direct", false, false, false, false);

Exchanges can also be deleted using the delete_exchange method.

Declaring Queues

The declare_queue method is used to declare (i.e., create, or verify the existence of) queues on the server. Unlike with exchanges, the server does not provide any queues by default, so declaring a queue is always necessary (unless one has already been created by another client, or configured ahead-of-time on the server itself).

Declaring a Queue

// Declare a queue.
amqpc1.DeclareQueue("channel", "MyQueue", false, false, false, false, false);

Queues may also be deleted or purged using the delete_queue and purge_queue methods.

Binding Queues to Exchanges

The bind_queue method is used to bind a queue to an exchange. Exchanges use the information held by their queue bindings to determine which messages to forward to which queues.

Note that all AMQP 0.9.1 servers automatically bind all queues to their default exchange (which is always a direct exchange with no name) using each queue's name as the binding's routing key. This makes it easy to send a message to a specific queue without having to declare bindings; just call publish_message, pass empty string for ExchangeName, and the name of the desired queue for RoutingKey.

Binding a Queue to an Exchange

// Bind a queue to an exchange. Messages will only be delivered to the queue if their routing key is "MyRoutingKey".
amqpc1.BindQueue("channel", "MyQueue", "MyExchange", "MyRoutingKey", false);

Queues can also be unbound from exchanges using the unbind_queue method.

Publishing Messages

To publish a message, populate the Message* properties, and then call the publish_message method.

Publishing a Message

amqpc1.Message.Body = "Hello, world!";

// Publish a message to the server's default (no-name) exchange, using the name of a specific queue as the routing key.
amqpc1.PublishMessage("channel", "", "MyQueue", false, false);

// Publish a message to the "MyExchange" exchange, using the routing key "MyRoutingKey".
amqpc1.PublishMessage("channel", "MyExchange", "MyRoutingKey", false, false);

Note that outgoing messages may be handled differently by the server if the channel they are sent over is in transaction or (for RabbitMQ only) "publish confirmations" mode. Refer to the enable_transaction_mode and enable_publish_confirms methods for more information.

Receiving Messages

There are two possible ways for the class to receive a message:

  • Messages can be asynchronously pushed to the class from the server. At any point in time, the server may push a message to the class from a queue that the consume method has been used to attach a consumer to.
  • Messages can be synchronously pulled from the server by the class. The fetch_message method is used to attempt to pull (or "fetch") messages from a specific queue.

Regardless of how they are received, all incoming messages cause the ReceivedMessage* properties to be populated and the on_message_in event to fire.

Receiving a Message

// MessageIn event handler.
amqpc1.OnMessageIn += (s, e) => {
  if (e.MessageCount == -1) {
    // The server pushed a message to us asynchronously due to a consumer we created.
    Console.WriteLine("The server pushed this message to us via consumer '" + e.ConsumerTag + "':");
    Console.WriteLine(amqpc1.ReceivedMessage.Body);
  } else if (e.DeliveryTag > 0) {
    // We pulled a message from a queue with the FetchMessage() method.
    Console.WriteLine("Message successfully pulled:");
    Console.WriteLine(amqpc1.ReceivedMessage.Body);
    Console.WriteLine(e.MessageCount + " messages are still available to pull.");
  } else {
    // We tried to pull a message, but there were none available to pull.
    Console.WriteLine("No messages available to pull.");
  }
};

// Attach a consumer to "MyQueue".
amqpc1.Consume("channel", "MyQueue", "consumerTag", false, true, false, false);

// Or, try to fetch a message from "MyQueue".
amqpc1.FetchMessage("channel", "MyQueue", true);

Note that the on_message_in event always fires if fetch_message is called successfully, even if there were no messages available to fetch; refer to on_message_in for more information.

Property List


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

argument_countThe number of records in the Argument arrays.
argument_nameThe table property's name.
argument_valueThe table property's value.
argument_value_typeThe table property's value type.
auth_schemeThe authentication scheme to use when connecting.
channel_countThe number of records in the Channel arrays.
channel_acceptWhether the channel is currently accepting new messages from the server.
channel_modeWhat mode the channel is operating in.
channel_nameThe name of the channel.
channel_ready_to_sendWhether the channel is ready to send a message.
client_property_countThe number of records in the ClientProperty arrays.
client_property_nameThe table property's name.
client_property_valueThe table property's value.
client_property_value_typeThe table property's value type.
connectedTriggers a connection or disconnection.
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.
heartbeatThe heartbeat timeout value.
incoming_message_countThe number of records in the IncomingMessage arrays.
incoming_message_app_idThe Id of the application that created the message.
incoming_message_bodyThe message body.
incoming_message_channel_nameThe name of the channel the message is associated with.
incoming_message_content_encodingThe content encoding of the message's body.
incoming_message_content_typeThe content type (MIME type) of the message's body.
incoming_message_correlation_idThe correlation Id of the message.
incoming_message_delivery_modeThe delivery mode of the message.
incoming_message_expirationThe time-to-live value for this message.
incoming_message_headersHeaders associated with the message.
incoming_message_idThe unique Id of the message.
incoming_message_priorityThe priority of the message.
incoming_message_reply_toThe address to send replies to for the message.
incoming_message_timestampThe message's timestamp.
incoming_message_typeThe message's type.
incoming_message_user_idThe identity of the user responsible for producing the message.
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_app_idThe Id of the application that created the message.
message_bodyThe message body.
message_channel_nameThe name of the channel the message is associated with.
message_content_encodingThe content encoding of the message's body.
message_content_typeThe content type (MIME type) of the message's body.
message_correlation_idThe correlation Id of the message.
message_delivery_modeThe delivery mode of the message.
message_expirationThe time-to-live value for this message.
message_headersHeaders associated with the message.
message_idThe unique Id of the message.
message_priorityThe priority of the message.
message_reply_toThe address to send replies to for the message.
message_timestampThe message's timestamp.
message_typeThe message's type.
message_user_idThe identity of the user responsible for producing the message.
outgoing_message_countThe number of records in the OutgoingMessage arrays.
outgoing_message_app_idThe Id of the application that created the message.
outgoing_message_bodyThe message body.
outgoing_message_channel_nameThe name of the channel the message is associated with.
outgoing_message_content_encodingThe content encoding of the message's body.
outgoing_message_content_typeThe content type (MIME type) of the message's body.
outgoing_message_correlation_idThe correlation Id of the message.
outgoing_message_delivery_modeThe delivery mode of the message.
outgoing_message_expirationThe time-to-live value for this message.
outgoing_message_headersHeaders associated with the message.
outgoing_message_idThe unique Id of the message.
outgoing_message_priorityThe priority of the message.
outgoing_message_reply_toThe address to send replies to for the message.
outgoing_message_timestampThe message's timestamp.
outgoing_message_typeThe message's type.
outgoing_message_user_idThe identity of the user responsible for producing the message.
passwordA password to use for SASL authentication.
queue_message_countThe message count returned by various queue operations.
received_message_app_idThe Id of the application that created the message.
received_message_bodyThe message body.
received_message_channel_nameThe name of the channel the message is associated with.
received_message_content_encodingThe content encoding of the message's body.
received_message_content_typeThe content type (MIME type) of the message's body.
received_message_correlation_idThe correlation Id of the message.
received_message_delivery_modeThe delivery mode of the message.
received_message_expirationThe time-to-live value for this message.
received_message_headersHeaders associated with the message.
received_message_idThe unique Id of the message.
received_message_priorityThe priority of the message.
received_message_reply_toThe address to send replies to for the message.
received_message_timestampThe message's timestamp.
received_message_typeThe message's type.
received_message_user_idThe identity of the user responsible for producing the message.
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.
server_property_countThe number of records in the ServerProperty arrays.
server_property_nameThe table property's name.
server_property_valueThe table property's value.
server_property_value_typeThe table property's value type.
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.
virtual_hostThe virtual host to connect to.

Method List


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

bind_queueBinds a queue to an exchange.
cancel_consumeCancels an existing consumer.
close_channelCloses a channel.
commit_transactionCommits the current transaction for a channel.
configSets or retrieves a configuration setting.
connectConnects to a remote host.
consumeStarts a new consumer for a given queue.
create_channelCreates a new channel.
declare_exchangeVerifies that an exchange exists, potentially creating it if necessary.
declare_queueVerifies that a queue exists, potentially creating it if necessary.
delete_exchangeDeletes an exchange.
delete_queueDeletes a queue.
disconnectDisconnects from the remote host.
do_eventsProcesses events from the internal message queue.
enable_publish_confirmsEnables publish confirmations mode for a channel.
enable_transaction_modeEnables transaction mode for a channel.
fetch_messageAttempts to fetch a message from a given queue.
interruptInterrupt the current action and disconnects from the remote host.
publish_messagePublishes a message.
purge_queuePurges all messages from a queue.
recoverRequest that the server redeliver all messages on a given channel that have not been acknowledged.
resetReset the class.
reset_messageResets the Message properties.
rollback_transactionRolls back the current transaction for a channel.
set_channel_acceptDisables or enables message acceptance for a given channel.
set_qosRequests a specific quality of service (QoS).
unbind_queueRemoves a previously-created queue binding.

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_channel_ready_to_sendFires when a channel is ready to send messages.
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_logFires once for each log message.
on_message_inFires when a message is received; as well as when an attempt is made to fetch a message from a currently empty queue.
on_message_outFires when a message is published.
on_message_returnedFires if a previously published message is returned by the server due to it being undeliverable.
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.
ConsumerTagThe consumer tag associated with the most recently created consumer.
LocaleThe desired message locale to use.
LocalesThe message locales supported by the server.
LogLevelThe level of detail that is logged.
MaxChannelCountThe maximum number of channels.
MaxFrameSizeThe maximum frame size.
MechanismsThe authentication mechanisms supported by the server.
NackMultipleWhether negative acknowledgments should be cumulative or not.
ProtocolVersionThe AMQP protocol version to conform to.
QueueConsumerCountThe consumer count associated with the most recently created (or verified) queue.
QueueNameThe queue name associated with the most recently created (or verified) queue.
RabbitMQCompatibleWhether to operate in a mode compatible with RabbitMQ.
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]