예제 #1
0
파일: rd.py 프로젝트: uchiha14/txThings
    def render_GET(self, request):
        """
        Return list of endpoints matching params specified in URI query.
        """
        try:
            params = parseUriQuery(request.opt.uri_query)
        except ValueError:
            log.msg("Bad or ambiguous query options!")
            response = coap.Message(code=coap.BAD_REQUEST, payload="Bad or ambiguous query options!")
            return defer.succeed(response)
        
        ep_pattern = params.get('ep', '*')
        d_pattern = params.get('d', '*')
        et_pattern = params.get('et', '*')
        
        link_format = []
        first_entry = True
        for entry in self.directory.children.values():
            if fnmatch.fnmatch(entry.endpoint, ep_pattern) and \
                    fnmatch.fnmatch(entry.domain, d_pattern) and \
                    fnmatch.fnmatch(entry.endpoint_type, et_pattern):
                if first_entry is True:
                    first_entry = False
                else:
                    link_format.append(',')
                link_format.append('<')
                link_format.append(entry.context)
                link_format.append('>;ep="')
                link_format.append(entry.endpoint)
                link_format.append('"')

        response = coap.Message(code=coap.CONTENT, payload=''.join(link_format))
        response.opt.content_format = coap.media_types_rev['application/link-format']
        return defer.succeed(response)
예제 #2
0
 def render_GET(self,
                request):  #get a message saying wheter repeat is on or off
     if (repeatFlag == True):
         response = coap.Message(code=coap.CHANGED, payload="Repeat is on")
     else:
         response = coap.Message(code=coap.CHANGED, payload="Repeat is off")
     return (defer.succeed(response))
예제 #3
0
    def render_GET(self, request):
        """
        As soon as the get request received,
        this function is called.
        """
        info = cbor.loads(request.payload)

        # Start Request
        if info["request"] == "start":
            if not self.do_meter:
                print
                print " -- Received start request from Metering Proxy -- "
                print " Metering Agent has started metering process."
                print
                self.u3 = info["u3"]
                self.session_id = info["session_id"]
                self.update_credit_dic["session_id"] = self.session_id
                self.update_credit_dic["request"] = "start"
                self.update_credit_dic["service_name"] = self.service_name
                self.notify_used_credit()

            # Create Metering proxy response ( the first time, it is the start
            # response and further times, it also contains metered usage credit )
            # Send the response to Metering Proxy
            response = coap.Message(code=coap.CONTENT,
                                    payload=self.create_metering_response())

            self.do_meter = 1
            return defer.succeed(response)

        # Commit Request
        elif info["request"] == "commit":
            print
            print " -- Received commit request from Metering Proxy -- "
            print " Metering Agent is going to commit the measured metering token."
            print
            self.pause = True
            self.session_id = info["session_id"]
            response = coap.Message(code=coap.CONTENT,
                                    payload=self.create_commit_response())
            return defer.succeed(response)

        # Stop Request
        elif info["request"] == "stop":
            print
            print " -- Received Stop request from Metering Proxy -- "

            print
            self.session_id = info["session_id"]
            response = coap.Message(code=coap.CONTENT,
                                    payload=self.create_stop_response())
            print " Metering Agent is going to stop....."
            reactor.callLater(10, self.stop)
            return defer.succeed(response)
예제 #4
0
    def test_encode(self):
        msg1 = coap.Message(mtype=coap.CON, mid=0)
        binary1 = chr(64)+chr(0)+chr(0)+chr(0)
        self.assertEqual(msg1.encode(), binary1, "wrong encode operation for empty CON message")
        
        msg2 = coap.Message(mtype=coap.ACK, mid=0xBC90, code=coap.CONTENT, payload="temp = 22.5 C", token='q')
        msg2.opt.etag = "abcd"
        binary2 = chr(97)+chr(69)+chr(188)+chr(144)+chr(113)+chr(68)+"abcd"+chr(255)+"temp = 22.5 C"
        self.assertEqual(msg2.encode(), binary2, "wrong encode operation for ACK message with payload, and Etag option")

        msg3 = coap.Message()
        self.assertRaises(TypeError, msg3.encode)
