mwasilak / txThings

CoAP library for Twisted
94 stars 43 forks source link

coap post implementation #7

Closed NTcoder closed 8 years ago

NTcoder commented 8 years ago

please help me with coap post implementation, where are the functions for coap POST.

mwasilak commented 8 years ago

Code for basic client that sends POST request:


import sys

from twisted.internet.defer import Deferred
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.python import log

import txthings.coap as coap
import txthings.resource as resource

class Agent():
    """
    Example class which performs single POST request to coap.me
    port 5683 (official IANA assigned CoAP port), URI "/large-create".
    Request is sent 1 second after initialization.
    Payload is bigger than 64 bytes, and with default settings it
    should be sent as several blocks.
    """

    def __init__(self, protocol):
        self.protocol = protocol
        reactor.callLater(1, self.putResource)

    def putResource(self):
        payload = "Riders on the storm.\nRiders on the storm.\nInto this house we're born\nInto this world we're thrown"
        request = coap.Message(code=coap.POST, payload=payload)
        request.opt.uri_path = ("large-create",)
        request.opt.content_format = coap.media_types_rev['text/plain']
        request.remote = ('134.102.218.18', coap.COAP_PORT)
        d = protocol.request(request)
        d.addCallback(self.printResponse)

    def printResponse(self, response):
        print 'Response Code: ' + coap.responses[response.code]
        print 'Payload: ' + response.payload

log.startLogging(sys.stdout)

endpoint = resource.Endpoint(None)
protocol = coap.Coap(endpoint)
client = Agent(protocol)

reactor.listenUDP(61616, protocol)
reactor.run()