55 - firmwareapi/pycom/network/coap.md
66 - chapter/firmwareapi/pycom/network/coap
77---
8- This module implements a CoAp Server and Client, operating as both at the same time .
8+ This module implements a CoAp Server and Client.
99
1010## Usage Example of CoAp Server
1111
@@ -15,26 +15,11 @@ from network import WLAN
1515from network import Coap
1616import _thread
1717
18- # Callback to be called when a new resource has been added via PUT
19- def new_resource_callback (new_resource ):
20- details = new_resource.get_details()
21- print (" New resource has been created!" )
22- print (" URI: {} " .format(details[0 ]))
23- print (" Mediatype: {} " .format(details[1 ]))
24- print (" Max Age: {} " .format(details[2 ]))
25- print (" ETAG: {} " .format(details[3 ]))
26- print (" ETAG value: {} " .format(details[4 ]))
27- print (" Value: {} " .format(new_resource.value()))
28- # Configure the properties of the new resource
29- new_resource.set_details(mediatype = Coap.MEDIATYPE_TEXT_PLAIN , max_age = 132 , etag = True )
30-
3118# Thread handling the CoAp Server
3219def coap_thread ():
3320 while True :
34- # Call Coap.read() without specyfing timeout value, in this way it handles all requests sent to the CoAp Server silently
3521 Coap.read()
3622
37-
3823# Connect to the network
3924wlan = WLAN(mode = WLAN .STA )
4025wlan.connect(' your-ssid' , auth = (WLAN .WPA2 , ' your-key' ))
@@ -44,26 +29,17 @@ Coap.init(str(wlan.ifconfig()[0]), service_discovery=True, dynamic_resources=Tru
4429# Register callback which will be called when new resource is added via PUT
4530Coap.register_new_resource_handler(new_resource_callback)
4631
47- # Add a resource with default value and plain text content format
32+ # Add an example resource with URI "resource1" and value "default_value" and content format "plain text"
4833r = Coap.add_resource(" resource1" , media_type = Coap.MEDIATYPE_TEXT_PLAIN , value = " default_value" )
49- # Add an attribute to the resource
50- r.add_attribute(" title" , " resource1" )
51- # Add an attribute to the resource
52- r.add_attribute(" ct" , str (Coap.MEDIATYPE_TEXT_PLAIN ))
5334# Configure the possible operations on the resource
5435r.callback(Coap.REQUEST_GET | Coap.REQUEST_POST | Coap.REQUEST_PUT , True )
5536
56- # Add a resource without default value, XML content format and E-Tag enabled
57- r = Coap.add_resource(" resource2" , media_type = Coap.MEDIATYPE_APP_XML , etag = True )
58- # Configure the possible operations on the resource
59- r.callback(Coap.REQUEST_GET | Coap.REQUEST_POST | Coap.REQUEST_PUT | Coap.REQUEST_DELETE , True )
60-
6137# Start a new thread which handles the CoAp Server
6238_thread.start_new_thread(coap_thread, ())
6339
6440```
6541
66- ## Usage Example of CoAp Client in blocking mode
42+ ## Usage Example of CoAp Client
6743
6844``` python
6945
@@ -83,110 +59,29 @@ def response_callback(code, id_param, type_param, token, payload):
8359# Thread handling the sockets
8460def coap_thread ():
8561 while True :
86- # Using Coap.read() without timeout value means that if no new packet arrives to any of the client sessions registered before this is called, then this function will never return
8762 Coap.read()
8863
89-
9064# Connect to the network
9165wlan = WLAN(mode = WLAN .STA )
9266wlan.connect(' your-ssid' , auth = (WLAN .WPA2 , ' your-key' ))
9367
9468# Initialize Coap module
95- Coap.init(str (wlan.ifconfig()[0 ]), service_discovery = True )
69+ Coap.init(str (wlan.ifconfig()[0 ]))
9670
9771# Register the response handler for the requests the module initiates as a Coap Client
9872Coap.register_response_handler(response_callback)
73+ # Create a new Client Session to use to communicate with the CoAp Server
74+ session = Coap.new_client_session(" server-ip-address" )
9975
100- # As the Coap.read() will be called in a form that it blocks until no new data arrives to the socket, it is only safe
101- # to create new client sessions before Coap.read() is called
102- session = Coap.new_client_session(" 192.168.0.234" , 5683 )
103-
104- # Start a new thread which calls Coap.read() which will block until no new packet arrives to the socket
76+ # Start a new thread which calls Coap.read() to handle incoming requests
10577_thread.start_new_thread(coap_thread, ())
10678
107- # After this point it is not safe to create new Coap Client Session as they might not be handled by Coap.read()
108-
109- # Request to a normal CoAp Server
110- id = session.send_request(Coap.REQUEST_GET , uri_path = " .well-known/core" , payload = " payload" , token = " token1" , include_options = True )
111- print (id )
112- # Request to a normal CoAp Server
113- id = session.send_request(Coap.REQUEST_GET , uri_path = " time" , payload = " payload" , token = " token2" , include_options = True )
114- print (id )
115- # Request to a normal CoAp Server
116- id = session.send_request(Coap.REQUEST_PUT , uri_path = " time" ,content_format = Coap.MEDIATYPE_TEXT_PLAIN , payload = " ABCD" , token = " token3" , include_options = True )
117- print (id )
118- # Request to a Dish Telemetry server, payload is the AMQP message, token is maximum 8 bytes containing the IMEI or IMSI id, no options should be present
119- imei = int (' 359738090028145' ).to_bytes(8 , ' big' )
120- id = session.send_request(Coap.REQUEST_GET , payload = " amqp://artemis:5672/dish.app1.FjhBV78.telemetry" , token = imei, include_options = False )
79+ # Send a GET Request to the CoAp Server asking for all resources via URI ".well-known/core"
80+ id = session.send_request(Coap.REQUEST_GET , uri_path = " .well-known/core" )
12181print (id )
12282
12383```
12484
125- ## Usage Example of CoAp Client in non-blocking mode
126-
127- ``` python
128-
129- from network import WLAN
130- from network import Coap
131- import _thread
132-
133- # Callback handling the responses to the requests sent to a Coap Server
134- def response_callback (code , id_param , type_param , token , payload ):
135- print (" Code: {} " .format(code))
136- # The ID can be used to pair the requests with the responses
137- print (" ID: {} " .format(id_param))
138- print (" Type: {} " .format(type_param))
139- print (" Token: {} " .format(token))
140- print (" Payload: {} " .format(payload))
141-
142- # Thread handling the sockets
143- def coap_thread ():
144- while True :
145- # Wait only 3 seconds for new packets then return back
146- # In the next call it will also handle any new CoAp Client Sessions created during the previous call
147- Coap.read(3000 )
148-
149-
150- # Connect to the network
151- wlan = WLAN(mode = WLAN .STA )
152- wlan.connect(' your-ssid' , auth = (WLAN .WPA2 , ' your-key' ))
153-
154- # Initialize Coap module, to be used only as a CoAp Client
155- Coap.init()
156-
157- # Start a new thread which handles the CoAp, it is safe to start as soon as possible as the Coap.read() has timeout specified
158- # After this point it is safe to create new CoAp Client Sessions, it will be processed by the coap_thread correctly as Coap.read() is used with timeout value
159- _thread.start_new_thread(coap_thread, ())
160-
161- # Register the response handler for the requests the module initiates as a Coap Client
162- Coap.register_response_handler(response_callback)
163-
164- # Create a new client session on demand
165- session1 = Coap.new_client_session(" 192.168.0.234" , 5683 )
166-
167- # Request to a normal CoAp Server via CoAp Client Session: session1
168- id = session1.send_request(Coap.REQUEST_GET , uri_path = " .well-known/core" , token = " session1" )
169- print (id )
170- # Request to a normal CoAp Server via CoAp Client Session: session1
171- id = session1.send_request(Coap.REQUEST_GET , uri_path = " time" , token = " session1" )
172- print (id )
173-
174- # Create again a new CoAp Client Session on demand, without restriction
175- session2 = Coap.new_client_session(" 192.168.0.236" , 5683 )
176-
177- # Request to a normal CoAp server via CoAp Client Session: session2
178- id = session2.send_request(Coap.REQUEST_GET , uri_path = " .well-known/core" )
179- print (id )
180- # Request to a normal CoAp server via CoAp Client Session: session2
181- id = session2.send_request(Coap.REQUEST_GET , uri_path = " resource1" )
182- print (id )
183- # Request to a normal CoAp server via CoAp Client Session: session2
184- id = session2.send_request(Coap.REQUEST_POST , uri_path = " resource1" , payload = " new_value" )
185- print (id )
186-
187- ```
188-
189-
19085## Initialization
19186
19287#### Coap.init(address, * , port=5683, service_discovery=False, dynamic_resources=False)
0 commit comments