예제 #5
0
 def render_PUT(self, request):
     global repeatFlag
     if (repeatFlag == False):  #turn on repeat
         repeatFlag = True
         response = coap.Message(code=coap.CHANGED,
                                 payload="Repeat is now enabled")
         return (defer.succeed(response))
     else:  #turn of repeat
         repeatFlag = False
         response = coap.Message(code=coap.CHANGED,
                                 payload="Repeat is now disabled")
         return (defer.succeed(response))
예제 #6
0
파일: rd.py 프로젝트: zorro2000se/haiot
    def render_GET(self, request):
        """
        Return list of resources matching params specified in URI query.
        """
        try:
            params = parseUriQuery(request.opt.uri_query)
        except ValueError:
            log.msg("Bad or ambiguous query options!")
            response = coap.Message(code=coap.BAD_REQUEST,
                                    payload="Bad or ambiguous query options!")
            return defer.succeed(response)

        #Endpoint parameters
        ep_pattern = params.get('ep', '*')
        d_pattern = params.get('d', '*')
        et_pattern = params.get('et', '*')

        #Resource parameters
        rt_pattern = params.get('rt', '*')
        title_pattern = params.get('title', '*')
        if_pattern = params.get('if', '*')

        link_format = []
        first_entry = True
        for entry in self.directory.children.values():
            if fnmatch.fnmatch(entry.endpoint, ep_pattern) and \
                    fnmatch.fnmatch(entry.domain, d_pattern) and \
                    fnmatch.fnmatch(entry.endpoint_type, et_pattern):
                for uri, params in entry.link_format.items():
                    if fnmatch.fnmatch(params.get('rt',''), rt_pattern) and \
                            fnmatch.fnmatch(params.get('title',''), title_pattern) and \
                            fnmatch.fnmatch(params.get('if',''), if_pattern):
                        if first_entry is True:
                            first_entry = False
                        else:
                            link_format.append(',')
                        link_format.append('<')
                        link_format.append(entry.context)
                        link_format.append(uri)
                        link_format.append('>')
                        for name, value in params.items():
                            link_format.append(';')
                            link_format.append(name)
                            link_format.append('="')
                            link_format.append(value)
                            link_format.append('"')

        response = coap.Message(code=coap.CONTENT,
                                payload=''.join(link_format))
        response.opt.content_format = coap.media_types_rev[
            'application/link-format']
        return defer.succeed(response)
예제 #7
0
 def render_PUT(self, request):
     global paused
     print 'PUT payload: ' + request.payload
     if (paused == False):  #if song is playing, pause it
         payload = "Music paused."
         paused = True
         response = coap.Message(code=coap.CHANGED, payload=payload)
         pygame.mixer.music.pause()
     else:  #if song is paused, resume it
         payload = "Music unpaused"
         response = coap.Message(code=coap.CHANGED, payload=payload)
         pygame.mixer.music.unpause()
     return defer.succeed(response)
예제 #8
0
 def render_PUT(self, request):
     global UNQueue
     print 'PUT payload: ' + request.payload
     payload = 'Next song: ' + request.payload
     addSong = request.payload
     for song in listOfSongs:
         if (addSong == song):  #if the song exists, put it in the queue
             UNQueue = UNQueue + (addSong + ",")
             response = coap.Message(code=coap.CHANGED, payload=payload)
             return defer.succeed(response)
         else:  #if not send error message
             response = coap.Message(
                 code=coap.CHANGED,
                 payload="There is no song containing this name")
     return defer.succeed(response)
예제 #9
0
파일: server.py 프로젝트: DarthThanatos/TIR
 def render_GET(self, request):
     payload = self.state
     print "PAYLOAD:", payload
     response = coap.Message(code=coap.CONTENT, payload=payload)
     response.opt.content_format = coap.media_types_rev[
         'application/link-format']
     return defer.succeed(response)
