Home

Awesome

SwiftCoAP

Updated for Swift 4.2

NEW: Download the Client-Implementation myCoAP for iOS/watchOS which builds upon this library: AppStore-Link

This project is an implementation of the "Constrained Application Protocol" (CoAP - RFC 7252) in Swift. It is intended for Clients and Servers. This implementation provides the standard CoAP features (including Caching) along with the extensions:

A short manual is provided below. Feedback is highly appreciated!

Want an Objective-C implementation? Checkout iCoAP.

Getting Started

###The Files:

###The Code

This section gives you an impression on how to use the provided data structures.

SCMessage

SCMessage represents a CoAP message in SwiftCoAP. You can initialize a message with help of the designated initializer as follows: SCMessage(). Alternatively, SCMessage provides a convenience initializer (convenience init(code: SCCodeValue, type: SCType, payload: NSData?)) that lets you create an instance the following way:

SCMessage(code: SCCodeValue(classValue: 0, detailValue: 01)!, type: .Confirmable, payload: "test".dataUsingEncoding(NSUTF8StringEncoding))

SCClient

This class represents a CoAP client, which can be initialized with the given designated initializer: init(delegate: SCClientDelegate?).

Properties

You can modify the following properties of an SCClient object to alter its behavior:

Send a message by calling the method sendCoAPMessage(message: SCMessage, hostName: String, port: UInt16) and implement the provided SCClientDelegate protocol to receive callbacks. This should be it.

Example
let m = SCMessage(code: SCCodeValue(classValue: 0, detailValue: 01), type: .Confirmable, payload: "test".dataUsingEncoding(NSUTF8StringEncoding))
m.addOption(SCOption.UriPath.rawValue, data: "test".dataUsingEncoding(NSUTF8StringEncoding)!)
let coapClient = SCClient(delegate: self)
coapClient.sendCoAPMessage(m, hostName: "coap.me", port: 5683)
Other Methods
HTTP-Proxying

The class SCClient gives you the opportunity to send a message as HTTP via a proxy. Just add the following line after initiating an SCClientobject:

coapClient.httpProxyingData = ("localhost", 5683)

The Options of the CoAP-Message are sent in the HTTP-Header. It is required that the Proxy returns the CoAP-Type in the Header of HTTP-Response as well. The respective Header-Field is COAP_TYPE. The Request-URI has the following Format: http://proxyHost:proxyPort/coapHost:coapPort An Example: Sending your message to the CoAP-Server coap.me with the Port 5683 via a HTTP-Proxy located at localhost:9292, lets the SwiftCoAP library compose the follwoing Request-URI: http://localhost:9292/coap.me:5683

Custom Transport Layer Functionality

SCClient encapsulates the CoAP transport layer functionality into a separate object which implements the SCCoAPTransportLayerProtocol protocol. SCClient uses the provided SCCoAPUDPTransportLayer class by default, which uses UDP. However, if you want to replace it with your own class just do the following steps:

An (real) example where using a custom transport layer functionality would be helpful: You cannot use UDP, e.g. when you bring this library to WatchOS 2. As UDP communcation is not available on this OS you can use WatchConnectiviy as transport layer object for your SCClient and let the iPhone execute the UDP sendings.

SCServer

This class represents a CoAP server, which can be initialized with the standard designated initializer init(). The given convenience initializer init?(port: UInt16) initializes a server instance and automatically starts listening on the given port. This initialization can fail if a UDP-socket error occurs.

Properties

You can modify the following properties of an SCServer object to alter its behavior:

Methods

Resource representation SCResourceModel

SwiftCoAP provides the base class SCResourceModel to represent a CoAP resource in the server implementation. To create your own resources with custom behavior, you just have to subclass SCResourceModel. You must use the designated initializer init(name: String, allowedRoutes: UInt) which requires you to set the name and the routes (GET, POST, PUT, DELETE) which you want to support (see explanation below).

Resource properties

SCResourceModel has the following properties which can be modified/set on initialization:

Resource methods

The following methods are used for data reception of your allowed routes. SCServer will call the appropriate message upon the reception of a reqeuest. Override the respective methods, which match your allowedRoutes.

SCServer passes a queryDictionary containing the URI query content (e.g ["user_id": "23"]) and all options contained in the respective request. The POST and PUT methods provide the message's payload as well. Please, refer to the example resources in the SwiftCoAPServerExample project for implementation examples.

The following methods require data for the given routes GET, POST, PUT, DELETE and must be overriden if needed. If you return nil, the server will respond with a Method not allowed error code (Make sure that you have set the allowed routes in the allowedRoutes bitmask property). You have to return a tuple with a statuscode, optional payload, optional content format for your provided payload and (in case of POST and PUT) an optional locationURI.

Server with Resources Example
let server = SCServer(port: 5683)
        
let resource = TestResourceModel(name: "test", allowedRoutes: SCAllowedRoute.Get.rawValue | SCAllowedRoute.Post.rawValue | SCAllowedRoute.Put.rawValue | SCAllowedRoute.Delete.rawValue, 
text: "This is a very long description text, I hope that all of you will like it")

server?.resources.append(resource)
server?.delegate = self

Don't hesitate to contact me if something is unclear!

Examples:

Make sure to take a look at the examples, which show the library in action. Let me know if you have questions, or other issues.

Used Libraries:

This version uses the public domain licensed CocoaAsyncSocket library for UDP-socket networking. Click here for more information.