0.1.3 • Published 6 years ago

xsc-adapter v0.1.3

Weekly downloads
-
License
MIT
Repository
-
Last release
6 years ago

XSC_Adapters

XSC_Adapters is a project of the University of Stuttgart to implement custom adapters for the XSC project. This project enables different connectors of machines to communicate with clients.

Capabilities

Capabilities are provided by machines. These can be things like reading the machine status, getting the current location of some machine part, or moving the part to a certain location. Capabilities have different attributes for us, that are described here:

Cyclic

Non-cyclic capabilities are capabilities that are executed once per call. For example, moving a machine part to a certain location or getting the machine state just once. The results of non-cyclic capabilities are sent as replies in a ReqRep-scheme.

A cyclic capability is one that is repeatedly called. For example, reading the machine state every second. The results of cyclic capabilities are sent via PubSub.

Multicast

Multicast capabilities are only interesting for cyclic capabilities. Non-multicast capabilities get an extra topic for every call. Although they use PubSub for sending results, they will only have one subscriber on each topic. This is useful when the result of a capability is time dependent. For example, the machine state can be read every millisecond and we call it at exactly 0 ms after the last second (x.000) and we want to read it every second. The second call wants to read the machine state every second as well but the call was started half a second later (x.500). The result of the first and the second call will be different, thus two different topics.

Multicast capabilities use one topic for every call. So, in the same example, the second caller would simply get the same result as the first caller.

Connector

A connector is a piece of software that provides capabilities like reading a state from a machine. Connectors are implemented by extending the ConnectorAdapter-class.

Implementation

To implement a Connector, please extend the ConnectorAdapter class exported by the package itself. Please also override the methods executeOneTimeCapability(capabilityId, commandRequest) and executeCyclicCapability(capabilityId, commandRequest, topic). The former is for non-cyclic capabilities and should return the result of the capability. The latter is for cyclic capabilities (both, multicast and non-multicast) and should return some kind of confirmation message that is sent to the client. Results of cyclic capabilities should be published on the set topic.

You also have to override the method stopCyclicCapability(capability, topic). This is called when no more subscribers exist for a cyclic message.

Client

A client is a piece of software that uses capabilities of connectors. Clients are implemented by extending the ClientAdapter-class.

Implementation

To implement a client, please extend the ClientAdapter class exported by the package itself. Please also override the method selectFromAmbiguousCapabilities(caps). It is called when there are multiple capabilities to choose from and the adapter cannot choose by itself. The returned value is the index of the chosen capability.

Functionality

XSC uses ZeroMQ to communicate between different components of the system. There are three possible components: Connector, Client, and Agent. The first two are described above, the last one is not yet published. It is a central component for each part of the system.

The client or connector establishes a connection with its local agent. All communication is routed by the agent.

API

Adapter

This class is the parent class of both ClientAdapter and ConnectorAdapter. Its methods or Fields are available in the derived classes.

Method or FieldDescription
void startAdapter() throws XSCErrorThis method starts the initiation after the adapter initialization. Includes initiateConnectionToAgent(), startHeartbeat() and startServices() method calls. Has to be called in the adapter child constructor.
void initiateConnectionToAgent() throws XSCErrorInitiates a connection to the local agent. If not specified otherwise in the capabilities.json, a protobuf message of type DISCOVERY (see Transfer Protocol) is send to localhost on port 31000. Includes buildGreeting(), to first generate the GREETING protobuf message and set up a secure connection. buildDiscoveryMessageBody is called before the message is build and published. Sets all fields based on the response.
XSCMessage buildGreeting(String secret) throws XSCSecurityErrorGenerates the protobuf GREETING message (see Transfer Protocol). Has to be called in initiateConnectionToAgent().
void startHeartbeat()This method starts a dedicated heartbeat server, which runs in background and answers Heartbeat Requests. The request are handled in handleHeartbeat()
XSCMessage handleHeartbeat(message)Replies to a heartbeat request by the local agent to ensure this adapter is still available. Sends a protobuf message of type ACK (see Transfer Protocol) REQ/REP initiated by the Discovery component. MessageID and Timestamp in the reply equal their request counterparts.
Number getMsgId()Returns a unique integer, which is used as message id.
Source getOwnSource()Builds a source object based on the adapter IP & UUID (see Transfer Protocol).
Destination getLocalAgentDestination()Builds a destination object based on the agent IP & UUID (see Transfer Protocol).
boolean validateMessage(XSCMessage message) throws XSCSecurityErrorChecks if the returned GREETING_RESPONSE is valid.
XSCMessage buildDiscoveryMessage() throws XSCErrorDefines the message body of the initial discovery message. Specialized method is implemented in ClientAdapter and ConnectorAdapter. Client: Register as CLIENT - Connector: Register as CONNECTOR with all local capabilities
void startServices() throws XSCErrorThis method has to be implemented in the adapter child classes. It starts child-specific services. Client: capability update server. - Connector: command request server.
boolean storePorts(List ports)This method has to be implemented in the adapter child classes. It stores child-specific ports assigned by the local agent. Client: one port for the capability updater server. - Connector: one port for the command request server and one port for the cyclic command response publisher. Both adapter types need another port for the heartbeat server.