예제 #10
0
    def render_GET(self, request):
        """
		Respond to GET request by asking for a put instead
		"""
        payload = "Use PUT instead!"
        response = coap.Message(code=coap.CONTENT, payload=payload)
        return defer.succeed(response)
예제 #11
0
    def render_PUT(self, request):
        print 'PUT payload: ' + request.payload
        payload = request.payload
        self.color = payload
        #########################

        index = payload.find("=")
        #if not found, later
        attribute = payload[:index]
        value = payload[index + 1:]
        if attribute == "on":
            if value == "True":
                self.light.on = True
                print "Turn lamp " + self.id + " ON"
            else:
                self.light.on = False
                print "Turn lamp " + self.id + " OFF"

        elif attribute == "hue":
            self.light.hue = int(value)
            print "Set hue value lamp " + self.id + " to " + value

        elif attribute == "bri":
            self.light.bri = int(value)
            print "Set brightness value lamp " + self.id + " to " + value

        elif attribute == "sat":
            self.light.sat = int(value)
            print "Set saturation value lamp " + self.id + " to " + value

        else:
            print "Wrong query"

        response = coap.Message(code=coap.CHANGED, payload=payload)
        return defer.succeed(response)
def requestResource(protocol, command, server_ip, server_port, api_key, path,
                    payload, device_id):

    request = coap.Message(code=command)
    request.opt.uri_path = (path.split("/"))
    request.opt.observe = 0
    # api-key option
    request.opt.addOption(coap.StringOption(number=2502, value=api_key))
    # device id option
    request.opt.addOption(coap.StringOption(number=2503, value=device_id))
    # version option (reserved for future requirements)
    #    request.opt.addOption(coap.StringOption(number=2504, value="1.0"))
    print 'Remote server in ' + server_ip + ':' + str(server_port)
    ipAddress = None
    try:
        ipAddress = ip_address(server_ip)
    except Exception:
        ipAddress = ip_address(socket.gethostbyname(server_ip))
    request.remote = (ipAddress, server_port)
    if payload != None:
        request.payload = str(payload)
        request.opt.content_format = coap.media_types_rev['application/json']
    print "About to send payload: " + request.payload + " of type " + str(
        type(request.payload))
    d = protocol.request(request, observeCallback=printLaterResponse)
    d.addCallback(printResponse)
    d.addErrback(noResponse)
예제 #13
0
 def render_DELETE(self, request):
     try:
         os.remove("temperatures.txt")
     except:
         pass
     response_message = coap.Message(code=coap.CONTENT, payload="History of temperatures deleted successfully.")
     return defer.succeed(response_message)
예제 #14
0
 def render_DELETE(self, request):
     try:
         os.remove("program_output.txt")
     except:
         pass
     response_message = coap.Message(code=coap.CONTENT, payload="Program's output file deleted successfully.")
     return defer.succeed(response_message)
예제 #15
0
 def render_PUT(self, request):
     arguments = (request.payload).split(" ")
     duration = (int)(arguments[0])
     arguments.pop(0)
     response_message = coap.Message(code=coap.CONTENT, payload="Program registered and started successfully.")
     thread.start_new_thread(self.thread_function, (duration, arguments))
     return defer.succeed(response_message)
예제 #16
0
 def putResource(self, ip, payload, uri):
     request = coap.Message(code=coap.PUT, payload=payload)
     request.opt.uri_path = uri
     request.opt.content_format = coap.media_types_rev['text/plain']
     request.remote = (ip, coap.COAP_PORT)
     d = self.protocol.request(request)
     d.addCallback(self.printResponse)
