def __init__(self, ipAddress='', server_address='/tmp/borderAgent'): # initialize the parent class threading.Thread.__init__(self) self.mote_list = {} self.bridge_ip = '' # open self.coap = coap.coap(ipAddress=ipAddress) self.nbrResource = nbrResource(notify=self.setBridgeIp) # install resource self.coap.addResource(self.nbrResource) # Make sure the socket does not already exist try: os.unlink(server_address) except OSError: if os.path.exists(server_address): raise # Create a UDS socket self.socket_handler = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) # Bind the socket to the port log.info('starting up on %s' % server_address) self.socket_handler.bind(server_address) self.active = True self.start()
def twoEndPoints(request): # start two coap endpoints coap1 = coap.coap(ipAddress=IPADDRESS1,testing=True) coap2 = coap.coap(ipAddress=IPADDRESS2,testing=True) # create new resource newResource = dummyResource() # install resource on coap1 coap1.addResource(newResource) f = lambda : twoEndPointsTeardown(coap1,coap2) request.addfinalizer(f) return (coap1,coap2)
def twoEndPoints(request): # start two coap endpoints coap1 = coap.coap(ipAddress=IPADDRESS1, testing=True) coap2 = coap.coap(ipAddress=IPADDRESS2, testing=True) # create new resource newResource = dummyResource() # install resource on coap1 coap1.addResource(newResource) f = lambda: twoEndPointsTeardown(coap1, coap2) request.addfinalizer(f) return (coap1, coap2)
def _receiveFromMesh(self, sender, signal, data): ''' Receive packet from the mesh destined for JRC's CoAP server. Forwards the packet to the virtual CoAP server running in test mode (PyDispatcher). ''' sender = openvisualizer.openvisualizer_utils.formatIPv6Addr(data[0]) # FIXME pass source port within the signal and open coap client at this port self.coapClient = coap.coap(ipAddress=sender, udpPort=d.DEFAULT_UDP_PORT, testing=True, receiveCallback=self._receiveFromCoAP) self.coapClient.socketUdp.sendUdp(destIp='', destPort=d.DEFAULT_UDP_PORT, msg=data[1]) # low level forward of the CoAP message return True
def create_coap(self): if self.coap: self.coap.close() while True: try: self.coap = coap.coap(udpPort=self.get_random_port()) except: time.sleep(1) else: break
def coap_post(mote, conf = True): print "running post on mote " + str(mote) + " with confirmable " + str(conf) c = coap.coap() mote_ip = MOTE_IP_BASE + str(mote) p = c.POST('coap://[{0}]/l'.format(mote_ip), payload = [ord('C')], confirmable=conf ) print "done" print ''.join([chr(b) for b in p]) c.close() return p
def coap_get(mote, conf = True): print "running get on mote " + str(mote) + " with confirmable " + str(conf) c = coap.coap() mote_ip = MOTE_IP_BASE + str(mote) p = c.GET('coap://[{0}]/rt'.format(mote_ip), confirmable=conf ) print "done" print ''.join([chr(b) for b in p]) c.close() return p
def twoEndPoints(request): # start two coap endpoints coap1 = coap.coap(ipAddress=IPADDRESS1, testing=True) coap2 = coap.coap(ipAddress=IPADDRESS2, testing=True) # create new resource newResource = dummyResource() if request.param == True: # if testing with security, protect the resource with security context context = oscoap.SecurityContext(masterSecret=OSCOAPMASTERSECRET, senderID=OSCOAPCLIENTID, recipientID=OSCOAPSERVERID) # add resource - context binding with authorized methods newResource.addSecurityBinding((context, d.METHOD_ALL)) # install resource on coap1 coap1.addResource(newResource) f = lambda: twoEndPointsTeardown(coap1, coap2) request.addfinalizer(f) return (coap1, coap2, request.param)
def _receiveFromMesh(self, sender, signal, data): ''' Receive packet from the mesh destined for JRC's CoAP server. Forwards the packet to the virtual CoAP server running in test mode (PyDispatcher). ''' sender = openvisualizer.openvisualizer_utils.formatIPv6Addr(data[0]) # FIXME pass source port within the signal and open coap client at this port self.coapClient = coap.coap(ipAddress=sender, udpPort=d.DEFAULT_UDP_PORT, testing=True, receiveCallback=self._receiveFromCoAP) self.coapClient.socketUdp.sendUdp( destIp='', destPort=d.DEFAULT_UDP_PORT, msg=data[1]) # low level forward of the CoAP message return True
def __init__(self, app, websrv, roverMode): ''' :param app: OpenVisualizerApp :param websrv: Web server ''' log.info('Creating OpenVisualizerWeb') # store params self.app = app self.engine = SimEngine.SimEngine() self.websrv = websrv self.roverMode = roverMode # command support Cmd.__init__(self) self.doc_header = 'Commands (type "help all" or "help <topic>"):' self.prompt = '> ' self.intro = '\nOpenVisualizer (type "help" for commands)' #used for remote motes : if roverMode: self.roverMotes = {} self.client = coap.coap() self.client.respTimeout = 2 self.client.ackTimeout = 2 self.client.maxRetransmit = 1 self._defineRoutes() # To find page templates bottle.TEMPLATE_PATH.append('{0}/web_files/templates/'.format( self.app.datadir)) # initialize parent class eventBusClient.eventBusClient.__init__( self, name='OpenVisualizerWeb', registrations=[], ) # Set DAGroots imported if app.DAGrootList: #Wait the end of the mote threads creation time.sleep(1) for moteid in app.DAGrootList: self._showMoteview(moteid) self._getMoteData(moteid) self._toggleDAGroot(moteid)
def __init__(self): #=== singleton pattern start === if self._init: return self._init = True #=== singleton pattern stop === # local variables self.dataLock = threading.RLock() self.coap = coap.coap() self.busy = False self.statusBusy = False self._status = '' self.statusStart = None self.period = None
def sendMsgToMote(ipv6ip_mote, msg, mote_to_fwd_to_addr=None): c = coap.coap() payload = [] for ch in msg: payload.append(ord(ch)) if mote_to_fwd_to_addr is not None: for ipByte in ipv6ToHexArray(mote_to_fwd_to_addr): payload.append(ipByte) print "PUTting " + msg + " to mote " + str(ipv6ip_mote) p = c.PUT('coap://[{0}]/rt'.format(ipv6ip_mote), payload = payload, confirmable = True) c.close() return p
def __init__(self,app,websrv): ''' :param app: OpenVisualizerApp :param websrv: Web server ''' log.info('Creating OpenVisualizerWeb') # store params self.app = app self.engine = SimEngine.SimEngine() self.websrv = websrv # command support Cmd.__init__(self) self.doc_header = 'Commands (type "help all" or "help <topic>"):' self.prompt = '> ' self.intro = '\nOpenVisualizer (type "help" for commands)' #used for remote motes : self.roverMotes = {} self.client = coap.coap(udpPort=9000) self.client.respTimeout = 2 self.client.ackTimeout = 2 self.client.maxRetransmit = 1 self._defineRoutes() # To find page templates bottle.TEMPLATE_PATH.append('{0}/web_files/templates/'.format(self.app.datadir)) # initialize parent class eventBusClient.eventBusClient.__init__( self, name = 'OpenVisualizerWeb', registrations = [], ) # Set DAGroots imported if app.DAGrootList: #Wait the end of the mote threads creation time.sleep(1) for moteid in app.DAGrootList: self._showMoteview(moteid) self._getMoteData(moteid) self._toggleDAGroot(moteid)
def __init__(self, coapResource, contextHandler=None): # log log.info("create instance") self.coapResource = coapResource # run CoAP server in testing mode # this mode does not open a real socket, rather uses PyDispatcher for sending/receiving messages # We interface this mode with OpenVisualizer to run JRC co-located with the DAG root self.coapServer = coap.coap(udpPort=d.DEFAULT_UDP_PORT, testing=True) self.coapServer.addResource(coapResource) #self.coapServer.addSecurityContextHandler(contextHandler) self.coapServer.maxRetransmit = 1 self.coapClient = None self.dagRootEui64 = None # store params # initialize parent class eventBusClient.eventBusClient.__init__( self, name='JRC', registrations=[ { 'sender': self.WILDCARD, 'signal': 'getL2SecurityKey', 'callback': self._getL2SecurityKey_notif, }, { 'sender': self.WILDCARD, 'signal': 'registerDagRoot', 'callback': self._registerDagRoot_notif }, { 'sender': self.WILDCARD, 'signal': 'unregisterDagRoot', 'callback': self._unregisterDagRoot_notif }, ] ) # local variables self.stateLock = threading.Lock()
def __init__(self, coapResource, contextHandler=None): # log log.info("create instance") self.coapResource = coapResource # run CoAP server in testing mode # this mode does not open a real socket, rather uses PyDispatcher for sending/receiving messages # We interface this mode with OpenVisualizer to run JRC co-located with the DAG root self.coapServer = coap.coap(udpPort=d.DEFAULT_UDP_PORT, testing=True) self.coapServer.addResource(coapResource) self.coapServer.addSecurityContextHandler(contextHandler) self.coapServer.maxRetransmit = 1 self.coapClient = None self.dagRootEui64 = None # store params # initialize parent class eventBusClient.eventBusClient.__init__( self, name='JRC', registrations=[ { 'sender': self.WILDCARD, 'signal': 'getL2SecurityKey', 'callback': self._getL2SecurityKey_notif, }, { 'sender': self.WILDCARD, 'signal': 'registerDagRoot', 'callback': self._registerDagRoot_notif }, { 'sender': self.WILDCARD, 'signal': 'unregisterDagRoot', 'callback': self._unregisterDagRoot_notif }, ]) # local variables self.stateLock = threading.Lock()
import os import sys here = sys.path[0] print here sys.path.insert(0, os.path.join(here, '..', '..', '..', '..', '..', '..', 'coap')) from coap import coap MOTE_IP = 'bbbb::1415:92cc:0:2' c = coap.coap() # read status of debug LED p = c.GET('coap://[{0}]/l'.format(MOTE_IP)) print chr(p[0]) # toggle debug LED p = c.PUT( 'coap://[{0}]/l'.format(MOTE_IP), payload=[ord('2')], ) # read status of debug LED p = c.GET('coap://[{0}]/l'.format(MOTE_IP)) print chr(p[0]) raw_input("Done. Press enter to close.")
here = sys.path[0] sys.path.insert(0, os.path.join(here, '..')) import time import binascii from coap import coap from coap import coapOption as o from coap import coapObjectSecurity as oscoap import logging_setup SERVER_IP = '::1' # open c = coap.coap(udpPort=5000) context = oscoap.SecurityContext( masterSecret=binascii.unhexlify('000102030405060708090A0B0C0D0E0F'), senderID=binascii.unhexlify('636c69656e74'), recipientID=binascii.unhexlify('736572766572'), aeadAlgorithm=oscoap.AES_CCM_16_64_128()) objectSecurity = o.ObjectSecurity(context=context) try: # retrieve value of 'test' resource p = c.GET('coap://[{0}]/test'.format(SERVER_IP), confirmable=True, options=[objectSecurity])
import os import sys here = sys.path[0] print here sys.path.insert(0,os.path.join(here,'..','..','..','..','..','..','coap')) from coap import coap MOTE_IP = 'bbbb::1415:92cc:0:2' UDPPORT = 61618 # can't be the port used in OV c = coap.coap(udpPort=UDPPORT) # read status of debug LED p = c.GET('coap://[{0}]/l'.format(MOTE_IP)) print chr(p[0]) # toggle debug LED p = c.PUT( 'coap://[{0}]/l'.format(MOTE_IP), payload = [ord('2')], ) # read status of debug LED p = c.GET('coap://[{0}]/l'.format(MOTE_IP)) print chr(p[0]) raw_input("Done. Press enter to close.")
def __init__(self, eui): super(WhisperCoapSender, self).__init__() self.eui = eui self.UDP_PORT = 61619 self.socket = coap.coap(udpPort=self.UDP_PORT) self.running = True
import os import sys here = sys.path[0] sys.path.insert(0, os.path.join(here,'..')) import time from coap import coap import logging_setup SERVER_IP = '::1' # open c = coap.coap(udpPort=5000) # retrieve value of 'test' resource p = c.GET('coap://[{0}]/test'.format(SERVER_IP),) print '=====' print ''.join([chr(b) for b in p]) print '=====' # close c.close() time.sleep(0.500) raw_input("Done. Press enter to close.")
mote = motes_ip['front_light'] result = cmd_sw_config(coap, mote, args[1::]) return result elif cmd == 'back': #fish jar control mote = motes_ip['back_light'] result = cmd_sw_config(coap, mote, args[1::]) return result elif cmd == 'exit': return -1 return 0 if __name__ == '__main__': # open c = coap.coap(udpPort=5683) context = oscoap.SecurityContext( masterSecret=binascii.unhexlify('000102030405060708090A0B0C0D0E0F'), senderID=binascii.unhexlify('636c69656e74'), recipientID=binascii.unhexlify('736572766572'), aeadAlgorithm=oscoap.AES_CCM_16_64_128()) objectSecurity = o.ObjectSecurity(context=context) while True: raw_in = input('mote#') args = raw_in.split() result = cmd_parser(c, args) print("cmd exec result: %d" % result) if result < 0:
def __init__(self, name, ipv6): super(Motes, self).__init__(name, measurements='environment') self._ipv6 = ipv6 self._conn = coap.coap()
import os import sys here = sys.path[0] print here sys.path.insert(0,os.path.join(here,'..','..','..','..','..','..','coap')) from coap import coap MOTE_IP = 'bbbb::1415:92cc:0:2' c = coap.coap() # read the information about the board status p = c.GET('coap://[{0}]/rt'.format(MOTE_IP)) print ''.join([chr(b) for b in p]) raw_input("Done. Press enter to close.")
# initialize parent class coapResource.coapResource.__init__( self, path = 'test', ) def GET(self,options=[]): print 'GET received' respCode = d.COAP_RC_2_05_CONTENT respOptions = [] respPayload = [ord(b) for b in 'dummy response'] return (respCode,respOptions,respPayload) # open c = coap.coap(ipAddress='::1') # install resource c.addResource(testResource()) for t in threading.enumerate(): print t.name # let the server run raw_input('\n\nServer running. Press Enter to close.\n\n') # close c.close()
path='test', ) def GET(self, options=[]): print 'GET received' respCode = d.COAP_RC_2_05_CONTENT respOptions = [] respPayload = [ord(b) for b in 'hello world 1 2 3 4 5 6 7 8 9 0'] return (respCode, respOptions, respPayload) # open c = coap.coap(ipAddress='::1') testResource = testResource() context = oscoap.SecurityContext( masterSecret=binascii.unhexlify('000102030405060708090A0B0C0D0E0F'), senderID=binascii.unhexlify('736572766572'), recipientID=binascii.unhexlify('636c69656e74'), aeadAlgorithm=oscoap.AES_CCM_16_64_128()) # add resource - context binding with authorized methods testResource.addSecurityBinding((context, d.METHOD_ALL)) # install resource c.addResource(testResource)
"endASN": end_asn, "diff": end_asn - start_asn, "numDesync": numDesync, "myRank": myrank, "tx": tx, "txACK": txACK, "packetSequence": packet_sequence, "lastSuccessLeft": last_success_left, "errorCounter": error_counter } import json # r = requests.post('http://140.124.184.204:8080/Cloud/WSN/Insert', data=json.dumps(data), ) # # cursor.close() # cnx.close() except: print "oops" print "Unexpected error:", sys.exc_info()[0] print "---------------------------------------------------------" respCode = coapDefines.COAP_RC_2_01_CREATED respOptions = [] respPayload = [] return (respCode, respOptions, respPayload) # coap_server = coap.coap(udpPort=UDP_PORT) # coap_server.addResource(exResource())