ClientAdapter

This class is not completely implemented, methods whose implementation is missing are marked as abstract.

Method or FieldDescription
boolean isValidIndex(int index, int listSize)Check if a user return int is a valid index for a given list length.
XSCMessage handleCapUpdates(XSCMessage message)Passes a CLIENT_UPDATE message to the update() method of ClientCapabilities and returns a ACK message.
Routing convertParameterListToRouting(String capabilityName, List parameters)Generates a Routing object based on all applying routing parameters. Used in extractRoutingParameters().
XSCMessage buildCommandRequest(String capabilityName, GeneratedMessageV3 msg, Destination dest) throws XSCInputError, XSCCommandError, SecurityErrorMethod to generate basic COMMAND_REQUEST with elements needed in all requests. Uses extractRoutingParameters().
List getMatchingValuedCapabilities(List capabilities, GeneratedMessageV3 msg)Creates a list of Capability holding all capabilities whose routing parameters match a given protobuf message. Instead of holding the regex of a routing parameter field, it holds the value of the given protobuf message field. Uses createMatchedParameter(). Used in extractRoutingParameters().
CapabilityParameter createMatchedParameter(CapabilityParameter param, GeneratedMessageV3 msg) throws ErrorCreates a CapabilityParameter if this routing parameter regex matches a protobuf message. Instead of holding the regex of a routing parameter field, it holds the value of the given protobuf message field. Exception thrown if parameter does not match. Used in createMatchedParameter().
RoutingAndDestination extractRoutingParameters(String capabilityName, GeneratedMessageV3 msg, Destination dest) throws XSCInputError, XSCCommandError, SecurityErrorPuts all to use routing parameters and the IP and UUID of the target connector into one object. Uses getMatchingValuedCapabilities(), convertParameterListToRouting(), getSelectedCapability(), createDestination() and ClientCapabilities getActiveCapabilities().
CapabilityIdentification getSelectedCapability(List matchedCaps, Destination dest) throws XSCInputError, SecurityErrorSends a CAPABILITY_SELECTION to the local agent to get the IP & UUID of the connector providing a capability. Then provides the list to the user to choose a element. Choosing is done by providing the index of the element, to prevent returning made up data. Used selectFromAmbiguousCapabilities()and isValidIndex().
String deserialize(ProtobufMessage msg, String position)Tries to get a string value of a given field of a protobuf message. Position is in format protobuf-field-number(.protobuf-field-number)*.
List getCapabilities()Returns a list containing all active capabilities.
Set getTopics()Returns a set with all currently subscribed to topics.
Destination createDestination(String ip, String uuid)Creates a Destination object with given IP and UUID.
void subscribe(Response resp, Consumer callback) throws XSCInputErrorSubscribes to a topic included in the response object and performs the Callback on any incoming message. Puts the topic in the topicMap.
void unsubscribe() throws SecurityError, XSCInputErrorEither takes a String or response object as input parameter. Unsubscribes of a given topic and sends a message to the local agent to inform the ConnectorAdapter to decrease the subscriber counter.
()=>Response createResponseCallable(XSCMessage msg) throws XSCError, SecurityErrorGenerates a response object from the internal transfer message. Used in callCapability().
XSCMessage callCapability(capabilityName, message, encryptedBodyOrEncryptor, destOrIpOrUndefined, uuidOrUndefined) throws XSCError, SecurityErrorTakes a String (capability name or id) and a protobuf version 3 message as base input parameters. Can additionally take two Strings or a Destination object consisting of IP and UUID of the target connector and a ByteString or Lamda function returning a ByteString to use in the message body instead of the actual message as input parameters. Calls a connector capability in the network via local agent. Creates a protobuf message of type COMMANDREQUEST, which is then send to the local agent. encryptedBodyOrEncryptor is either the encrypted body that is sent in the message, a function to feed the serialized message into to get the encrypted body, or null/undefined if you want to send the unencrypted message. If destOrIpOrUndefined is undefined, automatic routing is used, else, the given destination or IP is used. With the IP, the UUID from the last parameter is used. Uses createResponseCallable().
abstract int selectFromAmbiguousCapabilities(final List capabilities)Gets a list containing matched capabilities and their providing connector. Has to be user implemented, should return the index of the chosen capability.

ConnectorAdapter

This class is not completely implemented, methods whose implementation is missing are marked as abstract.