예제 #17
0
    def requestResource(self):

        request = coap.Message(code=coap.GET)
        # Send request to "coap://coap.me:5683/test, raspberry 168.188.124.196"

        global result
        result = fire.get('/control_HW/ONOFF', None)

        if result == "alert":
            print 'check alert'
            request.opt.uri_path = ('counter', )
            # Danger = clientPUT.Agent(self)
            # 아직 Alert에 대한 구체적인 방안 검토 필요, 현재는 모터 회전으로 사용
        elif result == "ON" or result == "on":
            # Led on

            print "check on"
            reactor.crash()
        elif result == "OFF" or result == "off":
            # Led off
            print "check off"
        request.opt.uri_path = ('counter', )
        request.opt.observe = 0
        request.remote = (ip_address("168.188.124.196"), coap.COAP_PORT)
        d = protocol.request(request, observeCallback=self.printResponse)
        d.addCallback(self.printResponse)
        d.addErrback(self.noResponse)
예제 #18
0
 def render_GET(self, request):
     payload = "To use this resource, POST a json string like \"" + \
             "{'value': <myValue>, 'xively_api_key': '<myApiKey>'," +\
             "'xively_feed_id': '<myFeedId>'," + \
             "'xively_channel_id':'<myChannelId>'}\" to this resource."
     response = coap.Message(code=coap.CONTENT, payload=payload)
     return defer.succeed(response)
예제 #19
0
 def putRequest(self, payload = "0"):
     request = coap.Message(code=coap.PUT, payload=payload)
     request.opt.uri_path = ("led",)
     request.opt.content_format = coap.media_types_rev['text/plain']
     request.remote = ('192.168.200.128', coap.COAP_PORT)
     d = protocol.request(request)
     d.addCallback(self.printResponse)
예제 #20
0
class MsgResource(resource.CoAPResource):
    def __init__(self, disc):
        resource.CoAPResource.__init__(self)
        self.visible = True
        self.addParam(resource.LinkParam("title", "Message resource"))
        self.disc = disc

    def render_PUT(self, request):
        logg.debug('PUT payload: {0}'.format(request.payload))
        # process received device messages'
        # better create another thread to process received messages
        try:
            payload = json.loads(request.payload)
            Thread(target=self.proc_dev_msg,
                   name="CoapMsgProc_Thread",
                   args=(payload, )).start()
            payload = "Received~"
        except ValueError, err:
            # json can't be parsed
            logg.error('Value: {0}, Error:{1}'.format(request.payload,
                                                      str(err)))
            payload = "Received wrong message (no jason message)"

        # send response
        response = coap.Message(code=coap.CHANGED, payload=payload)
        return defer.succeed(response)
예제 #21
0
 def render_PUT(self, request):
     global stopIndict
     print 'STOP' + request.payload
     pygame.mixer.music.stop()
     response = coap.Message(code=coap.CHANGED, payload="Stopping music")
     stopIndict = True
     return (defer.succeed(response))
예제 #22
0
 def test_exchange(self):
     request = coap.Message(code=coap.GET)
     request.opt.uri_path = ('text', )
     request.remote = (SERVER_ADDRESS, SERVER_PORT)
     d = self.client_protocol.request(request)
     d.addCallback(self.evaluateResponse)
     return d
예제 #23
0
 def putResource(self):
     msg = {
         "Banana23": {
             "k1": "v1",
             "serial": "0",
             "kn": "vn"
         }
     }
     while self.flag:
         if self.cnt >= 5:
             time.sleep(1000);
         else:
             msg["Banana23"]["serial"] = str(self.cnt)
             logg.debug("send msg:{0}".format(msg))
             payload = json.dumps(msg)
             request = coap.Message(code=coap.PUT, payload=payload)
             request.opt.uri_path = ("messages",)
             request.opt.content_format = coap.media_types_rev['text/plain']
             request.remote = (self.ip, self.port)
             d = self.protocol.request(request)
             d.addCallback(self.printResponse)
             time.sleep(5);
         self.cnt += 1
         if self.cnt > 20:
             self.flag = False