Method or FieldDescription
Connector getCapabilitiesFromJsonFile() throws XSCErrorThis method reads the machine connector's capabilities of the configuration JSON file, which was provided at start up. Objects are parsed and put into registry objects. Used in buildDiscoveryMessage().
XSCMessage handleCommand(XSCMessage request)This method handles incoming CommandRequests and forwards them to the actual connector and returns the corresponding CommandResponse to the Client. The capability is checked for cyclic and multicast attributes. If it is neither, executeOneTimeCapability is called. If it is cyclic but not multicast or both but not yet in active topics, executeCyclicCapability is called with a newly generated topic. Topics are generated as "/XSC/{originating_client_ip}/{originating_client_uuid}/{message_id}/{capability_name}". If it is cyclic and multicast and already in active topics, the corresponding topic is returned to the client.
XSCMessage handleUnsubscribe(XSCMessage unsubscription)Passes the topic to TopicList's unsubscribe() method and in case it returns true (no more active subscribers), publishes a UNSUBSCRIBE message on the given topic as initiative for agents to unsubscribe. After the message is published, calls stopCyclicCapability() and returns either way ACK message.
Capability matchCapabilityPerConnector(XSCMessage commandRequest)This method maps the called capability to an available local capability. The first matching capability is returned, assuming there cannot be a second one. Returns a registry capability. Only calls CapabilityUtil's matchCapabilityPerConnector().
void publish(ByteString byteString, String topic)This method publishes cyclic CommandResponses to a defined topic. It is called by the Connector when a new message has to be published to the subscribed client(s).
abstract ByteString executeOneTimeCapability(String capabilityId, ByteString commandRequest) throws ErrorHas to be implemented in a class that extends ConnectorAdapter. Receives the call to execute a specified one-time capability, which then should trigger the usage of this capability. Can throw the parsing error of protobuf messages, which will result in the client receiving a XSCCommandException.
abstract ByteString executeCyclicCapability(String capabilityId, ByteString commandRequest, String topic) throws ErrorHas to be implemented in a class that extends ConnectorAdapter. Receives the call to execute a specified cyclic or multicast capability, which then should trigger the usage of this capability. Can throw the parsing error of protobuf messages, which will result in the client receiving a XSCCommandException.
abstract void stopCyclicCapability(Capability capability, String topic)Has to be implemented in a class that extends ConnectorAdapter. Is called if all subscribes have unsubscribed a topic. Should trigger the end of the task currently publishing on the given topic to save resources.

Configuration

This configuration file specifies all data adapters should provide. An sample file with additional descriptions is given below. The configuration is only important for ConnectorAdapters.

{
    "Agent": {
        "IP": "localhost",
        "UUID": "-"
    },
    "Protocol": "ADS",
    "Name": "Beckhoff Walze K350a Halle 3",
    "IP": "localhost",
    "Description": "<Description>",
    "Capabilities": [
        {
            "Name": "connect",
            "Cyclic": false,
            "Description": "establishes connection an ADS device",
            "Multicast": false,
            "Parameters": [
                {
                    "Field": "1",
                    "RegEx": "[1-9][0-9]{0-2}.[0-9]{1-3}.[0-9]{1-3}.[0-9]{1-3}.[0-9]{1-3}.[0-9]{1-3}"
                }
            ]
        },
        {
            "Name": "disconnect",
            "Cyclic": true,
            "Description": "severs a running connection to a specified ADS device",
            "Multicast": false,
            "Parameters": [
                {
                    "Field": "2.4",
                    "RegEx": "[1-9][0-9]{0-2}.[0-9]{1-3}.[0-9]{1-3}.[0-9]{1-3}.[0-9]{1-3}.[0-9]{1-3}"
                }
            ]
        },
        {
            "Name": "setInfeedSpeed",
            "Cyclic": true,
            "Description": "defines the speed with which materials are pulled in",
            "Multicast": true,
            "Parameters": [
                {
                    "Field": "3.1.5",
                    "RegEx": "0.[01][0-9]"
                }
            ]
        }
    ]
}
  • Agent: - IP: The network address of the agent which will act as local agent. Is an IPv4 address or default value of localhost - UUID: The identifier of the agent which will act as local agent
  • Protocol: The underlying protocol of the machine connector, which can help to identify a machine connector
  • Name: Freely chosen string
  • IP: The network address of the adapter. Is an IPv4 address or default value of localhost
  • Description: Describes the connector/the machine it is connected to
  • Capabilities: Array of Capability, which includes all provided capabilities. These capabilities need to be implemented by a developer in a class, which extends the ConnectorAdapter
  • Capability: A single provided capability consisting of the following variables: - Name: The string name, which clients (in a implementation of ClientAdapter) use to call and execute a capability - Cyclic: True, if the capability is cyclic and can be subscribed to - Description: Capability string description - Multicast: True, if the capability can be subscribed to by multiple clients on the same topic (non-time-relevant) - Parameters: Array of Parameter, which includes all parameters which should act as routing parameter. - Parameter: - Field: Position/index in the external Protobuf message - RegEx: String regular expression description of valid values

Warning

This library is a beta version. We do not claim error free (or mostly error free) functionality.

0.1.3

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago

0.0.11

6 years ago

0.0.10

6 years ago

0.0.9

6 years ago

0.0.8

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.1

6 years ago