예제 #24
0
파일: rd.py 프로젝트: zorro2000se/haiot
    def render_POST(self, request):
        """
        Add new entry to resource directory.
        """
        if request.opt.content_format is not coap.media_types_rev[
                'application/link-format']:
            log.msg('Unsupported content-format!')
            response = coap.Message(code=coap.UNSUPPORTED_CONTENT_FORMAT,
                                    payload='')
            return defer.succeed(response)
        try:
            params = parseUriQuery(request.opt.uri_query)
        except ValueError:
            log.msg("Bad or ambiguous query options!")
            response = coap.Message(code=coap.BAD_REQUEST,
                                    payload="Bad or ambiguous query options!")
            return defer.succeed(response)

        if 'ep' not in params:
            log.msg("No 'ep' query option in request.")
            response = coap.Message(code=coap.BAD_REQUEST,
                                    payload="No 'ep' query option in request.")
            return defer.succeed(response)
        endpoint = params['ep']

        if endpoint in self.directory:
            del self.children[self.directory[endpoint]]
        else:
            self.directory[endpoint] = str(self.eid)
            self.eid += 1

        link_format = link_header.parse_link_value(request.payload)
        domain = params.get('d', '')
        endpoint_type = params.get('et', '')
        lifetime = params.get('lt', DEFAULT_LIFETIME)
        context = params.get(
            'con',
            'coap://' + request.remote[0] + ":" + str(request.remote[1]))

        entry = DirectoryEntryResource(self, link_format, endpoint, domain,
                                       endpoint_type, lifetime, context)
        self.putChild(self.directory[endpoint], entry)
        response = coap.Message(code=coap.CREATED, payload='')
        response.opt.location_path = ('rd', self.directory[endpoint])
        log.msg("RD entry added: endpoint=%s, lifetime=%d" %
                (endpoint, lifetime))
        return defer.succeed(response)
예제 #25
0
파일: clientPUT.py 프로젝트: pmtoan/CoAP
 def putResource(self):
     payload = "CoAP Client say hello to server"
     request = coap.Message(code=coap.PUT, payload=payload)
     request.opt.uri_path = (str(coap_resoure),)
     request.opt.content_format = coap.media_types_rev['text/plain']
     request.remote = (coap_server, coap.COAP_PORT)
     d = protocol.request(request)
     d.addCallback(self.printResponse)
예제 #26
0
 def render_GET(self, request):
     data = []
     self.root.generateResourceList(data, "")
     payload = ",".join(data)
     print payload
     response = coap.Message(code=coap.CONTENT, payload=payload)
     response.opt.content_format = coap.media_types_rev['application/link-format']
     return defer.succeed(response)
예제 #27
0
파일: rd.py 프로젝트: uchiha14/txThings
 def render_DELETE(self, request):
     """
     Delete this resource directory entry.
     """
     log.msg("RD entry deleted: endpoint=%s" % self.endpoint)
     self.removeResource()
     response = coap.Message(code=coap.DELETED, payload='')
     return defer.succeed(response)
예제 #28
0
 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.PUT, payload=payload)
     request.opt.uri_path = ("large-update", )
     request.opt.content_format = coap.media_types_rev['text/plain']
     request.remote = ('198.41.30.241', coap.COAP_PORT)
     d = protocol.request(request)
     d.addCallback(self.printResponse)
 def requestResource(self):
     request = coap.Message(code=coap.GET)
     request.opt.uri_path = (self.uri,)
     request.opt.observe = 0
     request.remote = (self.host, self.port)
     d = protocol.request(request, observeCallback=self.processLaterResponse)
     d.addCallback(self.processResponse)
     d.addErrback(self.noResponse)
 def requestResource3(self):
     request = coap.Message(code=coap.GET)
     request.opt.uri_path = ('sensor3',)
     request.opt.observe = 1
     request.remote = (self.remote_hst, 5684)
     d = protocol.request(request, observeCallback=self.processLaterResponse)
     d.addCallback(self.processResponse)
     d.addErrback(self.noResponse)