- \
- $if title: : $title\
-
-
-
-
-
-
-
-
+$def with (title=None)
+
+
+
+ \
+ $if title: : $title\
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/software/openEndPoint/bin/EpUdpRawCli/EpUdpRawCli.py b/software/openEndPoint/bin/EpUdpRawCli/EpUdpRawCli.py
index 4c89f9b0a..127bcaf75 100644
--- a/software/openEndPoint/bin/EpUdpRawCli/EpUdpRawCli.py
+++ b/software/openEndPoint/bin/EpUdpRawCli/EpUdpRawCli.py
@@ -1,86 +1,86 @@
-import os
-import sys
-if __name__=='__main__':
- cur_path = sys.path[0]
- sys.path.insert(0, os.path.join(cur_path, '..', '..', '..', 'openCli')) # openCli/
- sys.path.insert(0, os.path.join(cur_path, '..', '..')) # openEndPoint/
-
-import logging
-import logging.handlers
-
-from engine import EndPointCli
-from engine import EndPoint
-from listener import ListenerUdp
-from epparser import ParserOneList
-from publisher import PublisherScreen
-from injector import InjectorCoap, InjectorCoapLed
-
-UDP_PORT = 5683
-
-class EpUdpRawCli(EndPointCli.EndPointCli):
-
- def __init__(self,endPoint):
-
- # initialize parent class
- EndPointCli.EndPointCli.__init__(self,endPoint,"endPoint UDP Raw")
-
- # add commands
- self.registerCommand('inject',
- 'in',
- 'inject data to CoAP resource',
- [],
- self._handlerInject)
-
- #======================== public ==========================================
-
- #======================== private =========================================
-
- #===== callbacks
-
- def _handlerInject(self,params):
- destination_ip = "2001:470:810a:d42f:1415:9209:22c:99"
- destination_port = 5683
- destination_resource = 'l'
- payload = [0x01,0x02]
- InjectorCoap.InjectorCoap.inject((destination_ip,destination_port),
- destination_resource,
- payload)
-
-def main():
-
- # create an endpoint
- endPoint = EndPoint.EndPoint(
- ListenerUdp.ListenerUdp(UDP_PORT), # listener
- ParserOneList.ParserOneList(), # parser
- [ # publishers
- PublisherScreen.PublisherScreen(),
- ],
- )
- endPoint.start()
-
- # create an openCLI
- cli = EpUdpRawCli(endPoint)
- cli.start()
-
-if __name__=='__main__':
-
- # setup loggin
- logHandler = logging.handlers.RotatingFileHandler('EpUdpRawCli.log',
- maxBytes=2000000,
- backupCount=5,
- mode='w')
- logHandler.setFormatter(logging.Formatter("%(asctime)s [%(name)s:%(levelname)s] %(message)s"))
- for loggerName in ['EndPoint',
- 'ListeningEngine',
- 'ListenerUdp',
- 'ProcessingEngine',
- 'ParserOneNum',
- 'PublishingEngine',
- 'PublisherScreen',
- ]:
- temp = logging.getLogger(loggerName)
- temp.setLevel(logging.DEBUG)
- temp.addHandler(logHandler)
-
- # start the application
+import os
+import sys
+if __name__=='__main__':
+ cur_path = sys.path[0]
+ sys.path.insert(0, os.path.join(cur_path, '..', '..', '..', 'openCli')) # openCli/
+ sys.path.insert(0, os.path.join(cur_path, '..', '..')) # openEndPoint/
+
+import logging
+import logging.handlers
+
+from engine import EndPointCli
+from engine import EndPoint
+from listener import ListenerUdp
+from epparser import ParserOneList
+from publisher import PublisherScreen
+from injector import InjectorCoap, InjectorCoapLed
+
+UDP_PORT = 5683
+
+class EpUdpRawCli(EndPointCli.EndPointCli):
+
+ def __init__(self,endPoint):
+
+ # initialize parent class
+ EndPointCli.EndPointCli.__init__(self,endPoint,"endPoint UDP Raw")
+
+ # add commands
+ self.registerCommand('inject',
+ 'in',
+ 'inject data to CoAP resource',
+ [],
+ self._handlerInject)
+
+ #======================== public ==========================================
+
+ #======================== private =========================================
+
+ #===== callbacks
+
+ def _handlerInject(self,params):
+ destination_ip = "2001:470:810a:d42f:1415:9209:22c:99"
+ destination_port = 5683
+ destination_resource = 'l'
+ payload = [0x01,0x02]
+ InjectorCoap.InjectorCoap.inject((destination_ip,destination_port),
+ destination_resource,
+ payload)
+
+def main():
+
+ # create an endpoint
+ endPoint = EndPoint.EndPoint(
+ ListenerUdp.ListenerUdp(UDP_PORT), # listener
+ ParserOneList.ParserOneList(), # parser
+ [ # publishers
+ PublisherScreen.PublisherScreen(),
+ ],
+ )
+ endPoint.start()
+
+ # create an openCLI
+ cli = EpUdpRawCli(endPoint)
+ cli.start()
+
+if __name__=='__main__':
+
+ # setup loggin
+ logHandler = logging.handlers.RotatingFileHandler('EpUdpRawCli.log',
+ maxBytes=2000000,
+ backupCount=5,
+ mode='w')
+ logHandler.setFormatter(logging.Formatter("%(asctime)s [%(name)s:%(levelname)s] %(message)s"))
+ for loggerName in ['EndPoint',
+ 'ListeningEngine',
+ 'ListenerUdp',
+ 'ProcessingEngine',
+ 'ParserOneNum',
+ 'PublishingEngine',
+ 'PublisherScreen',
+ ]:
+ temp = logging.getLogger(loggerName)
+ temp.setLevel(logging.DEBUG)
+ temp.addHandler(logHandler)
+
+ # start the application
main()
\ No newline at end of file
diff --git a/software/openEndPoint/engine/EndPoint.py b/software/openEndPoint/engine/EndPoint.py
index 28f445bd2..9b8ff1350 100644
--- a/software/openEndPoint/engine/EndPoint.py
+++ b/software/openEndPoint/engine/EndPoint.py
@@ -1,63 +1,63 @@
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('EndPoint')
-log.setLevel(logging.ERROR)
-log.addHandler(NullHandler())
-
-import ListeningEngine
-import ProcessingEngine
-import PublishingEngine
-
-class EndPoint(object):
-
- def __init__(self,listener,parser,publishers):
-
- # store params
- self.listeningEngine = None
- self.listener = listener
- self.processingEngine = None
- self.parser = parser
- self.publisherEngines = []
- self.publishers = publishers
-
- # log
- log.debug('creating instance')
-
- # publisherEngines
- input_functions = []
- for publisher in self.publishers:
- tempEngine = PublishingEngine.PublishingEngine(publisher)
- self.publisherEngines.append(tempEngine)
- input_functions.append(tempEngine.indicateData)
-
- # processingEngine
- self.processingEngine = ProcessingEngine.ProcessingEngine(self.parser,
- input_functions)
-
- # listeningEngine
- self.listeningEngine = ListeningEngine.ListeningEngine(self.listener,
- self.processingEngine.indicateData)
-
- def start(self):
-
- # log
- log.debug('starting')
-
- for pub in self.publisherEngines:
- pub.start()
- self.processingEngine.start()
- self.listeningEngine.start()
-
- def stop(self):
- # close the listening thread. This will propagate to the processing
- # and publishing threads.
- self.listeningEngine.stop()
-
- def getStats(self):
- return {
- 'listeningEngine' : self.listeningEngine.getStats(),
- 'processingEngine' : self.processingEngine.getStats(),
- 'publisherEngines' : [pub.getStats() for pub in self.publisherEngines],
+import logging
+class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+log = logging.getLogger('EndPoint')
+log.setLevel(logging.ERROR)
+log.addHandler(NullHandler())
+
+import ListeningEngine
+import ProcessingEngine
+import PublishingEngine
+
+class EndPoint(object):
+
+ def __init__(self,listener,parser,publishers):
+
+ # store params
+ self.listeningEngine = None
+ self.listener = listener
+ self.processingEngine = None
+ self.parser = parser
+ self.publisherEngines = []
+ self.publishers = publishers
+
+ # log
+ log.debug('creating instance')
+
+ # publisherEngines
+ input_functions = []
+ for publisher in self.publishers:
+ tempEngine = PublishingEngine.PublishingEngine(publisher)
+ self.publisherEngines.append(tempEngine)
+ input_functions.append(tempEngine.indicateData)
+
+ # processingEngine
+ self.processingEngine = ProcessingEngine.ProcessingEngine(self.parser,
+ input_functions)
+
+ # listeningEngine
+ self.listeningEngine = ListeningEngine.ListeningEngine(self.listener,
+ self.processingEngine.indicateData)
+
+ def start(self):
+
+ # log
+ log.debug('starting')
+
+ for pub in self.publisherEngines:
+ pub.start()
+ self.processingEngine.start()
+ self.listeningEngine.start()
+
+ def stop(self):
+ # close the listening thread. This will propagate to the processing
+ # and publishing threads.
+ self.listeningEngine.stop()
+
+ def getStats(self):
+ return {
+ 'listeningEngine' : self.listeningEngine.getStats(),
+ 'processingEngine' : self.processingEngine.getStats(),
+ 'publisherEngines' : [pub.getStats() for pub in self.publisherEngines],
}
\ No newline at end of file
diff --git a/software/openEndPoint/engine/EndPointCli.py b/software/openEndPoint/engine/EndPointCli.py
index b6caf5bd2..a6df7eb7b 100644
--- a/software/openEndPoint/engine/EndPointCli.py
+++ b/software/openEndPoint/engine/EndPointCli.py
@@ -1,39 +1,39 @@
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('endPointTestCli')
-log.setLevel(logging.ERROR)
-log.addHandler(NullHandler())
-
-import pprint
-
-import OpenCli
-
-class EndPointCli(OpenCli.OpenCli):
-
- def __init__(self,endPoint,appName):
-
- # store params
- self.endPoint = endPoint
-
- # initialize parent class
- OpenCli.OpenCli.__init__(self,appName,self.quit_cb)
-
- # add commands
- self.registerCommand('stats',
- 'st',
- 'list stats',
- [],
- self._handlerStats)
-
- #======================== public ==========================================
-
- def quit_cb(self):
- self.endPoint.stop()
-
- #======================== private =========================================
-
- def _handlerStats(self,params):
- pp = pprint.PrettyPrinter(indent=3)
- pp.pprint(self.endPoint.getStats())
+import logging
+class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+log = logging.getLogger('endPointTestCli')
+log.setLevel(logging.ERROR)
+log.addHandler(NullHandler())
+
+import pprint
+
+import OpenCli
+
+class EndPointCli(OpenCli.OpenCli):
+
+ def __init__(self,endPoint,appName):
+
+ # store params
+ self.endPoint = endPoint
+
+ # initialize parent class
+ OpenCli.OpenCli.__init__(self,appName,self.quit_cb)
+
+ # add commands
+ self.registerCommand('stats',
+ 'st',
+ 'list stats',
+ [],
+ self._handlerStats)
+
+ #======================== public ==========================================
+
+ def quit_cb(self):
+ self.endPoint.stop()
+
+ #======================== private =========================================
+
+ def _handlerStats(self,params):
+ pp = pprint.PrettyPrinter(indent=3)
+ pp.pprint(self.endPoint.getStats())
diff --git a/software/openEndPoint/engine/EngineException.py b/software/openEndPoint/engine/EngineException.py
index 2713719e7..4105cb539 100644
--- a/software/openEndPoint/engine/EngineException.py
+++ b/software/openEndPoint/engine/EngineException.py
@@ -1,20 +1,20 @@
-class EngineException(Exception):
-
- def __init__(self, reason=''):
- self.value = reason
-
- def __str__(self) :
- return "{0}: {1}".format(self.__class__.__name__,
- self.value)
-
-class TearDownException(EngineException):
- pass
-
-class OutputUnavailableException(EngineException):
- pass
-
-class ParsingException(EngineException):
- pass
-
-class PublishingException(EngineException):
- pass
+class EngineException(Exception):
+
+ def __init__(self, reason=''):
+ self.value = reason
+
+ def __str__(self) :
+ return "{0}: {1}".format(self.__class__.__name__,
+ self.value)
+
+class TearDownException(EngineException):
+ pass
+
+class OutputUnavailableException(EngineException):
+ pass
+
+class ParsingException(EngineException):
+ pass
+
+class PublishingException(EngineException):
+ pass
diff --git a/software/openEndPoint/engine/EngineStats.py b/software/openEndPoint/engine/EngineStats.py
index eca08471d..e5967fc91 100644
--- a/software/openEndPoint/engine/EngineStats.py
+++ b/software/openEndPoint/engine/EngineStats.py
@@ -1,50 +1,50 @@
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('EngineStats')
-log.setLevel(logging.ERROR)
-log.addHandler(NullHandler())
-
-import threading
-import copy
-
-class EngineStats(object) :
-
- def __init__(self, statNames):
-
- # store params
- self.statNames = statNames
-
- # local variables
- self.statsLock = threading.Lock()
- self.stats = {}
-
- # reset stats
- self.reset()
-
- def __str__(self):
- return '\n'.join(["- {0}: {1}".format(k,v) for (k,v) in self.stats.items()])
-
- #======================== public ==========================================
-
- def reset(self):
- self.statsLock.acquire()
- self.stats = {}
- for name in self.statNames:
- self.stats[name] = 0
- self.statsLock.release()
-
- def increment(self,statName,step=1):
- self.statsLock.acquire()
- self.stats[statName] += step
- self.statsLock.release()
-
- def getStats(self):
- self.statsLock.acquire()
- returnVal = copy.deepcopy(self.stats)
- self.statsLock.release()
-
- return returnVal
-
+import logging
+class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+log = logging.getLogger('EngineStats')
+log.setLevel(logging.ERROR)
+log.addHandler(NullHandler())
+
+import threading
+import copy
+
+class EngineStats(object) :
+
+ def __init__(self, statNames):
+
+ # store params
+ self.statNames = statNames
+
+ # local variables
+ self.statsLock = threading.Lock()
+ self.stats = {}
+
+ # reset stats
+ self.reset()
+
+ def __str__(self):
+ return '\n'.join(["- {0}: {1}".format(k,v) for (k,v) in self.stats.items()])
+
+ #======================== public ==========================================
+
+ def reset(self):
+ self.statsLock.acquire()
+ self.stats = {}
+ for name in self.statNames:
+ self.stats[name] = 0
+ self.statsLock.release()
+
+ def increment(self,statName,step=1):
+ self.statsLock.acquire()
+ self.stats[statName] += step
+ self.statsLock.release()
+
+ def getStats(self):
+ self.statsLock.acquire()
+ returnVal = copy.deepcopy(self.stats)
+ self.statsLock.release()
+
+ return returnVal
+
#======================== private =========================================
\ No newline at end of file
diff --git a/software/openEndPoint/engine/ListeningEngine.py b/software/openEndPoint/engine/ListeningEngine.py
index a14f1efc5..75fa6dc44 100644
--- a/software/openEndPoint/engine/ListeningEngine.py
+++ b/software/openEndPoint/engine/ListeningEngine.py
@@ -1,73 +1,73 @@
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('ListeningEngine')
-log.setLevel(logging.ERROR)
-log.addHandler(NullHandler())
-
-import threading
-
-import EngineStats
-from EngineException import TearDownException, \
- OutputUnavailableException
-
-class ListeningEngine(threading.Thread):
-
- def __init__(self,listener,output_cb):
-
- # store params
- self.listener = listener
- self.output_cb = output_cb
-
- # log
- log.debug("creating instance")
-
- # initialize parent class
- threading.Thread.__init__(self)
-
- # give this thread a name
- self.name = 'ListeningEngine'
-
- # local variables
- self.stats = EngineStats.EngineStats(['numIn',
- 'numOutOk',
- 'numOutFail'])
-
- #======================== public ==========================================
-
- def run(self):
-
- while True:
-
- # block until receiving some data
- try:
- (timestamp,source,data) = self.listener.getData()
- except TearDownException:
- # log
- self.warning("TearDown")
-
- # stop this thread
- break
-
- # log
- log.debug("Got data {2} at {0} from {1}".format(timestamp,source,data))
-
- # update stats
- self.stats.increment('numIn')
-
- # pass on to output
- try:
- self.output_cb((timestamp,source,data))
- except OutputUnavailableException:
- self.stats.increment('numOutFail')
- else:
- self.stats.increment('numOutOk')
-
- def stop(self):
- self.listener.stop()
-
- def getStats(self):
- return self.stats.getStats()
-
+import logging
+class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+log = logging.getLogger('ListeningEngine')
+log.setLevel(logging.ERROR)
+log.addHandler(NullHandler())
+
+import threading
+
+import EngineStats
+from EngineException import TearDownException, \
+ OutputUnavailableException
+
+class ListeningEngine(threading.Thread):
+
+ def __init__(self,listener,output_cb):
+
+ # store params
+ self.listener = listener
+ self.output_cb = output_cb
+
+ # log
+ log.debug("creating instance")
+
+ # initialize parent class
+ threading.Thread.__init__(self)
+
+ # give this thread a name
+ self.name = 'ListeningEngine'
+
+ # local variables
+ self.stats = EngineStats.EngineStats(['numIn',
+ 'numOutOk',
+ 'numOutFail'])
+
+ #======================== public ==========================================
+
+ def run(self):
+
+ while True:
+
+ # block until receiving some data
+ try:
+ (timestamp,source,data) = self.listener.getData()
+ except TearDownException:
+ # log
+ self.warning("TearDown")
+
+ # stop this thread
+ break
+
+ # log
+ log.debug("Got data {2} at {0} from {1}".format(timestamp,source,data))
+
+ # update stats
+ self.stats.increment('numIn')
+
+ # pass on to output
+ try:
+ self.output_cb((timestamp,source,data))
+ except OutputUnavailableException:
+ self.stats.increment('numOutFail')
+ else:
+ self.stats.increment('numOutOk')
+
+ def stop(self):
+ self.listener.stop()
+
+ def getStats(self):
+ return self.stats.getStats()
+
#======================== private =========================================
\ No newline at end of file
diff --git a/software/openEndPoint/engine/ProcessingEngine.py b/software/openEndPoint/engine/ProcessingEngine.py
index b9f5b9d86..20d792154 100644
--- a/software/openEndPoint/engine/ProcessingEngine.py
+++ b/software/openEndPoint/engine/ProcessingEngine.py
@@ -1,80 +1,80 @@
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('ProcessingEngine')
-log.setLevel(logging.ERROR)
-log.addHandler(NullHandler())
-
-import threading
-import Queue
-
-import EngineStats
-from EngineException import OutputUnavailableException, \
- ParsingException
-
-class ProcessingEngine(threading.Thread):
-
- def __init__(self,parser,output_cbs):
-
- # store params
- self.parser = parser
- self.output_cbs = output_cbs
-
- # log
- log.debug("creating instance")
-
- # initialize parent class
- threading.Thread.__init__(self)
-
- # give this thread a name
- self.name = 'ProcessingEngine'
-
- # local variables
- self.goOn = True
- self.inputQueue = Queue.Queue()
- self.stats = EngineStats.EngineStats(['numIn',
- 'numParseOk',
- 'numParseFail',
- 'numOutOk',
- 'numOutFail'])
-
- def run(self):
-
- # log
- log.debug('starting')
-
- while self.goOn:
-
- # block until reading data from the input queue
- (timestamp,source,data) = self.inputQueue.get()
-
- # increment stats
- self.stats.increment('numIn')
-
- # parse
- try:
- parsedData = self.parser.parse(data)
- except ParsingException:
- # increment stats
- self.stats.increment('numParseFail')
- else:
- # increment stats
- self.stats.increment('numParseOk')
-
- # call the callbacks
- for cb in self.output_cbs:
- cb((timestamp,source,parsedData))
-
- #======================== public ==========================================
-
- def indicateData(self,data):
- try:
- self.inputQueue.put_nowait(data)
- except Queue.Full:
- raise OutputUnavailableException()
-
- def getStats(self):
- return self.stats.getStats()
-
+import logging
+class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+log = logging.getLogger('ProcessingEngine')
+log.setLevel(logging.ERROR)
+log.addHandler(NullHandler())
+
+import threading
+import Queue
+
+import EngineStats
+from EngineException import OutputUnavailableException, \
+ ParsingException
+
+class ProcessingEngine(threading.Thread):
+
+ def __init__(self,parser,output_cbs):
+
+ # store params
+ self.parser = parser
+ self.output_cbs = output_cbs
+
+ # log
+ log.debug("creating instance")
+
+ # initialize parent class
+ threading.Thread.__init__(self)
+
+ # give this thread a name
+ self.name = 'ProcessingEngine'
+
+ # local variables
+ self.goOn = True
+ self.inputQueue = Queue.Queue()
+ self.stats = EngineStats.EngineStats(['numIn',
+ 'numParseOk',
+ 'numParseFail',
+ 'numOutOk',
+ 'numOutFail'])
+
+ def run(self):
+
+ # log
+ log.debug('starting')
+
+ while self.goOn:
+
+ # block until reading data from the input queue
+ (timestamp,source,data) = self.inputQueue.get()
+
+ # increment stats
+ self.stats.increment('numIn')
+
+ # parse
+ try:
+ parsedData = self.parser.parse(data)
+ except ParsingException:
+ # increment stats
+ self.stats.increment('numParseFail')
+ else:
+ # increment stats
+ self.stats.increment('numParseOk')
+
+ # call the callbacks
+ for cb in self.output_cbs:
+ cb((timestamp,source,parsedData))
+
+ #======================== public ==========================================
+
+ def indicateData(self,data):
+ try:
+ self.inputQueue.put_nowait(data)
+ except Queue.Full:
+ raise OutputUnavailableException()
+
+ def getStats(self):
+ return self.stats.getStats()
+
#======================== private =========================================
\ No newline at end of file
diff --git a/software/openEndPoint/engine/PublishingEngine.py b/software/openEndPoint/engine/PublishingEngine.py
index 77c7bd779..bd3a3d8a7 100644
--- a/software/openEndPoint/engine/PublishingEngine.py
+++ b/software/openEndPoint/engine/PublishingEngine.py
@@ -1,75 +1,75 @@
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('PublishingEngine')
-log.setLevel(logging.ERROR)
-log.addHandler(NullHandler())
-
-import threading
-import Queue
-
-import EngineStats
-from EngineException import OutputUnavailableException, \
- PublishingException
-
-class PublishingEngine(threading.Thread):
-
- def __init__(self,publisher):
-
- # store params
- self.publisher = publisher
-
- # log
- log.debug("creating instance")
-
- # initialize parent class
- threading.Thread.__init__(self)
-
- # give this thread a name
- self.name = 'PublishingEngine'
-
- # local variables
- self.goOn = True
- self.inputQueue = Queue.Queue()
- self.stats = EngineStats.EngineStats(['numIn',
- 'numPublishedOk',
- 'numPublishedFail'])
-
- def run(self):
-
- # log
- log.debug('starting')
-
- self.publisher.run()
-
- while self.goOn:
-
- # block until reading data from the input queue
- (timestamp,source,data) = self.inputQueue.get()
-
- # increment stats
- self.stats.increment('numIn')
-
- # publish
- try:
- self.publisher.publish(timestamp,source,data)
- except PublishingException:
- # increment stats
- self.stats.increment('numPublishedFail')
- else:
- # increment stats
- self.stats.increment('numPublishedOk')
-
- #======================== public ==========================================
-
- def indicateData(self,data):
- try:
- self.inputQueue.put_nowait(data)
- except Queue.Full:
- raise OutputUnavailableException()
-
- def getStats(self):
- return self.stats.getStats()
-
+import logging
+class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+log = logging.getLogger('PublishingEngine')
+log.setLevel(logging.ERROR)
+log.addHandler(NullHandler())
+
+import threading
+import Queue
+
+import EngineStats
+from EngineException import OutputUnavailableException, \
+ PublishingException
+
+class PublishingEngine(threading.Thread):
+
+ def __init__(self,publisher):
+
+ # store params
+ self.publisher = publisher
+
+ # log
+ log.debug("creating instance")
+
+ # initialize parent class
+ threading.Thread.__init__(self)
+
+ # give this thread a name
+ self.name = 'PublishingEngine'
+
+ # local variables
+ self.goOn = True
+ self.inputQueue = Queue.Queue()
+ self.stats = EngineStats.EngineStats(['numIn',
+ 'numPublishedOk',
+ 'numPublishedFail'])
+
+ def run(self):
+
+ # log
+ log.debug('starting')
+
+ self.publisher.run()
+
+ while self.goOn:
+
+ # block until reading data from the input queue
+ (timestamp,source,data) = self.inputQueue.get()
+
+ # increment stats
+ self.stats.increment('numIn')
+
+ # publish
+ try:
+ self.publisher.publish(timestamp,source,data)
+ except PublishingException:
+ # increment stats
+ self.stats.increment('numPublishedFail')
+ else:
+ # increment stats
+ self.stats.increment('numPublishedOk')
+
+ #======================== public ==========================================
+
+ def indicateData(self,data):
+ try:
+ self.inputQueue.put_nowait(data)
+ except Queue.Full:
+ raise OutputUnavailableException()
+
+ def getStats(self):
+ return self.stats.getStats()
+
#======================== private =========================================
\ No newline at end of file
diff --git a/software/openEndPoint/epparser/CoapCodes.py b/software/openEndPoint/epparser/CoapCodes.py
index a6d0dc9e9..1d450b76f 100644
--- a/software/openEndPoint/epparser/CoapCodes.py
+++ b/software/openEndPoint/epparser/CoapCodes.py
@@ -1,50 +1,50 @@
-#defines all coap option code
-
-option_codes = {
- #response codes
- 65:"2.01 Created ",
- 66:"2.02 Deleted ",
- 67:"2.03 Valid ",
- 68:"2.04 Changed ",
- 69:"2.05 Content ",
- 128:"4.00 Bad Request ",
- 129:"4.01 Unauthorized ",
- 130:"4.02 Bad Option ",
- 131:"4.03 Forbidden ",
- 132:"4.04 Not Found ",
- 133:"4.05 Method Not Allowed ",
- 140:"4.12 Precondition Failed ",
- 141:"4.13 Request Entity Too Large ",
- 143:"4.15 Unsupported Media Type ",
- 160:"5.00 Internal Server Error ",
- 161:"5.01 Not Implemented ",
- 162:"5.02 Bad Gateway ",
- 163:"5.03 Service Unavailable ",
- 164:"5.04 Gateway Timeout ",
- 165:"5.05 Proxying Not Supported ",
- #option number registry
- 1:"Content-Type ",
- 2:"Max-Age ",
- 3:"Proxy-Uri ",
- 4:"ETag ",
- 5:"Uri-Host ",
- 6:"Location-Path ",
- 7:"Uri-Port ",
- 8:"Location-Query ",
- 9:"Uri-Path ",
- 11:"Token ",
- 12:"Accept ",
- 13:"If-Match ",
- 15:"Uri-Query ",
- 21:"If-None-Match ",
- #media types
- 0:"text/plain; charset=utf-8 ",
- 40:"application/link-format ",
- 41:"application/xml ",
- 42:"application/octet-stream ",
- 47:"application/exi ",
- 50:"application/json "
-}
-
-
+#defines all coap option code
+
+option_codes = {
+ #response codes
+ 65:"2.01 Created ",
+ 66:"2.02 Deleted ",
+ 67:"2.03 Valid ",
+ 68:"2.04 Changed ",
+ 69:"2.05 Content ",
+ 128:"4.00 Bad Request ",
+ 129:"4.01 Unauthorized ",
+ 130:"4.02 Bad Option ",
+ 131:"4.03 Forbidden ",
+ 132:"4.04 Not Found ",
+ 133:"4.05 Method Not Allowed ",
+ 140:"4.12 Precondition Failed ",
+ 141:"4.13 Request Entity Too Large ",
+ 143:"4.15 Unsupported Media Type ",
+ 160:"5.00 Internal Server Error ",
+ 161:"5.01 Not Implemented ",
+ 162:"5.02 Bad Gateway ",
+ 163:"5.03 Service Unavailable ",
+ 164:"5.04 Gateway Timeout ",
+ 165:"5.05 Proxying Not Supported ",
+ #option number registry
+ 1:"Content-Type ",
+ 2:"Max-Age ",
+ 3:"Proxy-Uri ",
+ 4:"ETag ",
+ 5:"Uri-Host ",
+ 6:"Location-Path ",
+ 7:"Uri-Port ",
+ 8:"Location-Query ",
+ 9:"Uri-Path ",
+ 11:"Token ",
+ 12:"Accept ",
+ 13:"If-Match ",
+ 15:"Uri-Query ",
+ 21:"If-None-Match ",
+ #media types
+ 0:"text/plain; charset=utf-8 ",
+ 40:"application/link-format ",
+ 41:"application/xml ",
+ 42:"application/octet-stream ",
+ 47:"application/exi ",
+ 50:"application/json "
+}
+
+
\ No newline at end of file
diff --git a/software/openEndPoint/epparser/IsJSON.py b/software/openEndPoint/epparser/IsJSON.py
index 211be1d85..37a1d9697 100644
--- a/software/openEndPoint/epparser/IsJSON.py
+++ b/software/openEndPoint/epparser/IsJSON.py
@@ -1,24 +1,24 @@
-'''
-Created on 11/07/2012
-
-@author: xvilajosana
-'''
-import JSONWrapper
-
-class IsJSON(object):
- '''
- classdocs
- '''
-
-
- def __init__(s):
- '''
- Constructor
- '''
-
- def toJSON(self):
- json=JSONWrapper.JSONWrapper()
- return json.json_repr(self)
-
- def __str__(self):
+'''
+Created on 11/07/2012
+
+@author: xvilajosana
+'''
+import JSONWrapper
+
+class IsJSON(object):
+ '''
+ classdocs
+ '''
+
+
+ def __init__(s):
+ '''
+ Constructor
+ '''
+
+ def toJSON(self):
+ json=JSONWrapper.JSONWrapper()
+ return json.json_repr(self)
+
+ def __str__(self):
return self.toJSON()
\ No newline at end of file
diff --git a/software/openEndPoint/epparser/old/coapCodes.py b/software/openEndPoint/epparser/old/coapCodes.py
index a6d0dc9e9..1d450b76f 100644
--- a/software/openEndPoint/epparser/old/coapCodes.py
+++ b/software/openEndPoint/epparser/old/coapCodes.py
@@ -1,50 +1,50 @@
-#defines all coap option code
-
-option_codes = {
- #response codes
- 65:"2.01 Created ",
- 66:"2.02 Deleted ",
- 67:"2.03 Valid ",
- 68:"2.04 Changed ",
- 69:"2.05 Content ",
- 128:"4.00 Bad Request ",
- 129:"4.01 Unauthorized ",
- 130:"4.02 Bad Option ",
- 131:"4.03 Forbidden ",
- 132:"4.04 Not Found ",
- 133:"4.05 Method Not Allowed ",
- 140:"4.12 Precondition Failed ",
- 141:"4.13 Request Entity Too Large ",
- 143:"4.15 Unsupported Media Type ",
- 160:"5.00 Internal Server Error ",
- 161:"5.01 Not Implemented ",
- 162:"5.02 Bad Gateway ",
- 163:"5.03 Service Unavailable ",
- 164:"5.04 Gateway Timeout ",
- 165:"5.05 Proxying Not Supported ",
- #option number registry
- 1:"Content-Type ",
- 2:"Max-Age ",
- 3:"Proxy-Uri ",
- 4:"ETag ",
- 5:"Uri-Host ",
- 6:"Location-Path ",
- 7:"Uri-Port ",
- 8:"Location-Query ",
- 9:"Uri-Path ",
- 11:"Token ",
- 12:"Accept ",
- 13:"If-Match ",
- 15:"Uri-Query ",
- 21:"If-None-Match ",
- #media types
- 0:"text/plain; charset=utf-8 ",
- 40:"application/link-format ",
- 41:"application/xml ",
- 42:"application/octet-stream ",
- 47:"application/exi ",
- 50:"application/json "
-}
-
-
+#defines all coap option code
+
+option_codes = {
+ #response codes
+ 65:"2.01 Created ",
+ 66:"2.02 Deleted ",
+ 67:"2.03 Valid ",
+ 68:"2.04 Changed ",
+ 69:"2.05 Content ",
+ 128:"4.00 Bad Request ",
+ 129:"4.01 Unauthorized ",
+ 130:"4.02 Bad Option ",
+ 131:"4.03 Forbidden ",
+ 132:"4.04 Not Found ",
+ 133:"4.05 Method Not Allowed ",
+ 140:"4.12 Precondition Failed ",
+ 141:"4.13 Request Entity Too Large ",
+ 143:"4.15 Unsupported Media Type ",
+ 160:"5.00 Internal Server Error ",
+ 161:"5.01 Not Implemented ",
+ 162:"5.02 Bad Gateway ",
+ 163:"5.03 Service Unavailable ",
+ 164:"5.04 Gateway Timeout ",
+ 165:"5.05 Proxying Not Supported ",
+ #option number registry
+ 1:"Content-Type ",
+ 2:"Max-Age ",
+ 3:"Proxy-Uri ",
+ 4:"ETag ",
+ 5:"Uri-Host ",
+ 6:"Location-Path ",
+ 7:"Uri-Port ",
+ 8:"Location-Query ",
+ 9:"Uri-Path ",
+ 11:"Token ",
+ 12:"Accept ",
+ 13:"If-Match ",
+ 15:"Uri-Query ",
+ 21:"If-None-Match ",
+ #media types
+ 0:"text/plain; charset=utf-8 ",
+ 40:"application/link-format ",
+ 41:"application/xml ",
+ 42:"application/octet-stream ",
+ 47:"application/exi ",
+ 50:"application/json "
+}
+
+
\ No newline at end of file
diff --git a/software/openEndPoint/epparser/old/coapParserX.py b/software/openEndPoint/epparser/old/coapParserX.py
index ae9e30f58..3c59f0515 100644
--- a/software/openEndPoint/epparser/old/coapParserX.py
+++ b/software/openEndPoint/epparser/old/coapParserX.py
@@ -1,149 +1,149 @@
-import binascii
-import socket
-import struct
-import os
-import datetime
-
-port = 5683
-
-option_codes = {
- #response codes
- 65:"2.01 Created",
- 66:"2.02 Deleted",
- 67:"2.03 Valid",
- 68:"2.04 Changed",
- 69:"2.05 Content",
- 128:"4.00 Bad Request ",
- 129:"4.01 Unauthorized",
- 130:"4.02 Bad Option",
- 131:"4.03 Forbidden",
- 132:"4.04 Not Found",
- 133:"4.05 Method Not Allowed",
- 140:"4.12 Precondition Failed",
- 141:"4.13 Request Entity Too Large",
- 143:"4.15 Unsupported Media Type",
- 160:"5.00 Internal Server Error",
- 161:"5.01 Not Implemented",
- 162:"5.02 Bad Gateway",
- 163:"5.03 Service Unavailable ",
- 164:"5.04 Gateway Timeout",
- 165:"5.05 Proxying Not Supported",
- #option number registry
- 1:"Content-Type",
- 2:"Max-Age",
- 3:"Proxy-Uri",
- 4:"ETag",
- 5:"Uri-Host",
- 6:"Location-Path",
- 7:"Uri-Port",
- 8:"Location-Query",
- 9:"Uri-Path",
- 11:"Token",
- 12:"Accept",
- 13:"If-Match",
- 15:"Uri-Query",
- 21:"If-None-Match",
- #media types
- 0:"text/plain; charset=utf-8",
- 40:"application/link-format",
- 41:"application/xml",
- 42:"application/octet-stream",
- 47:"application/exi",
- 50:"application/json"
-}
-
-
-def parseCoapData(data, address):
- #try:
- version = int((ord(data[0])& 0xc0) >> 6)
- type = int((ord(data[0])& 0x30) >> 4)
- options = int((ord(data[0])& 0xF))
- code = int(ord(data[1]))
- #for now we only deal with code=3(PUT) code=2(POST)
- mId = int(str(data[2:4]).encode("hex"),16)
- optionList = []
- option_pointer = 4
- #print version,type,options,code
- for i in range(0, options):
- optionDelta = int((ord(data[option_pointer])&0b11110000)>>4)
- optionNumber = optionDelta
- if (i > 0):
- optionNumber = optionDelta + optionList[i-1][0]
- length = int(ord(data[option_pointer])&0b00001111)
- print data[option_pointer+1:option_pointer+length+1]
- option_payload = data[option_pointer+1:option_pointer+length+1]
- option_desc = "" #string describing option
- try:
- #try to get a string to associate with the option code, if none exists use the number
- #option_payload = int(ord(option_payload))
- #option_payload = option_codes[optionDelta]
- option_desc = option_codes[optionNumber]
- except:
- pass
- optionList.append([optionDelta, length, option_desc, option_payload])
- option_pointer = option_pointer + length + 1
-
- #print "poipoi start"
- #for b in data[option_pointer:option_pointer+5]:
- #print str(ord(b))
- #xaviPayload = 256*ord(data[option_pointer])+ord(data[option_pointer+1])
- #print "xaviP="+str(xaviPayload)
- #cmd = 'wget "http://openwsnstats.appspot.com/rest/stats?sid=1&nid=1&rssi='+str(xaviPayload)+'&numtx=10&numrx=20&numack=10&cost=1.0"'
- #print cmd
- #os.system(cmd)
- #print "poipoi stop"
-
- payload=""
- #try:
- # for i in range(len(data[option_pointer:])-1):
- # payload += hex(struct.unpack('b',data[option_pointer+i:option_pointer+i+1])[0]) #data[option_pointer:]
- #except:
- # for i in range(len(data[option_pointer:])-1):
- # payload += hex(struct.unpack('b',data[option_pointer+i:option_pointer+i+1])[0])
-
- payload = binascii.hexlify(data[option_pointer:])
-
- print "addr", address
- print "version ", version
- print "type ", type
- print "options ", options
- print "code ", code
- print "mId", mId
- print "optionList (delta, length, str)", optionList
- print "payload ", payload
-
- #write the data to file if we're intereted in it
- if((code == 3 or code == 2) and address[0][0:2] != "00" ):
- print "writing file"
- if not os.path.exists("/var/www/data/" + address[0]):
- os.makedirs("/var/www/data/" + address[0])
- sensor_name = ""
- now = datetime.datetime.now()
- for option in optionList:
- if (option[2] == 'Location-Path'):
- filepath = "/var/www/data/"+address[0]+"/" + option[3]+".txt"
- f = open(filepath,"a")
- if os.path.getsize(filepath)==0:
- f.write('logtime,coap-payload-hex'+ "\n")
- writeline = ""
- writeline += str(now) + ","
- print "payload xv ", payload
- writeline += payload
- f.write(writeline + "\n")
- f.close()
- #dump everythign else in a "raw" file for debugging
- f_raw = open("/var/www/data/"+address[0]+"/raw.txt","a")
- f_raw.write(str(now) + "," + binascii.hexlify(data) + "\n")
- f_raw.close()
-
- #except:
- # print "Error parsing packet. This demo server only supports a barebone coap post/put implementation."
-
-socket_handler = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
-socket_handler.bind(('',port))
-while True:
- raw,conn = socket_handler.recvfrom(1024)
- print raw
- parseCoapData(raw, conn)
- #print 'version='+str( (ord(raw[0])& 0xc0) >> 6)
- print binascii.hexlify(raw)
+import binascii
+import socket
+import struct
+import os
+import datetime
+
+port = 5683
+
+option_codes = {
+ #response codes
+ 65:"2.01 Created",
+ 66:"2.02 Deleted",
+ 67:"2.03 Valid",
+ 68:"2.04 Changed",
+ 69:"2.05 Content",
+ 128:"4.00 Bad Request ",
+ 129:"4.01 Unauthorized",
+ 130:"4.02 Bad Option",
+ 131:"4.03 Forbidden",
+ 132:"4.04 Not Found",
+ 133:"4.05 Method Not Allowed",
+ 140:"4.12 Precondition Failed",
+ 141:"4.13 Request Entity Too Large",
+ 143:"4.15 Unsupported Media Type",
+ 160:"5.00 Internal Server Error",
+ 161:"5.01 Not Implemented",
+ 162:"5.02 Bad Gateway",
+ 163:"5.03 Service Unavailable ",
+ 164:"5.04 Gateway Timeout",
+ 165:"5.05 Proxying Not Supported",
+ #option number registry
+ 1:"Content-Type",
+ 2:"Max-Age",
+ 3:"Proxy-Uri",
+ 4:"ETag",
+ 5:"Uri-Host",
+ 6:"Location-Path",
+ 7:"Uri-Port",
+ 8:"Location-Query",
+ 9:"Uri-Path",
+ 11:"Token",
+ 12:"Accept",
+ 13:"If-Match",
+ 15:"Uri-Query",
+ 21:"If-None-Match",
+ #media types
+ 0:"text/plain; charset=utf-8",
+ 40:"application/link-format",
+ 41:"application/xml",
+ 42:"application/octet-stream",
+ 47:"application/exi",
+ 50:"application/json"
+}
+
+
+def parseCoapData(data, address):
+ #try:
+ version = int((ord(data[0])& 0xc0) >> 6)
+ type = int((ord(data[0])& 0x30) >> 4)
+ options = int((ord(data[0])& 0xF))
+ code = int(ord(data[1]))
+ #for now we only deal with code=3(PUT) code=2(POST)
+ mId = int(str(data[2:4]).encode("hex"),16)
+ optionList = []
+ option_pointer = 4
+ #print version,type,options,code
+ for i in range(0, options):
+ optionDelta = int((ord(data[option_pointer])&0b11110000)>>4)
+ optionNumber = optionDelta
+ if (i > 0):
+ optionNumber = optionDelta + optionList[i-1][0]
+ length = int(ord(data[option_pointer])&0b00001111)
+ print data[option_pointer+1:option_pointer+length+1]
+ option_payload = data[option_pointer+1:option_pointer+length+1]
+ option_desc = "" #string describing option
+ try:
+ #try to get a string to associate with the option code, if none exists use the number
+ #option_payload = int(ord(option_payload))
+ #option_payload = option_codes[optionDelta]
+ option_desc = option_codes[optionNumber]
+ except:
+ pass
+ optionList.append([optionDelta, length, option_desc, option_payload])
+ option_pointer = option_pointer + length + 1
+
+ #print "poipoi start"
+ #for b in data[option_pointer:option_pointer+5]:
+ #print str(ord(b))
+ #xaviPayload = 256*ord(data[option_pointer])+ord(data[option_pointer+1])
+ #print "xaviP="+str(xaviPayload)
+ #cmd = 'wget "http://openwsnstats.appspot.com/rest/stats?sid=1&nid=1&rssi='+str(xaviPayload)+'&numtx=10&numrx=20&numack=10&cost=1.0"'
+ #print cmd
+ #os.system(cmd)
+ #print "poipoi stop"
+
+ payload=""
+ #try:
+ # for i in range(len(data[option_pointer:])-1):
+ # payload += hex(struct.unpack('b',data[option_pointer+i:option_pointer+i+1])[0]) #data[option_pointer:]
+ #except:
+ # for i in range(len(data[option_pointer:])-1):
+ # payload += hex(struct.unpack('b',data[option_pointer+i:option_pointer+i+1])[0])
+
+ payload = binascii.hexlify(data[option_pointer:])
+
+ print "addr", address
+ print "version ", version
+ print "type ", type
+ print "options ", options
+ print "code ", code
+ print "mId", mId
+ print "optionList (delta, length, str)", optionList
+ print "payload ", payload
+
+ #write the data to file if we're intereted in it
+ if((code == 3 or code == 2) and address[0][0:2] != "00" ):
+ print "writing file"
+ if not os.path.exists("/var/www/data/" + address[0]):
+ os.makedirs("/var/www/data/" + address[0])
+ sensor_name = ""
+ now = datetime.datetime.now()
+ for option in optionList:
+ if (option[2] == 'Location-Path'):
+ filepath = "/var/www/data/"+address[0]+"/" + option[3]+".txt"
+ f = open(filepath,"a")
+ if os.path.getsize(filepath)==0:
+ f.write('logtime,coap-payload-hex'+ "\n")
+ writeline = ""
+ writeline += str(now) + ","
+ print "payload xv ", payload
+ writeline += payload
+ f.write(writeline + "\n")
+ f.close()
+ #dump everythign else in a "raw" file for debugging
+ f_raw = open("/var/www/data/"+address[0]+"/raw.txt","a")
+ f_raw.write(str(now) + "," + binascii.hexlify(data) + "\n")
+ f_raw.close()
+
+ #except:
+ # print "Error parsing packet. This demo server only supports a barebone coap post/put implementation."
+
+socket_handler = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
+socket_handler.bind(('',port))
+while True:
+ raw,conn = socket_handler.recvfrom(1024)
+ print raw
+ parseCoapData(raw, conn)
+ #print 'version='+str( (ord(raw[0])& 0xc0) >> 6)
+ print binascii.hexlify(raw)
diff --git a/software/openEndPoint/epparser/specificparsers/UDPStormParser.py b/software/openEndPoint/epparser/specificparsers/UDPStormParser.py
index 2b36fa11a..ccff1aacb 100644
--- a/software/openEndPoint/epparser/specificparsers/UDPStormParser.py
+++ b/software/openEndPoint/epparser/specificparsers/UDPStormParser.py
@@ -1,40 +1,40 @@
-'''
-Created on 17/07/2012
-
-@author: xvilajosana
-'''
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('UDPStormParser')
-log.setLevel(logging.ERROR)
-log.addHandler(NullHandler())
-
-import SpecificParser
-from .. import CoapHeader
-from .. import Payload
-
-
-from ..ParserException import IncorrectParserException
-
-# Parses the ures test data
-class UDPStormParser(SpecificParser.SpecificParser):
-
- apps=['strm'] #application name, can be a list.
- headerStructure = {
- 'structure': '>8) & 0xff),
- ((myId>>0) & 0xff)]
-
- # log the activity
- self.log.debug('returning '+str(myEui64))
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_eui64_get'],
- myEui64)
-
- #======================== private =========================================
\ No newline at end of file
diff --git a/software/opensim/BspEmulator/BspRadio.py b/software/opensim/BspEmulator/BspRadio.py
deleted file mode 100644
index 4511d2861..000000000
--- a/software/opensim/BspEmulator/BspRadio.py
+++ /dev/null
@@ -1,458 +0,0 @@
-#!/usr/bin/python
-
-import struct
-import BspModule
-
-class RadioState:
- STOPPED = 'STOPPED', # Completely stopped.
- RFOFF = 'RFOFF', # Listening for commands by RF chain is off.
- SETTING_FREQUENCY = 'SETTING_FREQUENCY', # Configuring the frequency.
- FREQUENCY_SET = 'FREQUENCY_SET', # Done configuring the frequency.
- LOADING_PACKET = 'LOADING_PACKET', # Loading packet to send over SPI.
- PACKET_LOADED = 'PACKET_LOADED', # Packet is loaded in the TX buffer.
- ENABLING_TX = 'ENABLING_TX', # The RF Tx chaing is being enabled (includes locked the PLL).
- TX_ENABLED = 'TX_ENABLED', # Radio completely ready to transmit.
- TRANSMITTING = 'TRANSMITTING', # Busy transmitting bytes.
- ENABLING_RX = 'ENABLING_RX', # The RF Rx chaing is being enabled (includes locked the PLL).
- LISTENING = 'LISTENING', # RF chain is on, listening, but no packet received yet.
- RECEIVING = 'RECEIVING', # Busy receiving bytes.
- TXRX_DONE = 'TXRX_DONE', # Frame has been sent/received completely.
- TURNING_OFF = 'TURNING_OFF', # Turning the RF chain off.
-
-class BspRadio(BspModule.BspModule):
- '''
- \brief Emulates the 'radio' BSP module
- '''
-
- INTR_STARTOFFRAME_MOTE = 'radio.startofframe_fromMote'
- INTR_ENDOFFRAME_MOTE = 'radio.endofframe_fromMote'
- INTR_STARTOFFRAME_PROPAGATION = 'radio.startofframe_fromPropagation'
- INTR_ENDOFFRAME_PROPAGATION = 'radio.endofframe_fromPropagation'
-
- def __init__(self,engine,motehandler):
-
- # store params
- self.engine = engine
- self.motehandler = motehandler
-
- # local variables
- self.timeline = self.engine.timeline
- self.propagation = self.engine.propagation
- self.radiotimer = self.motehandler.bspRadiotimer
-
- # local variables
- self.frequency = None # frequency the radio is tuned to
- self.isRfOn = False # radio is off
- self.txBuf = []
- self.rxBuf = []
- self.delayTx = 0.000214
-
- # initialize the parent
- BspModule.BspModule.__init__(self,'BspRadio')
-
- # set initial state
- self._changeState(RadioState.STOPPED)
-
- #======================== public ==========================================
-
- #=== commands
-
- def cmd_init(self,params):
- '''emulates
- void radio_init()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_init')
-
- # change state
- self._changeState(RadioState.STOPPED)
-
- # remember that module has been intialized
- self.isInitialized = True
-
- # change state
- self._changeState(RadioState.RFOFF)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_init'])
-
- def cmd_reset(self,params):
- '''emulates
- void radio_reset()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_reset')
-
- # change state
- self._changeState(RadioState.STOPPED)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_reset'])
-
- def cmd_startTimer(self,params):
- '''emulates
- void radio_startTimer(PORT_TIMER_WIDTH period)'''
-
- # log the activity
- self.log.debug('cmd_startTimer')
-
- # defer to radiotimer
- params = self.motehandler.bspRadiotimer.cmd_start(params,True)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_startTimer'],
- params)
-
- def cmd_getTimerValue(self,params):
- '''emulates
- PORT_TIMER_WIDTH radio_getTimerValue()'''
-
- # log the activity
- self.log.debug('cmd_getTimerValue')
-
- # defer to radiotimer
- params = self.motehandler.bspRadiotimer.cmd_getValue(params,True)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_getTimerValue'],
- params)
-
- def cmd_setTimerPeriod(self,params):
- '''emulates
- void radio_setTimerPeriod(PORT_TIMER_WIDTH period)'''
-
- # log the activity
- self.log.debug('cmd_setTimerPeriod')
-
- # defer to radiotimer
- params = self.motehandler.bspRadiotimer.cmd_setPeriod(params,True)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_setTimerPeriod'],
- params)
-
- def cmd_getTimerPeriod(self,params):
- '''emulates
- PORT_TIMER_WIDTH radio_getTimerPeriod()'''
-
- # log the activity
- self.log.debug('cmd_getTimerPeriod')
-
- # defer to radiotimer
- params = self.motehandler.bspRadiotimer.cmd_getPeriod(params,True)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_getTimerPeriod'],
- params)
-
- def cmd_setFrequency(self,params):
- '''emulates
- void radio_setFrequency(uint8_t frequency)'''
-
- # unpack the parameters
- (self.frequency,) = struct.unpack('B', params)
-
- # log the activity
- self.log.debug('cmd_setFrequency frequency='+str(self.frequency))
-
- # change state
- self._changeState(RadioState.SETTING_FREQUENCY)
-
- # change state
- self._changeState(RadioState.FREQUENCY_SET)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_setFrequency'])
-
- def cmd_rfOn(self,params):
- '''emulates
- void radio_rfOn()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_rfOn')
-
- # update local variable
- self.isRfOn = True
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_rfOn'])
-
- def cmd_rfOff(self,params):
- '''emulates
- void radio_rfOff()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_rfOff')
-
- # change state
- self._changeState(RadioState.TURNING_OFF)
-
- # update local variable
- self.isRfOn = False
-
- # change state
- self._changeState(RadioState.RFOFF)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_rfOff'])
-
- def cmd_loadPacket(self,params):
- '''emulates
- void radio_loadPacket(uint8_t* packet, uint8_t len)'''
-
- # make sure length of params is expected
- assert(len(params)==127+1)
-
- # log the activity
- self.log.debug('cmd_loadPacket len={0}'.format(len(params)))
-
- # change state
- self._changeState(RadioState.LOADING_PACKET)
-
- # update local variable
- length = ord(params[0])
- print length
-
- self.txBuf = []
- self.txBuf.append(length)
- for i in range(1,length+1):
- self.txBuf.append(ord(params[i]))
- output = ''
- for c in self.txBuf:
- output += ' %.2x'%c
- print output
-
- # log
- self.log.debug('txBuf={0}'.format(self.txBuf))
-
- # change state
- self._changeState(RadioState.PACKET_LOADED)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_loadPacket'])
-
- def cmd_txEnable(self,params):
- '''emulates
- void radio_txEnable()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_txEnable')
-
- # change state
- self._changeState(RadioState.ENABLING_TX)
-
- # change state
- self._changeState(RadioState.TX_ENABLED)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_txEnable'])
-
- def cmd_txNow(self,params):
- '''emulates
- void radio_txNow()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_txNow')
-
- # change state
- self._changeState(RadioState.TRANSMITTING)
-
- # get current time
- currenttime = self.timeline.getCurrentTime()
-
- # calculate when the "start of frame" event will take place
- startOfFrameTime = currenttime+self.delayTx
-
- # schedule "start of frame" event
- self.timeline.scheduleEvent(startOfFrameTime,
- self.motehandler.getId(),
- self.intr_startOfFrame_fromMote,
- self.INTR_STARTOFFRAME_MOTE)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_txNow'])
-
- def cmd_rxEnable(self,params):
- '''emulates
- void radio_rxEnable()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_rxEnable')
-
- # change state
- self._changeState(RadioState.ENABLING_RX)
-
- # change state
- self._changeState(RadioState.LISTENING)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_rxEnable'])
-
- def cmd_rxNow(self,params):
- '''emulates
- void radio_rxNow()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_rxNow')
-
- # change state
- self._changeState(RadioState.LISTENING)
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_rxNow'])
-
- def cmd_getReceivedFrame(self,params):
- '''emulates
- void radio_getReceivedFrame(uint8_t* pBufRead,
- uint8_t* pLenRead,
- uint8_t maxBufLen,
- int8_t* pRssi,
- uint8_t* pLqi,
- uint8_t* pCrc)'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_getReceivedFrame')
-
- #==== prepare response
- # uint8_t rxBuffer[128];
- params = self.rxBuf[1:]
- while len(params)<128:
- params.append(0)
- # uint8_t len;
- params.append(len(self.rxBuf)-1)
- # int8_t rssi;
- for i in struct.pack('>0)%0xff,(counterVal>>8)%0xff])
-
- def intr_startOfFrame_fromPropagation(self):
-
- # signal start of frame to mote
- counterVal = self.radiotimer.getCounterVal()
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_isr_startFrame'],
- [(counterVal>>0)%0xff,(counterVal>>8)%0xff])
-
- def intr_endOfFrame_fromMote(self):
- # indicate transmission end to propagation model
- self.propagation.txEnd(self.motehandler.getId())
-
- # signal end of frame to mote
- counterVal = self.radiotimer.getCounterVal()
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_isr_endFrame'],
- [(counterVal>>0)%0xff,(counterVal>>8)%0xff])
-
- def intr_endOfFrame_fromPropagation(self):
-
- # signal end of frame to mote
- counterVal = self.radiotimer.getCounterVal()
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_radio_isr_endFrame'],
- [(counterVal>>0)%0xff,(counterVal>>8)%0xff])
-
- #======================== indication from propagation =====================
-
- def indicateTxStart(self,moteId,packet,channel):
-
- self.log.debug('indicateTxStart from moteId={0} channel={1} len={2}'.format(
- moteId,channel,len(packet)))
-
- if (self.isInitialized==True and
- self.state==RadioState.LISTENING and
- self.frequency==channel):
- self._changeState(RadioState.RECEIVING)
- self.rxBuf = packet
- self.rssi = -50
- self.lqi = 100
- self.crcPasses = True
-
- # log
- self.log.debug('rxBuf={0}'.format(self.rxBuf))
-
- # schedule start of frame
- self.timeline.scheduleEvent(self.timeline.getCurrentTime(),
- self.motehandler.getId(),
- self.intr_startOfFrame_fromPropagation,
- self.INTR_STARTOFFRAME_PROPAGATION)
-
- def indicateTxEnd(self,moteId):
-
- self.log.debug('indicateTxEnd from moteId={0}'.format(moteId))
-
- if (self.isInitialized==True and
- self.state==RadioState.RECEIVING):
- self._changeState(RadioState.TXRX_DONE)
-
- # schedule end of frame
- self.timeline.scheduleEvent(self.timeline.getCurrentTime(),
- self.motehandler.getId(),
- self.intr_endOfFrame_fromPropagation,
- self.INTR_ENDOFFRAME_PROPAGATION)
-
- #======================== private =========================================
-
- def _packetLengthToDuration(self,numBytes):
- return float(numBytes*8)/250000.0
-
- def _changeState(self,newState):
- self.state = newState
- self.log.debug('state={0}'.format(self.state))
\ No newline at end of file
diff --git a/software/opensim/BspEmulator/BspUart.py b/software/opensim/BspEmulator/BspUart.py
deleted file mode 100644
index 61e846229..000000000
--- a/software/opensim/BspEmulator/BspUart.py
+++ /dev/null
@@ -1,139 +0,0 @@
-#!/usr/bin/python
-
-import struct
-import BspModule
-import serial
-
-class BspUart(BspModule.BspModule):
- '''
- \brief Emulates the 'uart' BSP module
- '''
-
- def __init__(self,engine,motehandler):
-
- # store params
- self.engine = engine
- self.motehandler = motehandler
-
- # local variables
- #self.serialHandler = serial.Serial('\\\\.\\CNCA0',baudrate=115200)
- self.interruptsEnabled = False
- self.txInterruptFlag = False
- self.rxInterruptFlag = False
-
- # initialize the parent
- BspModule.BspModule.__init__(self,'BspUart')
-
- #======================== public ==========================================
-
- #=== commands
-
- def cmd_init(self,params):
- '''emulates
- void uart_init()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_init')
-
- # remember that module has been intialized
- self.isInitialized = True
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_uart_init'])
-
- def cmd_enableInterrupts(self,params):
- '''emulates
- void uart_enableInterrupts()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_enableInterrupts')
-
- # update variables
- self.interruptsEnabled = True
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_uart_enableInterrupts'])
-
- def cmd_disableInterrupts(self,params):
- '''emulates
- void uart_disableInterrupts()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_disableInterrupts')
-
- # update variables
- self.interruptsEnabled = False
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_uart_disableInterrupts'])
-
- def cmd_clearRxInterrupts(self,params):
- '''emulates
- void uart_clearRxInterrupts()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_clearRxInterrupts')
-
- # update variables
- self.rxInterruptFlag = False
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_uart_clearRxInterrupts'])
-
- def cmd_clearTxInterrupts(self,params):
- '''emulates
- void uart_clearTxInterrupts()'''
-
- # make sure length of params is expected
- assert(len(params)==0)
-
- # log the activity
- self.log.debug('cmd_clearTxInterrupts')
-
- # update variables
- self.txInterruptFlag = False
-
- # respond
- self.motehandler.sendCommand(self.motehandler.commandIds['OPENSIM_CMD_uart_clearTxInterrupts'])
-
- def cmd_writeByte(self,params):
- '''emulates
- void uart_writeByte(uint8_t byteToWrite)'''
-
- # unpack the parameters
- (self.lastTxChar,) = struct.unpack('timeLastTick:
- return 0
- else:
- period = self._getPeriod()
- return int(math.floor(float(timeLastTick-eventTime)/float(period)))
-
- #======================== private =========================================
-
- def _getPeriod(self):
-
- period = float(1)/float(self.frequency) # nominal period
- period += float(self.drift)*float(period/1000000) # apply drift
-
- return period
-
\ No newline at end of file
diff --git a/software/opensim/SimEngine/DaemonThread.py b/software/opensim/SimEngine/DaemonThread.py
deleted file mode 100644
index 94de981d4..000000000
--- a/software/opensim/SimEngine/DaemonThread.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-
-import threading
-import socket
-import logging
-
-from MoteHandler import MoteHandler
-
-TCPCONN_MAXBACKLOG = 1 # the max number of unserved TCP connections
-
-class NullLogHandler(logging.Handler):
- def emit(self, record):
- pass
-
-class DaemonThread(threading.Thread):
- '''
- \brief Thread waiting for new connections from motes over TCP.
- '''
-
- TCPPORT = 14159
-
- def __init__(self,engine):
-
- # store variables
- self.engine = engine
-
- # local variables
-
- # logging
- self.log = logging.getLogger('DaemonThread')
- self.log.setLevel(logging.DEBUG)
- self.log.addHandler(NullLogHandler())
-
- # initialize parent class
- threading.Thread.__init__(self)
-
- # set thread name
- self.setName('DaemonThread')
-
- # thread daemon mode
- self.setDaemon(True)
-
- def run(self):
-
- # log
- self.log.info('starting on port='+str(self.TCPPORT))
-
- # create socket to listen on
- try:
- self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.socket.bind(('',self.TCPPORT))
- self.socket.listen(TCPCONN_MAXBACKLOG)
- except Exception as err:
- self.log.debug('could not start listening, err='+str(err))
-
- self.log.debug('listening')
-
- while True:
-
- # the daemon stops here while waiting for a user to connect
- conn,addr = self.socket.accept()
-
- # log connection attempt
- self.log.info("Connection attempt from "+str(addr))
-
- # get id
-
- # get location
-
- # hand over connection to moteHandler
- moteHandler = MoteHandler(self.engine,conn,addr[0],addr[1])
-
- # indicate to the engine the new mote's handler
- self.engine.indicateNewMote(moteHandler)
-
- # start the new mote handler
- moteHandler.start()
diff --git a/software/opensim/SimEngine/LocationManager.py b/software/opensim/SimEngine/LocationManager.py
deleted file mode 100644
index 0d4180b37..000000000
--- a/software/opensim/SimEngine/LocationManager.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/python
-
-import random
-import logging
-
-class NullLogHandler(logging.Handler):
- def emit(self, record):
- pass
-
-class LocationManager(object):
- '''
- \brief The module which assigns locations to the motes.
- '''
-
- def __init__(self,engine):
-
- # store params
- self.engine = engine
-
- # local variables
-
- # logging
- self.log = logging.getLogger('LocationManager')
- self.log.setLevel(logging.DEBUG)
- self.log.addHandler(NullLogHandler())
-
-
- #======================== public ==========================================
-
- def getLocation(self):
-
- x = random.randint(0,100)
- y = random.randint(0,100)
- z = 0
-
- # debug
- self.log.debug('assigning location ('+str(x)+','+str(y)+','+str(z)+')')
-
- return (x,y,z)
-
- #======================== private =========================================
-
- #======================== helpers =========================================
-
\ No newline at end of file
diff --git a/software/opensim/SimEngine/MoteHandler.py b/software/opensim/SimEngine/MoteHandler.py
deleted file mode 100644
index 99152e84a..000000000
--- a/software/opensim/SimEngine/MoteHandler.py
+++ /dev/null
@@ -1,370 +0,0 @@
-#!/usr/bin/python
-
-import threading
-import socket
-import logging
-import os
-import time
-import binascii
-
-from BspEmulator import BspBoard
-from BspEmulator import BspBsp_timer
-from BspEmulator import BspDebugpins
-from BspEmulator import BspEui64
-from BspEmulator import BspLeds
-from BspEmulator import BspRadio
-from BspEmulator import BspRadiotimer
-from BspEmulator import BspUart
-from BspEmulator import HwSupply
-from BspEmulator import HwCrystal
-
-TCPRXBUFSIZE = 4096 # size of the TCP reception buffer
-
-class NullLogHandler(logging.Handler):
- def emit(self, record):
- pass
-
-class MoteHandler(threading.Thread):
- '''
- \brief Handle the connection of a mote.
- '''
-
- commandIds = {
- #===== from client to server
- # board
- 'OPENSIM_CMD_board_init' : 0,
- 'OPENSIM_CMD_board_sleep' : 1,
- # bsp_timer
- 'OPENSIM_CMD_bsp_timer_init' : 2,
- 'OPENSIM_CMD_bsp_timer_reset' : 3,
- 'OPENSIM_CMD_bsp_timer_scheduleIn' : 4,
- 'OPENSIM_CMD_bsp_timer_cancel_schedule' : 5,
- 'OPENSIM_CMD_bsp_timer_get_currentValue' : 6,
- # debugpins
- 'OPENSIM_CMD_debugpins_init' : 7,
- 'OPENSIM_CMD_debugpins_frame_toggle' : 8,
- 'OPENSIM_CMD_debugpins_frame_clr' : 9,
- 'OPENSIM_CMD_debugpins_frame_set' : 10,
- 'OPENSIM_CMD_debugpins_slot_toggle' : 11,
- 'OPENSIM_CMD_debugpins_slot_clr' : 12,
- 'OPENSIM_CMD_debugpins_slot_set' : 13,
- 'OPENSIM_CMD_debugpins_fsm_toggle' : 14,
- 'OPENSIM_CMD_debugpins_fsm_clr' : 15,
- 'OPENSIM_CMD_debugpins_fsm_set' : 16,
- 'OPENSIM_CMD_debugpins_task_toggle' : 17,
- 'OPENSIM_CMD_debugpins_task_clr' : 18,
- 'OPENSIM_CMD_debugpins_task_set' : 19,
- 'OPENSIM_CMD_debugpins_isr_toggle' : 20,
- 'OPENSIM_CMD_debugpins_isr_clr' : 21,
- 'OPENSIM_CMD_debugpins_isr_set' : 22,
- 'OPENSIM_CMD_debugpins_radio_toggle' : 23,
- 'OPENSIM_CMD_debugpins_radio_clr' : 24,
- 'OPENSIM_CMD_debugpins_radio_set' : 25,
- # eui64
- 'OPENSIM_CMD_eui64_get' : 26,
- # leds
- 'OPENSIM_CMD_leds_init' : 27,
- 'OPENSIM_CMD_leds_error_on' : 28,
- 'OPENSIM_CMD_leds_error_off' : 29,
- 'OPENSIM_CMD_leds_error_toggle' : 30,
- 'OPENSIM_CMD_leds_error_isOn' : 31,
- 'OPENSIM_CMD_leds_radio_on' : 32,
- 'OPENSIM_CMD_leds_radio_off' : 33,
- 'OPENSIM_CMD_leds_radio_toggle' : 34,
- 'OPENSIM_CMD_leds_radio_isOn' : 35,
- 'OPENSIM_CMD_leds_sync_on' : 36,
- 'OPENSIM_CMD_leds_sync_off' : 37,
- 'OPENSIM_CMD_leds_sync_toggle' : 38,
- 'OPENSIM_CMD_leds_sync_isOn' : 39,
- 'OPENSIM_CMD_leds_debug_on' : 40,
- 'OPENSIM_CMD_leds_debug_off' : 41,
- 'OPENSIM_CMD_leds_debug_toggle' : 42,
- 'OPENSIM_CMD_leds_debug_isOn' : 43,
- 'OPENSIM_CMD_leds_all_on' : 44,
- 'OPENSIM_CMD_leds_all_off' : 45,
- 'OPENSIM_CMD_leds_all_toggle' : 46,
- 'OPENSIM_CMD_leds_circular_shift' : 47,
- 'OPENSIM_CMD_leds_increment' : 48,
- # radio
- 'OPENSIM_CMD_radio_init' : 49,
- 'OPENSIM_CMD_radio_reset' : 50,
- 'OPENSIM_CMD_radio_startTimer' : 51,
- 'OPENSIM_CMD_radio_getTimerValue' : 52,
- 'OPENSIM_CMD_radio_setTimerPeriod' : 53,
- 'OPENSIM_CMD_radio_getTimerPeriod' : 54,
- 'OPENSIM_CMD_radio_setFrequency' : 55,
- 'OPENSIM_CMD_radio_rfOn' : 56,
- 'OPENSIM_CMD_radio_rfOff' : 57,
- 'OPENSIM_CMD_radio_loadPacket' : 58,
- 'OPENSIM_CMD_radio_txEnable' : 59,
- 'OPENSIM_CMD_radio_txNow' : 60,
- 'OPENSIM_CMD_radio_rxEnable' : 61,
- 'OPENSIM_CMD_radio_rxNow' : 62,
- 'OPENSIM_CMD_radio_getReceivedFrame' : 63,
- # radiotimer
- 'OPENSIM_CMD_radiotimer_init' : 64,
- 'OPENSIM_CMD_radiotimer_start' : 65,
- 'OPENSIM_CMD_radiotimer_getValue' : 66,
- 'OPENSIM_CMD_radiotimer_setPeriod' : 67,
- 'OPENSIM_CMD_radiotimer_getPeriod' : 68,
- 'OPENSIM_CMD_radiotimer_schedule' : 69,
- 'OPENSIM_CMD_radiotimer_cancel' : 70,
- 'OPENSIM_CMD_radiotimer_getCapturedTime' : 71,
- # uart
- 'OPENSIM_CMD_uart_init' : 72,
- 'OPENSIM_CMD_uart_enableInterrupts' : 73,
- 'OPENSIM_CMD_uart_disableInterrupts' : 74,
- 'OPENSIM_CMD_uart_clearRxInterrupts' : 75,
- 'OPENSIM_CMD_uart_clearTxInterrupts' : 76,
- 'OPENSIM_CMD_uart_writeByte' : 77,
- 'OPENSIM_CMD_uart_readByte' : 78,
- # supply
- #===== from server to client
- # board
- # bsp_timer
- 'OPENSIM_CMD_bsp_timer_isr' : 100,
- # debugpins
- # eui64
- # leds
- # radio
- 'OPENSIM_CMD_radio_isr_startFrame' : 101,
- 'OPENSIM_CMD_radio_isr_endFrame' : 102,
- # radiotimer
- 'OPENSIM_CMD_radiotimer_isr_compare' : 103,
- 'OPENSIM_CMD_radiotimer_isr_overflow' : 104,
- # uart
- 'OPENSIM_CMD_uart_isr_tx' : 105,
- 'OPENSIM_CMD_uart_isr_rx' : 106,
- # supply
- 'OPENSIM_CMD_supply_on' : 107,
- 'OPENSIM_CMD_supply_off' : 108,
- }
-
- def __init__(self,engine,conn,addr,port):
-
- # store params
- self.engine = engine
- self.conn = conn
- self.addr = addr
- self.port = port
-
- # obtain an id and location for the new mote
- self.id = self.engine.idmanager.getId()
- self.location = self.engine.locationmanager.getLocation()
-
- #=== local variables
- self.loghandler = self.engine.loghandler
- # stats
- self.numRxCommands = 0
- self.numTxCommands = 0
- # hw
- self.hwSupply = HwSupply.HwSupply(self.engine,self)
- self.hwCrystal = HwCrystal.HwCrystal(self.engine,self)
- # bsp
- self.bspBoard = BspBoard.BspBoard(self.engine,self)
- self.bspBsp_timer = BspBsp_timer.BspBsp_timer(self.engine,self)
- self.bspDebugpins = BspDebugpins.BspDebugpins(self.engine,self)
- self.bspEui64 = BspEui64.BspEui64(self.engine,self)
- self.bspLeds = BspLeds.BspLeds(self.engine,self)
- self.bspRadiotimer = BspRadiotimer.BspRadiotimer(self.engine,self)
- self.bspRadio = BspRadio.BspRadio(self.engine,self)
- self.bspUart = BspUart.BspUart(self.engine,self)
- # callbacks
- self.commandCallbacks = {
- # board
- self.commandIds['OPENSIM_CMD_board_init'] : self.bspBoard.cmd_init,
- self.commandIds['OPENSIM_CMD_board_sleep'] : self.bspBoard.cmd_sleep,
- # bsp_timer
- self.commandIds['OPENSIM_CMD_bsp_timer_init'] : self.bspBsp_timer.cmd_init,
- self.commandIds['OPENSIM_CMD_bsp_timer_reset'] : self.bspBsp_timer.cmd_reset,
- self.commandIds['OPENSIM_CMD_bsp_timer_scheduleIn'] : self.bspBsp_timer.cmd_scheduleIn,
- self.commandIds['OPENSIM_CMD_bsp_timer_cancel_schedule'] : self.bspBsp_timer.cmd_cancel_schedule,
- self.commandIds['OPENSIM_CMD_bsp_timer_get_currentValue']: self.bspBsp_timer.cmd_get_currentValue,
- # debugpins
- self.commandIds['OPENSIM_CMD_debugpins_init'] : self.bspDebugpins.cmd_init,
- self.commandIds['OPENSIM_CMD_debugpins_frame_toggle'] : self.bspDebugpins.cmd_frame_toggle,
- self.commandIds['OPENSIM_CMD_debugpins_frame_clr'] : self.bspDebugpins.cmd_frame_clr,
- self.commandIds['OPENSIM_CMD_debugpins_frame_set'] : self.bspDebugpins.cmd_frame_set,
- self.commandIds['OPENSIM_CMD_debugpins_slot_toggle'] : self.bspDebugpins.cmd_slot_toggle,
- self.commandIds['OPENSIM_CMD_debugpins_slot_clr'] : self.bspDebugpins.cmd_slot_clr,
- self.commandIds['OPENSIM_CMD_debugpins_slot_set'] : self.bspDebugpins.cmd_slot_set,
- self.commandIds['OPENSIM_CMD_debugpins_fsm_toggle'] : self.bspDebugpins.cmd_fsm_toggle,
- self.commandIds['OPENSIM_CMD_debugpins_fsm_clr'] : self.bspDebugpins.cmd_fsm_clr,
- self.commandIds['OPENSIM_CMD_debugpins_fsm_set'] : self.bspDebugpins.cmd_fsm_set,
- self.commandIds['OPENSIM_CMD_debugpins_task_toggle'] : self.bspDebugpins.cmd_task_toggle,
- self.commandIds['OPENSIM_CMD_debugpins_task_clr'] : self.bspDebugpins.cmd_task_clr,
- self.commandIds['OPENSIM_CMD_debugpins_task_set'] : self.bspDebugpins.cmd_task_set,
- self.commandIds['OPENSIM_CMD_debugpins_isr_toggle'] : self.bspDebugpins.cmd_isr_toggle,
- self.commandIds['OPENSIM_CMD_debugpins_isr_clr'] : self.bspDebugpins.cmd_isr_clr,
- self.commandIds['OPENSIM_CMD_debugpins_isr_set'] : self.bspDebugpins.cmd_isr_set,
- self.commandIds['OPENSIM_CMD_debugpins_radio_toggle'] : self.bspDebugpins.cmd_radio_toggle,
- self.commandIds['OPENSIM_CMD_debugpins_radio_clr'] : self.bspDebugpins.cmd_radio_clr,
- self.commandIds['OPENSIM_CMD_debugpins_radio_set'] : self.bspDebugpins.cmd_radio_set,
- # eui64
- self.commandIds['OPENSIM_CMD_eui64_get'] : self.bspEui64.cmd_get,
- # leds
- self.commandIds['OPENSIM_CMD_leds_init'] : self.bspLeds.cmd_init,
- self.commandIds['OPENSIM_CMD_leds_error_on'] : self.bspLeds.cmd_error_on,
- self.commandIds['OPENSIM_CMD_leds_error_off'] : self.bspLeds.cmd_error_off,
- self.commandIds['OPENSIM_CMD_leds_error_toggle'] : self.bspLeds.cmd_error_toggle,
- self.commandIds['OPENSIM_CMD_leds_error_isOn'] : self.bspLeds.cmd_error_isOn,
- self.commandIds['OPENSIM_CMD_leds_radio_on'] : self.bspLeds.cmd_radio_on,
- self.commandIds['OPENSIM_CMD_leds_radio_off'] : self.bspLeds.cmd_radio_off,
- self.commandIds['OPENSIM_CMD_leds_radio_toggle'] : self.bspLeds.cmd_radio_toggle,
- self.commandIds['OPENSIM_CMD_leds_radio_isOn'] : self.bspLeds.cmd_radio_isOn,
- self.commandIds['OPENSIM_CMD_leds_sync_on'] : self.bspLeds.cmd_sync_on,
- self.commandIds['OPENSIM_CMD_leds_sync_off'] : self.bspLeds.cmd_sync_off,
- self.commandIds['OPENSIM_CMD_leds_sync_toggle'] : self.bspLeds.cmd_sync_toggle,
- self.commandIds['OPENSIM_CMD_leds_sync_isOn'] : self.bspLeds.cmd_sync_isOn,
- self.commandIds['OPENSIM_CMD_leds_debug_on'] : self.bspLeds.cmd_debug_on,
- self.commandIds['OPENSIM_CMD_leds_debug_off'] : self.bspLeds.cmd_debug_off,
- self.commandIds['OPENSIM_CMD_leds_debug_toggle'] : self.bspLeds.cmd_debug_toggle,
- self.commandIds['OPENSIM_CMD_leds_debug_isOn'] : self.bspLeds.cmd_debug_isOn,
- self.commandIds['OPENSIM_CMD_leds_all_on'] : self.bspLeds.cmd_all_on,
- self.commandIds['OPENSIM_CMD_leds_all_off'] : self.bspLeds.cmd_all_off,
- self.commandIds['OPENSIM_CMD_leds_all_toggle'] : self.bspLeds.cmd_all_toggle,
- self.commandIds['OPENSIM_CMD_leds_circular_shift'] : self.bspLeds.cmd_circular_shift,
- self.commandIds['OPENSIM_CMD_leds_increment'] : self.bspLeds.cmd_increment,
- # radio
- self.commandIds['OPENSIM_CMD_radio_init'] : self.bspRadio.cmd_init,
- self.commandIds['OPENSIM_CMD_radio_reset'] : self.bspRadio.cmd_reset,
- self.commandIds['OPENSIM_CMD_radio_startTimer'] : self.bspRadio.cmd_startTimer,
- self.commandIds['OPENSIM_CMD_radio_getTimerValue'] : self.bspRadio.cmd_getTimerValue,
- self.commandIds['OPENSIM_CMD_radio_setTimerPeriod'] : self.bspRadio.cmd_setTimerPeriod,
- self.commandIds['OPENSIM_CMD_radio_getTimerPeriod'] : self.bspRadio.cmd_getTimerPeriod,
- self.commandIds['OPENSIM_CMD_radio_setFrequency'] : self.bspRadio.cmd_setFrequency,
- self.commandIds['OPENSIM_CMD_radio_rfOn'] : self.bspRadio.cmd_rfOn,
- self.commandIds['OPENSIM_CMD_radio_rfOff'] : self.bspRadio.cmd_rfOff,
- self.commandIds['OPENSIM_CMD_radio_loadPacket'] : self.bspRadio.cmd_loadPacket,
- self.commandIds['OPENSIM_CMD_radio_txEnable'] : self.bspRadio.cmd_txEnable,
- self.commandIds['OPENSIM_CMD_radio_txNow'] : self.bspRadio.cmd_txNow,
- self.commandIds['OPENSIM_CMD_radio_rxEnable'] : self.bspRadio.cmd_rxEnable,
- self.commandIds['OPENSIM_CMD_radio_rxNow'] : self.bspRadio.cmd_rxNow,
- self.commandIds['OPENSIM_CMD_radio_getReceivedFrame'] : self.bspRadio.cmd_getReceivedFrame,
- # radiotimer
- self.commandIds['OPENSIM_CMD_radiotimer_init'] : self.bspRadiotimer.cmd_init,
- self.commandIds['OPENSIM_CMD_radiotimer_start'] : self.bspRadiotimer.cmd_start,
- self.commandIds['OPENSIM_CMD_radiotimer_getValue'] : self.bspRadiotimer.cmd_getValue,
- self.commandIds['OPENSIM_CMD_radiotimer_setPeriod'] : self.bspRadiotimer.cmd_setPeriod,
- self.commandIds['OPENSIM_CMD_radiotimer_getPeriod'] : self.bspRadiotimer.cmd_getPeriod,
- self.commandIds['OPENSIM_CMD_radiotimer_schedule'] : self.bspRadiotimer.cmd_schedule,
- self.commandIds['OPENSIM_CMD_radiotimer_cancel'] : self.bspRadiotimer.cmd_cancel,
- self.commandIds['OPENSIM_CMD_radiotimer_getCapturedTime']: self.bspRadiotimer.cmd_getCapturedTime,
- # uart
- self.commandIds['OPENSIM_CMD_uart_init'] : self.bspUart.cmd_init,
- self.commandIds['OPENSIM_CMD_uart_enableInterrupts'] : self.bspUart.cmd_enableInterrupts,
- self.commandIds['OPENSIM_CMD_uart_disableInterrupts'] : self.bspUart.cmd_disableInterrupts,
- self.commandIds['OPENSIM_CMD_uart_clearRxInterrupts'] : self.bspUart.cmd_clearRxInterrupts,
- self.commandIds['OPENSIM_CMD_uart_clearTxInterrupts'] : self.bspUart.cmd_clearTxInterrupts,
- self.commandIds['OPENSIM_CMD_uart_writeByte'] : self.bspUart.cmd_writeByte,
- self.commandIds['OPENSIM_CMD_uart_readByte'] : self.bspUart.cmd_readByte,
- }
-
- # logging this module
- self.log = logging.getLogger('MoteHandler_'+str(self.id))
- self.log.setLevel(logging.DEBUG)
- self.log.addHandler(NullLogHandler())
-
- # logging this mote's modules
- for loggerName in [
- 'MoteHandler_'+str(self.id),
- # hw
- 'HwSupply_'+str(self.id),
- 'HwCrystal_'+str(self.id),
- # bsp
- 'BspBoard_'+str(self.id),
- 'BspBsp_timer_'+str(self.id),
- 'BspDebugpins_'+str(self.id),
- 'BspEui64_'+str(self.id),
- 'BspLeds_'+str(self.id),
- 'BspRadiotimer_'+str(self.id),
- 'BspRadio_'+str(self.id),
- 'BspUart_'+str(self.id),
- ]:
- temp = logging.getLogger(loggerName)
- temp.setLevel(logging.DEBUG)
- temp.addHandler(self.loghandler)
-
- # initialize parent class
- threading.Thread.__init__(self)
-
- # set thread name
- self.setName('MoteHandler_'+str(self.id))
-
- # thread daemon mode
- self.setDaemon(True)
-
- def run(self):
-
- # log
- self.log.info('starting')
-
- while(1):
- # wait for a command
- try:
- input = self.conn.recv(TCPRXBUFSIZE)
- except socket.error as err:
- self.log.critical('connection error (err='+str(err)+')')
- break
-
- # make sure I received something
- assert(len(input)>0)
-
- # handle the received packet
- self._handleReceivedCommand(input)
-
- #======================== public ==========================================
-
- def getId(self):
- return self.id
-
- def getLocation(self):
- return self.location
-
- def sendCommand(self,commandId,params=[]):
-
- # log
- self.log.debug('sending command='+self._cmdIdToName(commandId))
-
- # update statistics
- self.numTxCommands += 1
-
- # send command over connection
- dataToSend = ''
- dataToSend += chr(commandId)
- for c in params:
- dataToSend += chr(c)
- self.conn.sendall(dataToSend)
-
- #======================== private =========================================
-
- def _handleReceivedCommand(self,input):
-
- # get the command id and params from the received command
- cmdId = ord(input[0])
- params = input[1:]
-
- # log
- self.log.debug('received command='+self._cmdIdToName(cmdId))
-
- # update statistics
- self.numRxCommands += 1
-
- # make sure I know what callback to call
- assert(cmdId in self.commandCallbacks)
-
- # call the callback
- try:
- returnVal = self.commandCallbacks[cmdId](params)
- except Exception as err:
- self.log.critical(str(err))
- self.engine.pause()
- raise
-
- def _cmdIdToName(self,cmdId):
- cmdName = 'unknow'
- for k,v in self.commandIds.items():
- if cmdId==v:
- cmdName = k
- break
- return cmdName
\ No newline at end of file
diff --git a/software/opensim/SimEngine/Propagation.py b/software/opensim/SimEngine/Propagation.py
deleted file mode 100644
index 422ca26a3..000000000
--- a/software/opensim/SimEngine/Propagation.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-
-import logging
-
-class NullLogHandler(logging.Handler):
- def emit(self, record):
- pass
-
-class Propagation(object):
- '''
- \brief The propagation model of the engine.
- '''
-
- def __init__(self,engine):
-
- # store params
- self.engine = engine
-
- # local variables
-
- # logging
- self.log = logging.getLogger('Propagation')
- self.log.setLevel(logging.DEBUG)
- self.log.addHandler(NullLogHandler())
-
- #======================== public ==========================================
-
- def txStart(self,moteId,packet,channel):
-
- # log
- self.log.info('txStart from {0} on channel {1}, {2} bytes'.format(
- moteId,
- channel,
- len(packet)))
-
- # TODO: calculate rssi
-
- # indicate to each mote
- for i in range(self.engine.getNumMotes()):
- motehandler = self.engine.getMoteHandler(i)
- if motehandler.getId()!=moteId:
- motehandler.bspRadio.indicateTxStart(moteId,packet,channel)
-
- def txEnd(self,moteId):
-
- # log
- self.log.info('txStop from {0}'.format(moteId))
-
- # indicate to each mote
- for i in range(self.engine.getNumMotes()):
- motehandler = self.engine.getMoteHandler(i)
- if motehandler.getId()!=moteId:
- motehandler.bspRadio.indicateTxEnd(moteId)
-
- #======================== private =========================================
-
- #======================== helpers =========================================
-
\ No newline at end of file
diff --git a/software/opensim/SimEngine/opensim_proto.py b/software/opensim/SimEngine/opensim_proto.py
deleted file mode 100644
index dcbc21b94..000000000
--- a/software/opensim/SimEngine/opensim_proto.py
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/usr/bin/python
-
-import threading
-import socket
-import logging
-import os
-import time
-
-from BspEmulator import BspBoard
-from BspEmulator import BspBsp_timer
-from BspEmulator import BspDebugpins
-from BspEmulator import BspEui64
-from BspEmulator import BspLeds
-from BspEmulator import BspRadio
-from BspEmulator import BspRadiotimer
-from BspEmulator import BspUart
-
-TCPRXBUFSIZE = 4096 # size of the TCP reception buffer
-
-class NullLogHandler(logging.Handler):
- def emit(self, record):
- pass
-
-class OpenSimProto(object):
- '''
- \brief Handle the connection of a mote.
- '''
-
- def __init__(self,conn,addr,port):
-
- # store params
- self.conn = conn
- self.addr = addr
- self.port = port
-
- # local variables
- self.waitingForReplySem = threading.Lock()
- self.waitingForReply = False
-
- # bsp components
- self.bspBoard = BspBoard.BspBoard()
- self.bspBsp_timer = BspBsp_timer.BspBsp_timer()
- self.bspDebugpins = BspDebugpins.BspDebugpins()
- self.bspEui64 = BspEui64.BspEui64()
- self.bspLeds = BspLeds.BspLeds()
- self.bspRadio = BspRadio.BspRadio()
- self.bspRadiotimer = BspRadiotimer.BspRadiotimer()
- self.bspUart = BspUart.BspUart()
-
- # logging
- self.log = logging.getLogger('MoteHandler')
- self.log.setLevel(logging.DEBUG)
- self.log.addHandler(NullLogHandler())
-
- # initialize parent class
- threading.Thread.__init__(self)
-
- # set thread name
- self.setName('MoteHandler')
-
- # thread daemon mode
- self.setDaemon(True)
-
- def run(self):
-
- # log
- self.log.info('starting')
-
- self.conn.send('poipoi')
-
- while(1):
- try:
- input = self.conn.recv(TCPRXBUFSIZE)
- except socket.error as err:
- self.log.critical('connection error (err='+str(err)+')')
- break
-
- self.log.info('received input='+str(input))
- if self.waitingForReply:
- self.log.debug('This is a reply.')
- self.response = input
- self.waitingForReplySem.release()
- else:
- self.log.debug('This is a response.')
- self._handleReceivedCommand(input)
-
- #======================== public ==========================================
-
- def sendCommand(send,dataToSend):
- self.conn.send(dataToSend)
- self.waitingForReply = True
- self.waitingForReplySem.acquire()
-
- #======================== private =========================================
-
- def _handleReceivedCommand(self,input):
- time.sleep(1)
-
- print ord(input[0])
-
- self.conn.send(chr(0))
\ No newline at end of file
diff --git a/software/opensim/bin/opensim_cli/opensim_cli.py b/software/opensim/bin/opensim_cli/opensim_cli.py
deleted file mode 100644
index fcca6b734..000000000
--- a/software/opensim/bin/opensim_cli/opensim_cli.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python
-
-import os
-import sys
-
-temp_path = sys.path[0]
-if temp_path:
- sys.path.insert(0, os.path.join(temp_path, '..', '..'))
-
-import logging
-import logging.handlers
-import binascii
-from SimEngine import SimEngine
-from SimCli import SimCli
-
-LOG_FORMAT = "%(asctime)s [%(name)s:%(levelname)s] %(message)s"
-
-#============================ logging =========================================
-
-logFileName = 'logs/opensim.log'
-loghandler = logging.handlers.RotatingFileHandler(logFileName,
- maxBytes=2000000,
- backupCount=5,
- mode='w')
-loghandler.setFormatter(logging.Formatter(LOG_FORMAT))
-
-#============================ main ============================================
-
-def main():
-
- # instantiate a SimEngine object
- simengine = SimEngine.SimEngine(loghandler)
- simengine.start()
-
- # instantiate the CLI interface
- cliHandler = SimCli.SimCli(simengine)
- cliHandler.start()
-
-if __name__ == "__main__":
- main()
diff --git a/software/opensim/bin/opensim_gui/opensim_gui.py b/software/opensim/bin/opensim_gui/opensim_gui.py
deleted file mode 100644
index 48014554d..000000000
--- a/software/opensim/bin/opensim_gui/opensim_gui.py
+++ /dev/null
@@ -1,42 +0,0 @@
-#!/usr/bin/python
-
-import os
-import sys
-
-temp_path = sys.path[0]
-if temp_path:
- sys.path.insert(0, os.path.join(temp_path, '..', '..'))
-
-import logging
-import logging.handlers
-import binascii
-from SimEngine import SimEngine
-
-from SimGui import SimGui
-from SimGui import SimWindow
-
-LOG_FORMAT = "%(asctime)s [%(name)s:%(levelname)s] %(message)s"
-
-#============================ logging =========================================
-
-logFileName = 'logs/opensim.log'
-loghandler = logging.handlers.RotatingFileHandler(logFileName,
- maxBytes=2000000,
- backupCount=5,
- mode='w')
-loghandler.setFormatter(logging.Formatter(LOG_FORMAT))
-
-#============================ main ============================================
-
-def main():
-
- # instantiate a SimEngine object
- simengine = SimEngine.SimEngine(loghandler)
- simengine.start()
-
- # instantiate the CLI interface
- guiHandler = SimGui.SimGui(simengine)
- guiHandler.start()
-
-if __name__ == "__main__":
- main()
diff --git a/software/opensim/opensim.session b/software/opensim/opensim.session
deleted file mode 100644
index 814cce06b..000000000
--- a/software/opensim/opensim.session
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/software/opensim/sim_version.py b/software/opensim/sim_version.py
deleted file mode 100644
index bb4fecdfb..000000000
--- a/software/opensim/sim_version.py
+++ /dev/null
@@ -1 +0,0 @@
-VERSION = (1, 0, 0)
\ No newline at end of file
diff --git a/software/openvisualizer/EventBus/Event.py b/software/openvisualizer/EventBus/Event.py
deleted file mode 100644
index b6674d9a0..000000000
--- a/software/openvisualizer/EventBus/Event.py
+++ /dev/null
@@ -1,43 +0,0 @@
-'''
-Created on 24/08/2012
-
-@author: xvilajosana
-'''
-class Event:
- '''
- \brief Representation of an event, in the event bus.
-
- Events are used to queue them up when emitted synchronously.
- '''
- def __init__(self, uri, args, minNumReceivers=None, maxNumReceivers=None):
- '''
- \brief Initializer.
-
- \param uri The URI of the signal (a string). Can be a regular
- expression.
- \param args Any arguments to be passed to the listeners.
- '''
- self._uri = uri
- self._args = args
- self._minNumReceivers = minNumReceivers
- self._maxNumReceivers = maxNumReceivers
-
- def get_uri(self):
- return self._uri
-
- def get_args(self):
- return self._args
-
- def get_minNumReceivers(self):
- return self._minNumReceivers
-
- def get_maxNumReceivers(self):
- return self._maxNumReceivers
-
- def __str__(self):
- returnVal = []
- returnVal += ['uri={0}'.format(self._uri)]
- returnVal += ['args={0}'.format(self._args)]
- returnVal += ['minNumReceivers={0}'.format(self._minNumReceivers)]
- returnVal += ['maxNumReceivers={0}'.format(self._maxNumReceivers)]
- return ' '.join(returnVal)
\ No newline at end of file
diff --git a/software/openvisualizer/EventBus/EventBus.py b/software/openvisualizer/EventBus/EventBus.py
deleted file mode 100644
index 62b02ba79..000000000
--- a/software/openvisualizer/EventBus/EventBus.py
+++ /dev/null
@@ -1,365 +0,0 @@
-'''
-Created on 24/08/2012
-
-@author: xvilajosana
-'''
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('EventBus')
-log.setLevel(logging.DEBUG)
-log.addHandler(NullHandler())
-
-import sys
-import threading
-import time
-import copy
-import json
-
-import Subscription
-import Event
-
-class EventBus(threading.Thread):
- '''
- \brief An event bus to which modules can publish/subscribe.
-
- It is implemented as a singleton, i.e. only one instance of the eventBus
- lives in the system. This means that separate modules can instantiate this
- class independently and publish/subscribe to the result of that
- instantiation.
- '''
- _instance = None
- _init = False
-
- def __new__(cls, *args, **kwargs):
- '''
- \brief Override creation of the object so it is create only once
- (singleton pattern)
- '''
- if not cls._instance:
- cls._instance = super(EventBus, cls).__new__(cls, *args, **kwargs)
- return cls._instance
-
- def __init__(self):
- '''
- \brief Initializer.
-
- \note This function is called after __new__.
- '''
-
- if self._init:
- return
-
- # log
- log.debug("initialize instance")
-
- # intialize parent class
- threading.Thread.__init__(self)
-
- # give this thread a name
- self.name = 'eventBus'
-
- # local variables
- self._dataLock = threading.Lock()
- self._eventSem = threading.Semaphore(0)
- self._pending_events = [] ##< list of pending events
- self._subscriptions = {} ##< list of subscriptions
- self._next_id = 1 ##< index of a new element in _subscriptions
- self._init = True ##< this object was initialized
- self._stats = {}
-
- # start asynchronous handling
- self.start()
-
- def run(self):
- # log
- log.debug("thread running")
-
- try:
- while True:
-
- # block until at least one event is in the pending events
- self._eventSem.acquire()
-
- # pop the head event
- try:
- self._dataLock.acquire()
- event = self._pending_events.pop(0)
- finally:
- self._dataLock.release()
-
- if isinstance(event,Event.Event):
- # normal case
-
- # log
- log.debug("popped event {0} ".format(event))
-
- # publish
-
- self.publish_sync(event.get_uri(),
- *event.get_args(),
- minNumReceivers=event.get_minNumReceivers(),
- maxNumReceivers=event.get_maxNumReceivers())
-
- elif (instance(event,str)) and (event=='close'):
- # teardown case
-
- # log
- log.debug("...closed.")
-
- return
-
- else:
-
- # log
- log.critical("unexpected event={0}".format(event))
-
- raise SystemError()
- except Exception as err:
- log.critical(err)
- raise
-
- #======================== public ==========================================
-
- def subscribe(self, func, uri=None):
- '''
- \brief Adds a subscriber to the event bus.
-
- The given function pointer passed is called whenever an event is sent
- that matches the given regular expression. If no regular expression
- was given, the function is called for any emitted signal.
-
- \param func The function to call.
- \param uri The URI trigger this fuction to be called.
-
- \returns The unique identifier of this registration, an int. The caller
- can store and use that ID to unsubscribe.
- '''
-
- # log
- log.info("adding subscriber: {0} -> {1}".format(
- uri,
- func,
- )
- )
-
- # param validation
- assert callable(func)
- if uri:
- assert isinstance(uri,str)
-
- # create the Subscription instance
- subs = Subscription.Subscription(func,uri)
-
- # get a unique ID for that subscriber
- id = self._getNextId()
-
- # store subs
- try:
- self._dataLock.acquire()
- self._subscriptions[id] = subs
- finally:
- self._dataLock.release()
-
- return id
-
- def unsubscribe(self, id):
- '''
- \brief Removes a subscriber from the event bus.
-
- \param The id of the subscriber to remove, an int.
-
- \returns True if the subscriber was found (and removed).
- \returns False if the subscriber was not found.
- '''
-
- # param validation
- assert isinstance(id,int)
- assert id > 0
-
- try:
- self._dataLock.acquire()
- if id in self._subscriptions:
-
- # log
- log.info("removed subscriber id {0}".format(id))
-
- # delete
- del self._subscriptions[id]
-
- return True
-
- else:
-
- # log
- log.warning("could not find subscriber id {0} to remove".format(id))
-
- return False
-
- raise SystemError()
- finally:
- self._dataLock.release()
-
- def publish(self, uri, *args, **kwargs):
- '''
- \brief Publish an event.
-
- Publication is done asynchronously by the eventBus thread, i.e.
- sometimes after this function is called.
-
- \param uri The URI of the published event.
- \param args The arguments to pass to the callback function
- '''
- # log
- log.debug("publish uri={0} args={1} kwargs={2}".format(uri,args,kwargs))
-
- # param validation
- assert uri
- assert isinstance(uri,str)
- if 'minNumReceivers' in kwargs:
- assert isinstance(kwargs['minNumReceivers'],int)
- if 'maxNumReceivers' in kwargs:
- assert isinstance(kwargs['maxNumReceivers'],int)
-
- try:
- self._dataLock.acquire()
- self._pending_events.append(Event.Event(uri, args))
- self._eventSem.release()
- finally:
- self._dataLock.release()
-
- def publish_sync(self, uri, *args, **kwargs):
- '''
- \brief Publish an event synchronously.
-
- Publication is done before this function returns.
-
- \param uri The URI of the published event.
- \param args The arguments to pass to the callback function
- '''
- # log
- log.debug("publish_sync uri={0} args={1} kwargs={2}".format(uri,args,kwargs))
-
- # param validation
- assert uri
- assert isinstance(uri,str)
- if ('minNumReceivers' in kwargs) and kwargs['minNumReceivers']:
- assert isinstance(kwargs['minNumReceivers'],int)
- if ('maxNumReceivers' in kwargs) and kwargs['maxNumReceivers']:
- assert isinstance(kwargs['maxNumReceivers'],int)
-
- # update stats
- try:
- self._dataLock.acquire()
- if uri not in self._stats:
- self._stats[uri] = {
- 'numIn': 0,
- 'numOut': 0,
- }
- self._stats[uri]['numIn'] += 1
- finally:
- self._dataLock.release()
-
- # local variables
- self.numReceivers = 0
-
- # publish to subscribers
- try:
- self._dataLock.acquire()
- for (id,subs) in self._subscriptions.items():
- if subs.matches_uri(uri):
- subs.get_function()(*args)
- self.numReceivers += 1
- self._stats[uri]['numOut'] += self.numReceivers
- finally:
- self._dataLock.release()
-
- # ensure that number receivers is expected
- if ('minNumReceivers' in kwargs) and kwargs['minNumReceivers']:
- if self.numReceiverskwargs['maxNumReceivers']:
- raise SystemError('expected a most {0} receivers for event {1}, got {2}'.format(
- kwargs['maxNumReceivers'],
- uri,
- self.numReceivers,
- )
- )
-
- def getSubscriptions(self):
- '''
- \brief Retrieve the current list of subscriptions.
-
- \returns The current list of subscriptions, as a dictionary of
- dictionaries:
-
- returnVal = {
- 1: {
- 'uri': 'someURI'
- 'function': cb_function
- },
- etc.
- }
-
- '''
- returnVal = {}
- try:
- self._dataLock.acquire()
- for (id,subs) in self._subscriptions.items():
- returnVal[id] = {
- 'uri': subs.get_event_uri(),
- 'function': subs.get_function(),
- }
- finally:
- self._dataLock.release()
- return returnVal
-
- def getStats(self):
- try:
- self._dataLock.acquire()
- tempStats = copy.deepcopy(self._stats)
- finally:
- self._dataLock.release()
-
- returnVal = []
- for (k,v) in tempStats.items():
- returnVal.append({
- 'uri': k,
- 'numIn': v['numIn'],
- 'numOut': v['numOut'],
- })
- return json.dumps(returnVal,sort_keys=True,indent=4)
-
- def close(self):
- '''
- \brief Destroy this eventBus.
-
- \note This also stops the thread.
- '''
-
- # log
- log.debug("closing...")
-
- self._pending_events.append('close')
- self._eventSem.release()
-
- #======================== private =========================================
-
- def _getNextId(self):
- assert self._next_id < sys.maxint
-
- try:
- self._dataLock.acquire()
- retunVal = self._next_id
- self._next_id += 1
- finally:
- self._dataLock.release()
-
- return retunVal
diff --git a/software/openvisualizer/EventBus/Subscription.py b/software/openvisualizer/EventBus/Subscription.py
deleted file mode 100644
index 94ad2eee6..000000000
--- a/software/openvisualizer/EventBus/Subscription.py
+++ /dev/null
@@ -1,50 +0,0 @@
-'''
-Created on 24/08/2012
-
-@author: xvilajosana
-'''
-import re
-
-class Subscription:
- '''
- \brief Representation of an Subscription, in the event bus.
-
- This object contains both the URI and the function to call.
- '''
-
- def __init__(self, func, event_uri):
- '''
- \param func The function to be called when the event is sent.
- \param event_uri The URI of the signal (a string). Can be a regular
- expression.
- '''
- # validate params
- assert func
- assert callable(func)
- if event_uri:
- assert isinstance(event_uri,str)
-
- # store params
- self._func = func
- self._event_uri = event_uri
-
- # local variables
- self._event_re = None
- if event_uri:
- self._event_re = re.compile(event_uri)
-
- #======================== public ==========================================
-
- def get_function(self):
- return self._func
-
- def get_event_uri(self):
- return self._event_uri
-
- def matches_uri(self, uri):
- assert uri
- assert isinstance(uri,str)
-
- if self._event_re is None:
- return True
- return self._event_re.match(uri)
\ No newline at end of file
diff --git a/software/openvisualizer/EventBus/unit_tests/test_sync.py b/software/openvisualizer/EventBus/unit_tests/test_sync.py
deleted file mode 100644
index 23622464a..000000000
--- a/software/openvisualizer/EventBus/unit_tests/test_sync.py
+++ /dev/null
@@ -1,270 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import sys
-sys.path.insert(0, os.path.join(sys.path[0], '..'))
-
-import time
-import pprint
-import logging
-import logging.handlers
-
-import pytest
-
-import EventBus
-
-#============================ logging =========================================
-
-LOGFILE_NAME = 'test_sync.log'
-
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('test_sync')
-log.setLevel(logging.ERROR)
-log.addHandler(NullHandler())
-
-logHandler = logging.handlers.RotatingFileHandler(LOGFILE_NAME,
- backupCount=5,
- mode='w')
-logHandler.setFormatter(logging.Formatter("%(asctime)s [%(name)s:%(levelname)s] %(message)s"))
-for loggerName in ['test_sync',
- 'EventBus',]:
- temp = logging.getLogger(loggerName)
- temp.setLevel(logging.DEBUG)
- temp.addHandler(logHandler)
-
-#============================ helpers =========================================
-
-class Subscriber(object):
- def __init__(self,name):
- self.name = name
- self.resetNotifications()
-
- def notification_singleText(self,publishedText):
-
- # log
- log.debug("{0} notification_singleText publishedText={1}".format(self.name,
- publishedText))
-
- assert isinstance(publishedText,str)
-
- self.notifications['text'].append(publishedText)
-
- def notification_doubleNum(self,num1,num2):
-
- # log
- log.debug("{0} notification_doubleNum num1={1} num2={2}".format(
- self.name,
- num1,
- num2))
-
- assert isinstance(num1,int)
- assert isinstance(num2,int)
-
- self.notifications['num'].append((num1,num2))
-
- def resetNotifications(self):
- self.notifications = {
- 'text': [],
- 'num': [],
- }
-
-def prettyformat(dataToPrint):
- pp = pprint.PrettyPrinter(indent=4)
- return pp.pformat(dataToPrint)
-
-#============================ tests ===========================================
-
-global subscriber1
-global subscriber2
-
-#----- setup
-
-def test_setup():
- global bus
- global subscriber1
- global subscriber2
-
- log.debug("\n\n----------test_setup")
-
- bus = EventBus.EventBus()
-
- assert bus
- assert isinstance(bus,EventBus.EventBus)
- assert bus.getSubscriptions()=={}
-
-#---- subscription
-
-def test_subscribe_both():
- global subscriber1
- global subscriber2
-
- log.debug("\n\n----------test_subscribe_both")
-
- subscriber1 = Subscriber('subscriber1')
- subscriber2 = Subscriber('subscriber2')
-
- EventBus.EventBus().subscribe(subscriber1.notification_singleText,'text')
- EventBus.EventBus().subscribe(subscriber1.notification_doubleNum,'num')
- EventBus.EventBus().subscribe(subscriber2.notification_singleText,'text')
- EventBus.EventBus().subscribe(subscriber2.notification_doubleNum,'num')
-
- # log
- log.debug(prettyformat(bus.getSubscriptions()))
-
- assert len(bus.getSubscriptions().keys())==4
-
-#---- text publication
-
-def test_publishText_sync_both():
- global subscriber1
- global subscriber2
-
- log.debug("\n\n----------test_publishText_sync_both")
-
- EventBus.EventBus().publish_sync('text','someText1')
-
- # log
- log.debug(prettyformat(subscriber1.notifications))
- log.debug(prettyformat(subscriber2.notifications))
-
- assert subscriber1.notifications=={
- 'text': ['someText1'],
- 'num': [],
- }
- assert subscriber2.notifications=={
- 'text': ['someText1'],
- 'num': [],
- }
-
-def test_publishText_sync_both_again():
- global subscriber1
- global subscriber2
-
- log.debug("\n\n----------test_publishText_sync_both_again")
-
- EventBus.EventBus().publish_sync('text','someText2')
-
- # log
- log.debug(prettyformat(subscriber1.notifications))
- log.debug(prettyformat(subscriber2.notifications))
-
- assert subscriber1.notifications=={
- 'text': ['someText1','someText2'],
- 'num': [],
- }
- assert subscriber2.notifications=={
- 'text': ['someText1','someText2'],
- 'num': [],
- }
-
-def test_publishText_async_both():
- global subscriber1
- global subscriber2
-
- log.debug("\n\n----------test_publishText_async_both")
-
- EventBus.EventBus().publish('text','someText3')
-
- time.sleep(1) # longest possible time for thread to publish
-
- # log
- log.debug(prettyformat(subscriber1.notifications))
- log.debug(prettyformat(subscriber2.notifications))
-
- assert subscriber1.notifications=={
- 'text': ['someText1','someText2','someText3'],
- 'num': [],
- }
- assert subscriber2.notifications=={
- 'text': ['someText1','someText2','someText3'],
- 'num': [],
- }
-
-def test_publishText_async_both_again():
- global subscriber1
- global subscriber2
-
- log.debug("\n\n----------test_publishText_async_both_again")
-
- EventBus.EventBus().publish('text','someText4')
-
- time.sleep(1) # longest possible time for thread to publish
-
- # log
- log.debug(prettyformat(subscriber1.notifications))
- log.debug(prettyformat(subscriber2.notifications))
-
- assert subscriber1.notifications=={
- 'text': ['someText1','someText2','someText3','someText4'],
- 'num': [],
- }
- assert subscriber2.notifications=={
- 'text': ['someText1','someText2','someText3','someText4'],
- 'num': [],
- }
-
-def test_publishNum_sync_both():
- global subscriber1
- global subscriber2
-
- log.debug("\n\n----------test_publishNum_sync_both")
-
- EventBus.EventBus().publish_sync('num',1,2)
-
- # log
- log.debug(prettyformat(subscriber1.notifications))
- log.debug(prettyformat(subscriber2.notifications))
-
- assert subscriber1.notifications=={
- 'text': ['someText1','someText2','someText3','someText4'],
- 'num': [(1,2)],
- }
- assert subscriber2.notifications=={
- 'text': ['someText1','someText2','someText3','someText4'],
- 'num': [(1,2)],
- }
-
-#---- unsubscription
-
-def test_unsubscription():
- global subscriber1
- global subscriber2
-
- log.debug("\n\n----------test_unsubscription")
-
- res = EventBus.EventBus().unsubscribe(3)
- assert res
- res = EventBus.EventBus().unsubscribe(4)
- assert res
-
- # log
- log.debug(prettyformat(EventBus.EventBus().getSubscriptions()))
-
- EventBus.EventBus().publish_sync('text','someText5')
- EventBus.EventBus().publish_sync('num',3,4)
-
- # log
- log.debug(prettyformat(subscriber1.notifications))
- log.debug(prettyformat(subscriber2.notifications))
-
- assert subscriber1.notifications=={
- 'text': ['someText1','someText2','someText3','someText4','someText5'],
- 'num': [(1,2),(3,4)],
- }
- assert subscriber2.notifications=={
- 'text': ['someText1','someText2','someText3','someText4'],
- 'num': [(1,2)],
- }
-
-#----- teardown
-
-def test_teardown():
- global subscriber1
- global subscriber2
-
- log.debug("\n\n----------test_teardown")
-
- EventBus.EventBus().close()
\ No newline at end of file
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/MANIFEST.in b/software/openvisualizer/PyDispatcher-2.0.3/MANIFEST.in
deleted file mode 100644
index 558c5d2ae..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/MANIFEST.in
+++ /dev/null
@@ -1,14 +0,0 @@
-include MANIFEST.in
-include license.txt
-include *.py
-recursive-include docs *.html
-recursive-include docs/images *.png
-recursive-include docs/style *.css
-recursive-include docs/pydoc *.html *.py
-recursive-include examples *.py
-
-recursive-include tests *.py
-
-global-exclude *.bat
-global-exclude ./CVS
-global-exclude .cvsignore
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/PKG-INFO b/software/openvisualizer/PyDispatcher-2.0.3/PKG-INFO
deleted file mode 100644
index b12cb4045..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/PKG-INFO
+++ /dev/null
@@ -1,27 +0,0 @@
-Metadata-Version: 1.0
-Name: PyDispatcher
-Version: 2.0.3
-Summary: Multi-producer-multi-consumer signal dispatching mechanism
-Home-page: http://pydispatcher.sourceforge.net
-Author: Mike C. Fletcher
-Author-email: pydispatcher-devel@lists.sourceforge.net
-License: BSD-style, see license.txt for details
-Description: Dispatcher mechanism for creating event models
-
- PyDispatcher is an enhanced version of Patrick K. O'Brien's
- original dispatcher.py module. It provides the Python
- programmer with a robust mechanism for event routing within
- various application contexts.
-
- Included in the package are the robustapply and saferef
- modules, which provide the ability to selectively apply
- arguments to callable objects and to reference instance
- methods using weak-references.
-
-Keywords: dispatcher,dispatch,pydispatch,event,signal,sender,receiver,propagate,multi-consumer,multi-producer,saferef,robustapply,apply
-Platform: Any
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
-Classifier: Topic :: Software Development :: Libraries :: Python Modules
-Classifier: Intended Audience :: Developers
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/PKG-INFO b/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/PKG-INFO
deleted file mode 100644
index b12cb4045..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/PKG-INFO
+++ /dev/null
@@ -1,27 +0,0 @@
-Metadata-Version: 1.0
-Name: PyDispatcher
-Version: 2.0.3
-Summary: Multi-producer-multi-consumer signal dispatching mechanism
-Home-page: http://pydispatcher.sourceforge.net
-Author: Mike C. Fletcher
-Author-email: pydispatcher-devel@lists.sourceforge.net
-License: BSD-style, see license.txt for details
-Description: Dispatcher mechanism for creating event models
-
- PyDispatcher is an enhanced version of Patrick K. O'Brien's
- original dispatcher.py module. It provides the Python
- programmer with a robust mechanism for event routing within
- various application contexts.
-
- Included in the package are the robustapply and saferef
- modules, which provide the ability to selectively apply
- arguments to callable objects and to reference instance
- methods using weak-references.
-
-Keywords: dispatcher,dispatch,pydispatch,event,signal,sender,receiver,propagate,multi-consumer,multi-producer,saferef,robustapply,apply
-Platform: Any
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
-Classifier: Topic :: Software Development :: Libraries :: Python Modules
-Classifier: Intended Audience :: Developers
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/SOURCES.txt b/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/SOURCES.txt
deleted file mode 100644
index c1e0d8ec1..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,35 +0,0 @@
-MANIFEST.in
-license.txt
-setup.py
-PyDispatcher.egg-info/PKG-INFO
-PyDispatcher.egg-info/SOURCES.txt
-PyDispatcher.egg-info/dependency_links.txt
-PyDispatcher.egg-info/top_level.txt
-docs/index.html
-docs/images/greypinstripe.png
-docs/pydoc/__init__.py
-docs/pydoc/builddocs.py
-docs/pydoc/pydispatch.__init__.html
-docs/pydoc/pydispatch.dispatcher.html
-docs/pydoc/pydispatch.errors.html
-docs/pydoc/pydispatch.html
-docs/pydoc/pydispatch.robust.html
-docs/pydoc/pydispatch.robustapply.html
-docs/pydoc/pydispatch.saferef.html
-docs/pydoc/pydoc2.py
-docs/pydoc/weakref.html
-docs/style/sitestyle.css
-examples/__init__.py
-examples/extra_args.py
-examples/hello_messages.py
-examples/simple_sample.py
-pydispatch/__init__.py
-pydispatch/dispatcher.py
-pydispatch/errors.py
-pydispatch/robust.py
-pydispatch/robustapply.py
-pydispatch/saferef.py
-tests/__init__.py
-tests/test_dispatcher.py
-tests/test_robustapply.py
-tests/test_saferef.py
\ No newline at end of file
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/dependency_links.txt b/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/dependency_links.txt
deleted file mode 100644
index 8b1378917..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/top_level.txt b/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/top_level.txt
deleted file mode 100644
index 62f5b70fc..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/PyDispatcher.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-pydispatch
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/docs/images/greypinstripe.png b/software/openvisualizer/PyDispatcher-2.0.3/docs/images/greypinstripe.png
deleted file mode 100644
index 006a3a3d6..000000000
Binary files a/software/openvisualizer/PyDispatcher-2.0.3/docs/images/greypinstripe.png and /dev/null differ
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/docs/index.html b/software/openvisualizer/PyDispatcher-2.0.3/docs/index.html
deleted file mode 100644
index 4123d0b91..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/docs/index.html
+++ /dev/null
@@ -1,263 +0,0 @@
-
-
-
-
- Python Dispatch Package
-
-
-
-
-
-
-
-
-
PyDispatcher
-
-
PyDispatcher provides the Python programmer
-with a multiple-producer-multiple-consumer signal-registration and
-routing infrastructure for use in multiple contexts. The
-mechanism
-of PyDispatcher started life as a highly rated recipe
-in the Python
-Cookbook. The project
-aims
-to include various enhancements to the recipe developed during use in
-various applications. It is primarily maintained by Mike Fletcher. A derivative
-of the project provides the Django web framework's "signal" system.
-
-
-
To be more concrete about what PyDispatcher does for you:
-
-
-
-
-
provides a centralized service for delivering messages to
-registered objects (in the local process). It allows you to
-register any number of functions (callable objects) which can receive
-signals from senders.
-
-
registration can be for all senders, particular sending
-objects, or "anonymous" messages (messages where the sender is None)
-
-
registration can be for any signal, or particular signals
-
a single signal will be delivered to all appropriate registered
-receivers, so that multiple registrations do not interfere with each
-other
-
-
-
there is no requirement for the sender or receiver to be
-dispatcher-aware. Any Python object save the None object can act
-as a sender, and any callable object can act as a receiver. There
-is no need to inherit from a particular class or provide a particular
-interface on the object.
-
-
the system uses weak references to receivers wherever possible
-
-
object lifetimes are not affected by PyDispatcher registrations
-(that is, when your object goes away, the registrations related to the
-object also go away).
-
-
references to common transient objects (in particular instance
-methods) are stored as compound weak references.
-
-
weak references can be disabled on a
-registration-by-registration basis
-
-
allows rich signal types, signals are simply hashable objects
-used to store and retrieve sub-tables, they are otherwise opaque to the
-dispatcher mechanism
-
allows sending more information when sending than any particular
-receiver can handle, dispatcher automatically culls those arguments
-which are not appropriate for the particular receiver. This
-allows registering very simple functions dealing with general messages,
-while still allowing natural passing of arguments to higher level
-functions.
-
-
-
-
The dispatcher mechanism is particularly useful when constructing
-Model-View-Controller style applications where it is not desirable to
-have the Model objects aware of the event model.
-
-
Acquisition and Installation
-
-
PyDispatcher is available as a standard Python distutils
-installation package from the Python Package Index (PyPI). To
-install, run:
-
-
-
pip install PyDispatcher
-
-
PyDispatcher does not include any binary packages, so there should
-be no issues in installation. PyDispatcher is maintained on the
-LaunchPad project in bzr. To help develop, check out the project
-like so:
-
-
bzr branch lp:~mcfletch/pydispatcher/working
-
-
You can either send a pull request via LaunchPad or email a
-patch-set via:
-
-
bzr send --mail-to=mcfletch@vrplumber.com
-
-
PyDispatcher represents one of the more involved
-usage patterns for Python weakref objects. We have discovered a few
-problems in weakref operation of which users of the package should be
-aware.
-
-
-
Python 2.2.2 (and
-earlier) weak reference implementations have a subtle bug
-in their weakref destructor code which can cause memory access errors
-(aka segfaults) on program shutdown. If you are using Python 2.2,
-it is strongly
-recommended that you use Python 2.2.3 or
-later
-when using PyDispatcher. Note that this will not address the
-following issue.
-
-
-
Python 2.3.2 (and earlier) has a different (even
-more subtle) bug
-in the weakref destructor code which, again, can cause segfaults.
-If you are using Python 2.3, it is strongly
-recommended that you use Python 2.3.3 or
-later
-when using PyDispatcher. This bug-fix will not be ported back to
-the Python 2.2.x branch, so if you are using Python 2.2.3 you may
-encounter this situation.
-
-
-
Documentation
-
-
You can find usage samples in the examples directory of the
-distribution. The dispatcher module's reference documentation is
-currently the major source of information regarding usage.
-
-
-
PyDispatcher welcomes contributions, suggestions, and feedback from
-users in the pydispatcher-dev mailing
-list.
-
Usage
-
To set up a function to receive signals:
-
from pydispatch import dispatcher SIGNAL = 'my-first-signal'
def handle_event( sender ): """Simple event handler""" print 'Signal was sent by', sender dispatcher.connect( handle_event, signal=SIGNAL, sender=dispatcher.Any )
-
The use of the Any object allows the handler to listen for messages
-from any Sender or to listen to Any message being sent. To send
-messages:
Signal was sent by <object object at 0x196a090> Signal was sent by {}
-
Handler Functions
-
Handler functions in PyDispatcher are relatively loose in their
-definition. A handler can simply declare the parameters it would
-like to receive and receive only those parameters when the signal is
-sent. The sender can include extra parameters for those handlers
-which require them without worrying about whether a more generic
-handler can accept them:
-
def handle_specific_event( sender, moo ): """Handle a simple event, requiring a "moo" parameter""" print 'Specialized event for %(sender)s moo=%(moo)r'%locals() dispatcher.connect( handle_specific_event, signal=SIGNAL2, sender=dispatcher.Any )
-
This connection requires that all senders of the particular signal
-send a "moo" parameter, but a handler that listens for all events and
-does not provide a "moo" parameter would silently ignore the sender
-having passed a "moo".
-
2 parameters are always available to handler functions if they would like to use them:
-
-
-
-
Parameter
-
-
Value
-
-
-
-
sender
-
-
Object from/for which the event was sent, can be dispatcher.Anonymous for anonymous signals
-
-
-
-
signal
-
-
Signal object used when sending
-
-
-
-
-
Positional arguments and named arguments are passed through, but if
-positional arguments are used, they will fill in the parameters of the
-receiver in order and cause conflicts if named parameters are specified
-which match their names. Generally it is advisable to use named
-arguments when defining sending messages.
-
Reworked pydispatcher providing plugin infrastructure including
-Twisted and PyQt specific support
-
-
-
-
Release Notes
-
-
-
-
Version 2.0.3
-
-
Support for Python 3.2 (via 2to3) added, Python 2.x is still
-the primary development target
-
-
-
Version 2.0.2
-
-
Further packaging fixes.
-
-
-
Version 2.0.1 (this version and all previous versions are
-available from the old SourceForge
-project)
-
-
-
Packaging fixes to allow for easy_install based installation
-
-
Version 2.0.0
-
-
Renames the top-level package to "pydispatch" to avoid
-conflicts with common conflicting "dispatch" module.
-
-
Version 1.0.3
-
-
Add "robust" module with single function sendRobust, which
-catches errors during callbacks and returns the error instances instead
-of propagating the error
-
Patch bug in SafeRef deletion where traceback module has
-already been deleted by interpreter shutdown
-
Patch bug in _removeReceiver where sendersBack has already been
-deleted by interpreter shutdown
-
Make SafeRef pre-cache method name to allow for repr after
-cleanup of the method
-
-
Version 1.0.2
-
-
Fixes another memory leak, again wrt the back-reference table
-
-
-
Version 1.0.1
-
-
Fixes 2 memory leaks, one regarding the back-reference table
-for receivers, the other being a failure to register all receivers
-beyond the first for deletion
-
-
Version 1.0.0
-
-
Initial SourceForge release with restructured codebase
-
-
-
-
-
A SourceForge Open-Source project:
-
-
\ No newline at end of file
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/docs/pydoc/__init__.py b/software/openvisualizer/PyDispatcher-2.0.3/docs/pydoc/__init__.py
deleted file mode 100644
index 02576fcfe..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/docs/pydoc/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-"""pydoc documentation system with enhancements and automatic local builder
-
-This package is based on the standard pydoc package,
-with a few minor enhancements, and a slightly modified
-format. An automatic mechanism for generating extensive
-documentation for the OpenGLContext project is provided.
-"""
\ No newline at end of file
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/docs/pydoc/builddocs.py b/software/openvisualizer/PyDispatcher-2.0.3/docs/pydoc/builddocs.py
deleted file mode 100644
index d53bf89dd..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/docs/pydoc/builddocs.py
+++ /dev/null
@@ -1,26 +0,0 @@
-#! /usr/bin/env python
-"""Script to automatically generate OpenGLContext documentation"""
-import pydoc2
-
-if __name__ == "__main__":
- excludes = [
- "math",
- "string",
- ]
- stops = [
- "OpenGL.Demo.NeHe",
- "OpenGL.Demo.GLE",
- "OpenGL.Demo.da",
- ]
-
- modules = [
- "pydispatch",
- "weakref",
- ]
- pydoc2.PackageDocumentationGenerator(
- baseModules = modules,
- destinationDirectory = ".",
- exclusions = excludes,
- recursionStops = stops,
- ).process ()
-
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/docs/pydoc/pydispatch.__init__.html b/software/openvisualizer/PyDispatcher-2.0.3/docs/pydoc/pydispatch.__init__.html
deleted file mode 100644
index 1e4bc6ada..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/docs/pydoc/pydispatch.__init__.html
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-Python: module pydispatch.__init__
-
-
-
Multiple-producer-multiple-consumer signal-dispatching
-
-dispatcher is the core of the PyDispatcher system,
-providing the primary API and the core logic for the
-system.
-
-Module attributes of note:
-
- Any -- Singleton used to signal either "Any Sender" or
- "Any Signal". See documentation of the _Any class.
- Anonymous -- Singleton used to signal "Anonymous Sender"
- See documentation of the _Anonymous class.
-
-Internal attributes:
- WEAKREF_TYPES -- tuple of types/classes which represent
- weak references to receivers, and thus must be de-
- referenced on retrieval to retrieve the callable
- object
- connections -- { senderkey (id) : { signal : [receivers...]}}
- senders -- { senderkey (id) : weakref(sender) }
- used for cleaning up sender references on sender
- deletion
- sendersBack -- { receiverkey (id) : [senderkey (id)...] }
- used for cleaning up receiver references on receiver
- deletion, (considerably speeds up the cleanup process
- vs. the original code.)
Singleton used to signal "Anonymous Sender"
-
-The Anonymous object is used to signal that the sender
-of a message is not specified (as distinct from being
-"any sender"). Registering callbacks for Anonymous
-will only receive messages sent without senders. Sending
-with anonymous will only send messages to those receivers
-registered for Any or Anonymous.
-
-Note:
- The default sender for connect is Any, while the
- default sender for send is Anonymous. This has
- the effect that if you do not specify any senders
- in either function then all messages are routed
- as though there was a single sender (Anonymous)
- being used everywhere.
Singleton used to signal either "Any Sender" or "Any Signal"
-
-The Any object can be used with connect, disconnect,
-send, or sendExact to signal that the parameter given
-Any should react to all senders/signals, not just
-a particular sender/signal.
Kill old sendersBack references from receiver
-
-This guards against multiple registration of the same
-receiver for a given signal and sender leaking memory
-as old back reference records build up.
-
-Also removes old receiver instance from receivers
Connect receiver to sender for signal
-
-receiver -- a callable Python object which is to receive
- messages/signals/events. Receivers must be hashable
- objects.
-
- if weak is True, then receiver must be weak-referencable
- (more precisely saferef.safeRef() must be able to create
- a reference to the receiver).
-
- Receivers are fairly flexible in their specification,
- as the machinery in the robustApply module takes care
- of most of the details regarding figuring out appropriate
- subsets of the sent arguments to apply to a given
- receiver.
-
- Note:
- if receiver is itself a weak reference (a callable),
- it will be de-referenced by the system's machinery,
- so *generally* weak references are not suitable as
- receivers, though some use might be found for the
- facility whereby a higher-level library passes in
- pre-weakrefed receiver references.
-
-signal -- the signal to which the receiver should respond
-
- if Any, receiver will receive any signal from the
- indicated sender (which might also be Any, but is not
- necessarily Any).
-
- Otherwise must be a hashable Python object other than
- None (DispatcherError raised on None).
-
-sender -- the sender to which the receiver should respond
-
- if Any, receiver will receive the indicated signals
- from any sender.
-
- if Anonymous, receiver will only receive indicated
- signals from send/sendExact which do not specify a
- sender, or specify Anonymous explicitly as the sender.
-
- Otherwise can be any python object.
-
-weak -- whether to use weak references to the receiver
- By default, the module will attempt to use weak
- references to the receiver objects. If this parameter
- is false, then strong references will be used.
-
-returns None, may raise DispatcherTypeError
Disconnect receiver from sender for signal
-
-receiver -- the registered receiver to disconnect
-signal -- the registered signal to disconnect
-sender -- the registered sender to disconnect
-weak -- the weakref state to disconnect
-
-disconnect reverses the process of connect,
-the semantics for the individual elements are
-logically equivalent to a tuple of
-(receiver, signal, sender, weak) used as a key
-to be deleted from the internal routing tables.
-(The actual process is slightly more complex
-but the semantics are basically the same).
-
-Note:
- Using disconnect is not required to cleanup
- routing when an object is deleted, the framework
- will remove routes for deleted objects
- automatically. It's only necessary to disconnect
- if you want to stop routing to a live object.
-
-returns None, may raise DispatcherTypeError or
- DispatcherKeyError
Get list of all receivers from global tables
-
-This gets all receivers which should receive
-the given signal from sender, each receiver should
-be produced only once by the resulting generator
Get list of receivers from global tables
-
-This utility function allows you to retrieve the
-raw list of receivers from the connections table
-for the given sender and signal pair.
-
-Note:
- there is no guarantee that this is the actual list
- stored in the connections table, so the value
- should be treated as a simple iterable/truth value
- rather than, for instance a list to which you
- might append new records.
-
-Normally you would use liveReceivers( getReceivers( ...))
-to retrieve the actual receiver objects as an iterable
-object.
Filter sequence of receivers to get resolved, live receivers
-
-This is a generator which will iterate over
-the passed sequence, checking for weak references
-and resolving them, then returning all live
-receivers.
Send signal from sender to all connected receivers.
-
-signal -- (hashable) signal value, see connect for details
-
-sender -- the sender of the signal
-
- if Any, only receivers registered for Any will receive
- the message.
-
- if Anonymous, only receivers registered to receive
- messages from Anonymous or Any will receive the message
-
- Otherwise can be any python object (normally one
- registered with a connect if you actually want
- something to occur).
-
-arguments -- positional arguments which will be passed to
- *all* receivers. Note that this may raise TypeErrors
- if the receivers do not allow the particular arguments.
- Note also that arguments are applied before named
- arguments, so they should be used with care.
-
-named -- named arguments which will be filtered according
- to the parameters of the receivers to only provide those
- acceptable to the receiver.
-
-Return a list of tuple pairs [(receiver, response), ... ]
-
-if any receiver raises an error, the error propagates back
-through send, terminating the dispatch loop, so it is quite
-possible to not have all receivers called if a raises an
-error.
Send signal only to those receivers registered for exact message
-
-sendExact allows for avoiding Any/Anonymous registered
-handlers, sending only to those receivers explicitly
-registered for a particular signal on a particular
-sender.
Send signal from sender to all connected receivers catching errors
-
-signal -- (hashable) signal value, see connect for details
-
-sender -- the sender of the signal
-
- if Any, only receivers registered for Any will receive
- the message.
-
- if Anonymous, only receivers registered to receive
- messages from Anonymous or Any will receive the message
-
- Otherwise can be any python object (normally one
- registered with a connect if you actually want
- something to occur).
-
-arguments -- positional arguments which will be passed to
- *all* receivers. Note that this may raise TypeErrors
- if the receivers do not allow the particular arguments.
- Note also that arguments are applied before named
- arguments, so they should be used with care.
-
-named -- named arguments which will be filtered according
- to the parameters of the receivers to only provide those
- acceptable to the receiver.
-
-Return a list of tuple pairs [(receiver, response), ... ]
-
-if any receiver raises an error (specifically any subclass of Exception),
-the error instance is returned as the result for that receiver.
Robust apply mechanism
-
-Provides a function "call", which can sort out
-what arguments a given callable object can take,
-and subset the given arguments to match only
-those which are acceptable.
Get function-like callable object for given receiver
-
-returns (function_or_method, codeObject, fromMethod)
-
-If fromMethod is true, then the callable already
-has its first argument bound
'Safe' and reusable weak references to instance methods
-
-BoundMethodWeakref objects provide a mechanism for
-referencing a bound method without requiring that the
-method object itself (which is normally a transient
-object) is kept alive. Instead, the BoundMethodWeakref
-object keeps weak references to both the object and the
-function which together define the instance method.
-
-Attributes:
- key -- the identity key for the reference, calculated
- by the class's calculateKey method applied to the
- target instance method
- deletionMethods -- sequence of callable objects taking
- single argument, a reference to this object which
- will be called when *either* the target object or
- target function is garbage collected (i.e. when
- this object becomes invalid). These are specified
- as the onDelete parameters of safeRef calls.
- weakSelf -- weak reference to the target object
- weakFunc -- weak reference to the target function
-
-Class Attributes:
- _allInstances -- class attribute pointing to all live
- BoundMethodWeakref objects indexed by the class's
- calculateKey(target) method applied to the target
- objects. This weak value dictionary is used to
- short-circuit creation so that multiple references
- to the same (object, function) pair produce the
- same BoundMethodWeakref instance.
Return a strong reference to the bound method
-
-If the target cannot be retrieved, then will
-return None, otherwise returns a bound instance
-method for our object and function.
-
-Note:
- You may call this method any number of times,
- as it does not invalidate the reference.
Return a weak-reference-like instance for a bound method
-
-target -- the instance-method target for the weak
- reference, must have <im_self> and <im_func> attributes
- and be reconstructable via:
- target.<im_func>.__get__( target.<im_self> )
- which is true of built-in instance methods.
-onDelete -- optional callback which will be called
- when this weak reference ceases to be valid
- (i.e. either the object or the function is garbage
- collected). Should take a single argument,
- which will be passed a pointer to this object.
Calculate the reference key for this reference
-
-Currently this is a two-tuple of the id()'s of the
-target object and the target function respectively.
Create new instance or return current instance
-
-Basically this method of construction allows us to
-short-circuit creation of references to already-
-referenced instance methods. The key corresponding
-to the target is calculated, and if there is already
-an existing reference, that is returned, with its
-deletionMethods attribute updated. Otherwise the
-new instance is created and registered in the table
-of already-referenced methods.
-
-
-Data descriptors defined here:
-
__dict__
-
dictionary for instance variables (if defined)
-
-
__weakref__
-
list of weak references to the object (if defined)
Return a *safe* weak reference to a callable target
-
-target -- the object to be weakly referenced, if it's a
- bound method reference, will create a BoundMethodWeakref,
- otherwise creates a simple weakref.
-onDelete -- if provided, will have a hard reference stored
- to the callable to be called after the safe reference
- goes out of scope with the reference object, (either a
- weakref or a BoundMethodWeakref) as argument.
Specialized reference that includes a key corresponding to the value.
-
-This is used in the WeakValueDictionary to avoid having to create
-a function object for each key stored in the mapping. A shared
-callback object can use the 'key' attribute of a KeyedRef instead
-of getting a reference to the key from an enclosing scope.
Mapping class that references keys weakly.
-
-Entries in the dictionary will be discarded when there is no
-longer a strong reference to the key. This can be used to
-associate additional data with an object owned by other parts of
-an application without adding attributes to those objects. This
-can be especially useful with objects that override attribute
-accesses.
Return an iterator that yields the weak references to the keys.
-
-The references are not guaranteed to be 'live' at the time
-they are used, so the result of calling the references needs
-to be checked before being used. This can be used to avoid
-creating references that will cause the garbage collector to
-keep the keys around longer than needed.
Return a list of weak references to the keys.
-
-The references are not guaranteed to be 'live' at the time
-they are used, so the result of calling the references needs
-to be checked before being used. This can be used to avoid
-creating references that will cause the garbage collector to
-keep the keys around longer than needed.
Return an iterator that yields the weak references to the values.
-
-The references are not guaranteed to be 'live' at the time
-they are used, so the result of calling the references needs
-to be checked before being used. This can be used to avoid
-creating references that will cause the garbage collector to
-keep the values around longer than needed.
Return a list of weak references to the values.
-
-The references are not guaranteed to be 'live' at the time
-they are used, so the result of calling the references needs
-to be checked before being used. This can be used to avoid
-creating references that will cause the garbage collector to
-keep the values around longer than needed.
proxy(object[, callback]) -- create a proxy object that weakly
-references 'object'. 'callback', if given, is called with a
-reference to the proxy when 'object' is about to be finalized.
-
\ No newline at end of file
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/docs/style/sitestyle.css b/software/openvisualizer/PyDispatcher-2.0.3/docs/style/sitestyle.css
deleted file mode 100644
index 051defdb5..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/docs/style/sitestyle.css
+++ /dev/null
@@ -1,59 +0,0 @@
-h1,h2,h3 {
- color: #111144;
- background-image: url(../images/greypinstripe.png);
- border-top-style: solid;
- border-top-width: 1
-}
-.footer {
- color: #111144;
- background-image: url(../images/greypinstripe.png);
- text-align: center;
- border-bottom-style: solid;
- border-bottom-width: 1
-}
-th {
- color: #111144;
- background-image: url(../images/greypinstripe.png);
- text-align: center;
-}
-.introduction {
- margin-left: 60;
- margin-right: 60;
- color: #555555;
-}
-.technical {
- margin-left: 60;
- margin-right: 60;
- color: #557755;
-}
-p {
- margin-left: 10;
- margin-right: 10;
-}
-ul {
- margin-left: 30;
-}
-pre {
- background-color: #ffffcc;
- margin-left: 60;
-}
-blockquote {
- margin-left: 90;
-}
-body {
- background-color: #FFFFFF;
- color: #000000;
- font-family: Arial, Helvetica;
-}
-a:link {
- color: #3333e0;
- text-decoration: none;
-}
-a:visited {
- color: #1111aa;
- text-decoration: none;
-}
-a:active {
- color: #111133;
- text-decoration: none;
-}
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/examples/__init__.py b/software/openvisualizer/PyDispatcher-2.0.3/examples/__init__.py
deleted file mode 100644
index 393933cb8..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/examples/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-"""Example scripts for the dispatch project
-"""
-
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/examples/extra_args.py b/software/openvisualizer/PyDispatcher-2.0.3/examples/extra_args.py
deleted file mode 100644
index 19ff6d427..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/examples/extra_args.py
+++ /dev/null
@@ -1,23 +0,0 @@
-#! /usr/bin/env python
-from pydispatch import dispatcher
-SIGNAL = 'my-first-signal'
-SIGNAL2 = 'my-second-signal'
-
-def handle_event( sender ):
- """Simple event handler"""
- print 'Signal was sent by', sender
-dispatcher.connect( handle_event, signal=SIGNAL, sender=dispatcher.Any )
-def handle_specific_event( sender, moo ):
- """Handle a simple event, requiring a "moo" parameter"""
- print 'Specialized event for %(sender)s moo=%(moo)r'%locals()
-dispatcher.connect( handle_specific_event, signal=SIGNAL2, sender=dispatcher.Any )
-
-first_sender = object()
-second_sender = {}
-def main( ):
- dispatcher.send( signal=SIGNAL, sender=first_sender )
- dispatcher.send( signal=SIGNAL, sender=second_sender )
- dispatcher.send( signal=SIGNAL2, sender=second_sender, moo='this' )
-
-if __name__ == "__main__":
- main()
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/examples/hello_messages.py b/software/openvisualizer/PyDispatcher-2.0.3/examples/hello_messages.py
deleted file mode 100644
index 92f7540ea..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/examples/hello_messages.py
+++ /dev/null
@@ -1,17 +0,0 @@
-#! /usr/bin/env python
-from pydispatch import dispatcher
-SIGNAL = 'my-first-signal'
-
-def handle_event( sender ):
- """Simple event handler"""
- print 'Signal was sent by', sender
-dispatcher.connect( handle_event, signal=SIGNAL, sender=dispatcher.Any )
-
-first_sender = object()
-second_sender = {}
-def main( ):
- dispatcher.send( signal=SIGNAL, sender=first_sender )
- dispatcher.send( signal=SIGNAL, sender=second_sender )
-
-if __name__ == "__main__":
- main()
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/examples/simple_sample.py b/software/openvisualizer/PyDispatcher-2.0.3/examples/simple_sample.py
deleted file mode 100644
index 7de3f40fb..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/examples/simple_sample.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""Simple sample showing basic usage pattern"""
-from pydispatch import dispatcher
-
-def doSomethingUseful( table, signal, sender ):
- """Sample method to receive signals"""
- print ' doSomethingUseful', repr(table), signal, sender
-def doSomethingElse( signal, **named ):
- """Sample method to receive signals
-
- This method demonstrates the use of the **named
- parameter, which allows a method to receive all
- remaining parameters from the send call.
- """
- print ' doSomethingElse', named
-def doDefault( ):
- """Sample method to receive All signals
-
- Note that this function will be registered for all
- signals from a given object. It does not have the
- same interface as any of the other functions
- registered for those signals. The system will
- automatically determine the appropriate calling
- signature for the function.
- """
- print ' doDefault (no arguments)'
-
-class Node(object):
- """Sample object to send signals, note lack of dispatcher-aware code"""
- def __init__( self, name="an object" ):
- self.name = name
- def __repr__( self ):
- return "%s( %r )"%( self.__class__.__name__, self.name )
-
-DO_LOTS = 0
-DO_SOMETHING = ('THIS','IS','A','MORE','COMPLEX','SIGNAL')
-DO_SOMETHING_ELSE = Node()
-
-ourObjects = [
- Node(),
- Node(),
- Node(),
-]
-if __name__ == "__main__":
- # Establish some "routing" connections
- dispatcher.connect (
- doSomethingUseful,
- signal = DO_LOTS,
- sender = ourObjects[0],
- )
- dispatcher.connect (
- doSomethingElse,
- signal = DO_SOMETHING,
- sender = ourObjects[0],
- )
- dispatcher.connect(
- doDefault,
- signal = dispatcher.Any, # this is actually the default,
- sender = ourObjects[0],
- )
- print "Sending DO_LOTS from first object"
- dispatcher.send(
- signal = DO_LOTS,
- sender = ourObjects[0],
- table = "Table Argument",
- )
- print "Sending DO_SOMETHING from first object"
- dispatcher.send(
- signal = DO_SOMETHING,
- sender = ourObjects[0],
- table = "Table Argument",
- )
- print "Sending DO_SOMETHING_ELSE from first object"
- dispatcher.send(
- signal = DO_SOMETHING_ELSE,
- sender = ourObjects[0],
- table = "Table Argument",
- )
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/license.txt b/software/openvisualizer/PyDispatcher-2.0.3/license.txt
deleted file mode 100644
index 0960a6073..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/license.txt
+++ /dev/null
@@ -1,34 +0,0 @@
-PyDispatcher License
-
- Copyright (c) 2001-2006, Patrick K. O'Brien and Contributors
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
-
- Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- The name of Patrick K. O'Brien, or the name of any Contributor,
- may not be used to endorse or promote products derived from this
- software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- OF THE POSSIBILITY OF SUCH DAMAGE.
-
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/__init__.py b/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/__init__.py
deleted file mode 100644
index b13f5f695..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-"""Multi-consumer multi-producer dispatching mechanism
-"""
-__version__ = "2.0.3"
-__author__ = "Patrick K. O'Brien"
-__license__ = "BSD-style, see license.txt for details"
-
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/dispatcher.py b/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/dispatcher.py
deleted file mode 100644
index e0e48473f..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/dispatcher.py
+++ /dev/null
@@ -1,492 +0,0 @@
-"""Multiple-producer-multiple-consumer signal-dispatching
-
-dispatcher is the core of the PyDispatcher system,
-providing the primary API and the core logic for the
-system.
-
-Module attributes of note:
-
- Any -- Singleton used to signal either "Any Sender" or
- "Any Signal". See documentation of the _Any class.
- Anonymous -- Singleton used to signal "Anonymous Sender"
- See documentation of the _Anonymous class.
-
-Internal attributes:
- WEAKREF_TYPES -- tuple of types/classes which represent
- weak references to receivers, and thus must be de-
- referenced on retrieval to retrieve the callable
- object
- connections -- { senderkey (id) : { signal : [receivers...]}}
- senders -- { senderkey (id) : weakref(sender) }
- used for cleaning up sender references on sender
- deletion
- sendersBack -- { receiverkey (id) : [senderkey (id)...] }
- used for cleaning up receiver references on receiver
- deletion, (considerably speeds up the cleanup process
- vs. the original code.)
-"""
-from __future__ import generators
-import weakref
-from pydispatch import saferef, robustapply, errors
-
-__author__ = "Patrick K. O'Brien "
-__cvsid__ = "$Id: dispatcher.py,v 1.1 2010/03/30 15:45:55 mcfletch Exp $"
-__version__ = "$Revision: 1.1 $"[11:-2]
-
-class _Parameter:
- """Used to represent default parameter values."""
- def __repr__(self):
- return self.__class__.__name__
-
-class _Any(_Parameter):
- """Singleton used to signal either "Any Sender" or "Any Signal"
-
- The Any object can be used with connect, disconnect,
- send, or sendExact to signal that the parameter given
- Any should react to all senders/signals, not just
- a particular sender/signal.
- """
-Any = _Any()
-
-class _Anonymous(_Parameter):
- """Singleton used to signal "Anonymous Sender"
-
- The Anonymous object is used to signal that the sender
- of a message is not specified (as distinct from being
- "any sender"). Registering callbacks for Anonymous
- will only receive messages sent without senders. Sending
- with anonymous will only send messages to those receivers
- registered for Any or Anonymous.
-
- Note:
- The default sender for connect is Any, while the
- default sender for send is Anonymous. This has
- the effect that if you do not specify any senders
- in either function then all messages are routed
- as though there was a single sender (Anonymous)
- being used everywhere.
- """
-Anonymous = _Anonymous()
-
-WEAKREF_TYPES = (weakref.ReferenceType, saferef.BoundMethodWeakref)
-
-connections = {}
-senders = {}
-sendersBack = {}
-
-
-def connect(receiver, signal=Any, sender=Any, weak=True):
- """Connect receiver to sender for signal
-
- receiver -- a callable Python object which is to receive
- messages/signals/events. Receivers must be hashable
- objects.
-
- if weak is True, then receiver must be weak-referencable
- (more precisely saferef.safeRef() must be able to create
- a reference to the receiver).
-
- Receivers are fairly flexible in their specification,
- as the machinery in the robustApply module takes care
- of most of the details regarding figuring out appropriate
- subsets of the sent arguments to apply to a given
- receiver.
-
- Note:
- if receiver is itself a weak reference (a callable),
- it will be de-referenced by the system's machinery,
- so *generally* weak references are not suitable as
- receivers, though some use might be found for the
- facility whereby a higher-level library passes in
- pre-weakrefed receiver references.
-
- signal -- the signal to which the receiver should respond
-
- if Any, receiver will receive any signal from the
- indicated sender (which might also be Any, but is not
- necessarily Any).
-
- Otherwise must be a hashable Python object other than
- None (DispatcherError raised on None).
-
- sender -- the sender to which the receiver should respond
-
- if Any, receiver will receive the indicated signals
- from any sender.
-
- if Anonymous, receiver will only receive indicated
- signals from send/sendExact which do not specify a
- sender, or specify Anonymous explicitly as the sender.
-
- Otherwise can be any python object.
-
- weak -- whether to use weak references to the receiver
- By default, the module will attempt to use weak
- references to the receiver objects. If this parameter
- is false, then strong references will be used.
-
- returns None, may raise DispatcherTypeError
- """
- if signal is None:
- raise errors.DispatcherTypeError(
- 'Signal cannot be None (receiver=%r sender=%r)'%( receiver,sender)
- )
- if weak:
- receiver = saferef.safeRef(receiver, onDelete=_removeReceiver)
- senderkey = id(sender)
- if senderkey in connections:
- signals = connections[senderkey]
- else:
- connections[senderkey] = signals = {}
- # Keep track of senders for cleanup.
- # Is Anonymous something we want to clean up?
- if sender not in (None, Anonymous, Any):
- def remove(object, senderkey=senderkey):
- _removeSender(senderkey=senderkey)
- # Skip objects that can not be weakly referenced, which means
- # they won't be automatically cleaned up, but that's too bad.
- try:
- weakSender = weakref.ref(sender, remove)
- senders[senderkey] = weakSender
- except:
- pass
-
- receiverID = id(receiver)
- # get current set, remove any current references to
- # this receiver in the set, including back-references
- if signal in signals:
- receivers = signals[signal]
- _removeOldBackRefs(senderkey, signal, receiver, receivers)
- else:
- receivers = signals[signal] = []
- try:
- current = sendersBack.get( receiverID )
- if current is None:
- sendersBack[ receiverID ] = current = []
- if senderkey not in current:
- current.append(senderkey)
- except:
- pass
-
- receivers.append(receiver)
-
-
-
-def disconnect(receiver, signal=Any, sender=Any, weak=True):
- """Disconnect receiver from sender for signal
-
- receiver -- the registered receiver to disconnect
- signal -- the registered signal to disconnect
- sender -- the registered sender to disconnect
- weak -- the weakref state to disconnect
-
- disconnect reverses the process of connect,
- the semantics for the individual elements are
- logically equivalent to a tuple of
- (receiver, signal, sender, weak) used as a key
- to be deleted from the internal routing tables.
- (The actual process is slightly more complex
- but the semantics are basically the same).
-
- Note:
- Using disconnect is not required to cleanup
- routing when an object is deleted, the framework
- will remove routes for deleted objects
- automatically. It's only necessary to disconnect
- if you want to stop routing to a live object.
-
- returns None, may raise DispatcherTypeError or
- DispatcherKeyError
- """
- if signal is None:
- raise errors.DispatcherTypeError(
- 'Signal cannot be None (receiver=%r sender=%r)'%( receiver,sender)
- )
- if weak: receiver = saferef.safeRef(receiver)
- senderkey = id(sender)
- try:
- signals = connections[senderkey]
- receivers = signals[signal]
- except KeyError:
- raise errors.DispatcherKeyError(
- """No receivers found for signal %r from sender %r""" %(
- signal,
- sender
- )
- )
- try:
- # also removes from receivers
- _removeOldBackRefs(senderkey, signal, receiver, receivers)
- except ValueError:
- raise errors.DispatcherKeyError(
- """No connection to receiver %s for signal %s from sender %s""" %(
- receiver,
- signal,
- sender
- )
- )
- _cleanupConnections(senderkey, signal)
-
-def getReceivers( sender = Any, signal = Any ):
- """Get list of receivers from global tables
-
- This utility function allows you to retrieve the
- raw list of receivers from the connections table
- for the given sender and signal pair.
-
- Note:
- there is no guarantee that this is the actual list
- stored in the connections table, so the value
- should be treated as a simple iterable/truth value
- rather than, for instance a list to which you
- might append new records.
-
- Normally you would use liveReceivers( getReceivers( ...))
- to retrieve the actual receiver objects as an iterable
- object.
- """
- try:
- return connections[id(sender)][signal]
- except KeyError:
- return []
-
-def liveReceivers(receivers):
- """Filter sequence of receivers to get resolved, live receivers
-
- This is a generator which will iterate over
- the passed sequence, checking for weak references
- and resolving them, then returning all live
- receivers.
- """
- for receiver in receivers:
- if isinstance( receiver, WEAKREF_TYPES):
- # Dereference the weak reference.
- receiver = receiver()
- if receiver is not None:
- yield receiver
- else:
- yield receiver
-
-
-
-def getAllReceivers( sender = Any, signal = Any ):
- """Get list of all receivers from global tables
-
- This gets all receivers which should receive
- the given signal from sender, each receiver should
- be produced only once by the resulting generator
- """
- receivers = {}
- for set in (
- # Get receivers that receive *this* signal from *this* sender.
- getReceivers( sender, signal ),
- # Add receivers that receive *any* signal from *this* sender.
- getReceivers( sender, Any ),
- # Add receivers that receive *this* signal from *any* sender.
- getReceivers( Any, signal ),
- # Add receivers that receive *any* signal from *any* sender.
- getReceivers( Any, Any ),
- ):
- for receiver in set:
- if receiver: # filter out dead instance-method weakrefs
- try:
- if receiver not in receivers:
- receivers[receiver] = 1
- yield receiver
- except TypeError:
- # dead weakrefs raise TypeError on hash...
- pass
-
-def send(signal=Any, sender=Anonymous, *arguments, **named):
- """Send signal from sender to all connected receivers.
-
- signal -- (hashable) signal value, see connect for details
-
- sender -- the sender of the signal
-
- if Any, only receivers registered for Any will receive
- the message.
-
- if Anonymous, only receivers registered to receive
- messages from Anonymous or Any will receive the message
-
- Otherwise can be any python object (normally one
- registered with a connect if you actually want
- something to occur).
-
- arguments -- positional arguments which will be passed to
- *all* receivers. Note that this may raise TypeErrors
- if the receivers do not allow the particular arguments.
- Note also that arguments are applied before named
- arguments, so they should be used with care.
-
- named -- named arguments which will be filtered according
- to the parameters of the receivers to only provide those
- acceptable to the receiver.
-
- Return a list of tuple pairs [(receiver, response), ... ]
-
- if any receiver raises an error, the error propagates back
- through send, terminating the dispatch loop, so it is quite
- possible to not have all receivers called if a raises an
- error.
- """
- # Call each receiver with whatever arguments it can accept.
- # Return a list of tuple pairs [(receiver, response), ... ].
- responses = []
- for receiver in liveReceivers(getAllReceivers(sender, signal)):
- response = robustapply.robustApply(
- receiver,
- signal=signal,
- sender=sender,
- *arguments,
- **named
- )
- responses.append((receiver, response))
- return responses
-def sendExact( signal=Any, sender=Anonymous, *arguments, **named ):
- """Send signal only to those receivers registered for exact message
-
- sendExact allows for avoiding Any/Anonymous registered
- handlers, sending only to those receivers explicitly
- registered for a particular signal on a particular
- sender.
- """
- responses = []
- for receiver in liveReceivers(getReceivers(sender, signal)):
- response = robustapply.robustApply(
- receiver,
- signal=signal,
- sender=sender,
- *arguments,
- **named
- )
- responses.append((receiver, response))
- return responses
-
-
-def _removeReceiver(receiver):
- """Remove receiver from connections."""
- if not sendersBack:
- # During module cleanup the mapping will be replaced with None
- return False
- backKey = id(receiver)
- try:
- backSet = sendersBack.pop(backKey)
- except KeyError:
- return False
- else:
- for senderkey in backSet:
- try:
- signals = connections[senderkey].keys()
- except KeyError:
- pass
- else:
- for signal in signals:
- try:
- receivers = connections[senderkey][signal]
- except KeyError:
- pass
- else:
- try:
- receivers.remove( receiver )
- except Exception:
- pass
- _cleanupConnections(senderkey, signal)
-
-def _cleanupConnections(senderkey, signal):
- """Delete any empty signals for senderkey. Delete senderkey if empty."""
- try:
- receivers = connections[senderkey][signal]
- except:
- pass
- else:
- if not receivers:
- # No more connected receivers. Therefore, remove the signal.
- try:
- signals = connections[senderkey]
- except KeyError:
- pass
- else:
- del signals[signal]
- if not signals:
- # No more signal connections. Therefore, remove the sender.
- _removeSender(senderkey)
-
-def _removeSender(senderkey):
- """Remove senderkey from connections."""
- _removeBackrefs(senderkey)
- try:
- del connections[senderkey]
- except KeyError:
- pass
- # Senderkey will only be in senders dictionary if sender
- # could be weakly referenced.
- try:
- del senders[senderkey]
- except:
- pass
-
-
-def _removeBackrefs( senderkey):
- """Remove all back-references to this senderkey"""
- try:
- signals = connections[senderkey]
- except KeyError:
- signals = None
- else:
- items = signals.items()
- def allReceivers( ):
- for signal,set in items:
- for item in set:
- yield item
- for receiver in allReceivers():
- _killBackref( receiver, senderkey )
-
-def _removeOldBackRefs(senderkey, signal, receiver, receivers):
- """Kill old sendersBack references from receiver
-
- This guards against multiple registration of the same
- receiver for a given signal and sender leaking memory
- as old back reference records build up.
-
- Also removes old receiver instance from receivers
- """
- try:
- index = receivers.index(receiver)
- # need to scan back references here and remove senderkey
- except ValueError:
- return False
- else:
- oldReceiver = receivers[index]
- del receivers[index]
- found = 0
- signals = connections.get(signal)
- if signals is not None:
- for sig,recs in connections.get(signal,{}).iteritems():
- if sig != signal:
- for rec in recs:
- if rec is oldReceiver:
- found = 1
- break
- if not found:
- _killBackref( oldReceiver, senderkey )
- return True
- return False
-
-
-def _killBackref( receiver, senderkey ):
- """Do the actual removal of back reference from receiver to senderkey"""
- receiverkey = id(receiver)
- set = sendersBack.get( receiverkey, () )
- while senderkey in set:
- try:
- set.remove( senderkey )
- except:
- break
- if not set:
- try:
- del sendersBack[ receiverkey ]
- except KeyError:
- pass
- return True
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/errors.py b/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/errors.py
deleted file mode 100644
index a2eb32ed7..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/errors.py
+++ /dev/null
@@ -1,10 +0,0 @@
-"""Error types for dispatcher mechanism
-"""
-
-class DispatcherError(Exception):
- """Base class for all Dispatcher errors"""
-class DispatcherKeyError(KeyError, DispatcherError):
- """Error raised when unknown (sender,signal) set specified"""
-class DispatcherTypeError(TypeError, DispatcherError):
- """Error raised when inappropriate signal-type specified (None)"""
-
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/robust.py b/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/robust.py
deleted file mode 100644
index 929f550c6..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/robust.py
+++ /dev/null
@@ -1,57 +0,0 @@
-"""Module implementing error-catching version of send (sendRobust)"""
-from pydispatch.dispatcher import Any, Anonymous, liveReceivers, getAllReceivers
-from pydispatch.robustapply import robustApply
-
-def sendRobust(
- signal=Any,
- sender=Anonymous,
- *arguments, **named
-):
- """Send signal from sender to all connected receivers catching errors
-
- signal -- (hashable) signal value, see connect for details
-
- sender -- the sender of the signal
-
- if Any, only receivers registered for Any will receive
- the message.
-
- if Anonymous, only receivers registered to receive
- messages from Anonymous or Any will receive the message
-
- Otherwise can be any python object (normally one
- registered with a connect if you actually want
- something to occur).
-
- arguments -- positional arguments which will be passed to
- *all* receivers. Note that this may raise TypeErrors
- if the receivers do not allow the particular arguments.
- Note also that arguments are applied before named
- arguments, so they should be used with care.
-
- named -- named arguments which will be filtered according
- to the parameters of the receivers to only provide those
- acceptable to the receiver.
-
- Return a list of tuple pairs [(receiver, response), ... ]
-
- if any receiver raises an error (specifically any subclass of Exception),
- the error instance is returned as the result for that receiver.
- """
- # Call each receiver with whatever arguments it can accept.
- # Return a list of tuple pairs [(receiver, response), ... ].
- responses = []
- for receiver in liveReceivers(getAllReceivers(sender, signal)):
- try:
- response = robustApply(
- receiver,
- signal=signal,
- sender=sender,
- *arguments,
- **named
- )
- except Exception, err:
- responses.append((receiver, err))
- else:
- responses.append((receiver, response))
- return responses
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/robustapply.py b/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/robustapply.py
deleted file mode 100644
index 452760807..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/robustapply.py
+++ /dev/null
@@ -1,57 +0,0 @@
-"""Robust apply mechanism
-
-Provides a function "call", which can sort out
-what arguments a given callable object can take,
-and subset the given arguments to match only
-those which are acceptable.
-"""
-import sys
-if sys.hexversion >= 0x3000000:
- im_func = '__func__'
- im_self = '__self__'
- im_code = '__code__'
- func_code = '__code__'
-else:
- im_func = 'im_func'
- im_self = 'im_self'
- im_code = 'im_code'
- func_code = 'func_code'
-
-def function( receiver ):
- """Get function-like callable object for given receiver
-
- returns (function_or_method, codeObject, fromMethod)
-
- If fromMethod is true, then the callable already
- has its first argument bound
- """
- if hasattr(receiver, '__call__'):
- # Reassign receiver to the actual method that will be called.
- if hasattr( receiver.__call__, im_func) or hasattr( receiver.__call__, im_code):
- receiver = receiver.__call__
- if hasattr( receiver, im_func ):
- # an instance-method...
- return receiver, getattr(getattr(receiver, im_func), func_code), 1
- elif not hasattr( receiver, func_code):
- raise ValueError('unknown reciever type %s %s'%(receiver, type(receiver)))
- return receiver, getattr(receiver,func_code), 0
-
-def robustApply(receiver, *arguments, **named):
- """Call receiver with arguments and an appropriate subset of named
- """
- receiver, codeObject, startIndex = function( receiver )
- acceptable = codeObject.co_varnames[startIndex+len(arguments):codeObject.co_argcount]
- for name in codeObject.co_varnames[startIndex:startIndex+len(arguments)]:
- if name in named:
- raise TypeError(
- """Argument %r specified both positionally and as a keyword for calling %r"""% (
- name, receiver,
- )
- )
- if not (codeObject.co_flags & 8):
- # fc does not have a **kwds type parameter, therefore
- # remove unacceptable arguments.
- for arg in named.keys():
- if arg not in acceptable:
- del named[arg]
- return receiver(*arguments, **named)
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/saferef.py b/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/saferef.py
deleted file mode 100644
index f1929a593..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/pydispatch/saferef.py
+++ /dev/null
@@ -1,171 +0,0 @@
-"""Refactored "safe reference" from dispatcher.py"""
-import weakref, traceback, sys
-
-if sys.hexversion >= 0x3000000:
- im_func = '__func__'
- im_self = '__self__'
-else:
- im_func = 'im_func'
- im_self = 'im_self'
-def safeRef(target, onDelete = None):
- """Return a *safe* weak reference to a callable target
-
- target -- the object to be weakly referenced, if it's a
- bound method reference, will create a BoundMethodWeakref,
- otherwise creates a simple weakref.
- onDelete -- if provided, will have a hard reference stored
- to the callable to be called after the safe reference
- goes out of scope with the reference object, (either a
- weakref or a BoundMethodWeakref) as argument.
- """
- if hasattr(target, im_self):
- if getattr(target, im_self) is not None:
- # Turn a bound method into a BoundMethodWeakref instance.
- # Keep track of these instances for lookup by disconnect().
- assert hasattr(target, im_func), """safeRef target %r has %s, but no %s, don't know how to create reference"""%( target,im_self,im_func)
- reference = BoundMethodWeakref(
- target=target,
- onDelete=onDelete
- )
- return reference
- if onDelete is not None:
- return weakref.ref(target, onDelete)
- else:
- return weakref.ref( target )
-
-class BoundMethodWeakref(object):
- """'Safe' and reusable weak references to instance methods
-
- BoundMethodWeakref objects provide a mechanism for
- referencing a bound method without requiring that the
- method object itself (which is normally a transient
- object) is kept alive. Instead, the BoundMethodWeakref
- object keeps weak references to both the object and the
- function which together define the instance method.
-
- Attributes:
- key -- the identity key for the reference, calculated
- by the class's calculateKey method applied to the
- target instance method
- deletionMethods -- sequence of callable objects taking
- single argument, a reference to this object which
- will be called when *either* the target object or
- target function is garbage collected (i.e. when
- this object becomes invalid). These are specified
- as the onDelete parameters of safeRef calls.
- weakSelf -- weak reference to the target object
- weakFunc -- weak reference to the target function
-
- Class Attributes:
- _allInstances -- class attribute pointing to all live
- BoundMethodWeakref objects indexed by the class's
- calculateKey(target) method applied to the target
- objects. This weak value dictionary is used to
- short-circuit creation so that multiple references
- to the same (object, function) pair produce the
- same BoundMethodWeakref instance.
-
- """
- _allInstances = weakref.WeakValueDictionary()
- def __new__( cls, target, onDelete=None, *arguments,**named ):
- """Create new instance or return current instance
-
- Basically this method of construction allows us to
- short-circuit creation of references to already-
- referenced instance methods. The key corresponding
- to the target is calculated, and if there is already
- an existing reference, that is returned, with its
- deletionMethods attribute updated. Otherwise the
- new instance is created and registered in the table
- of already-referenced methods.
- """
- key = cls.calculateKey(target)
- current =cls._allInstances.get(key)
- if current is not None:
- current.deletionMethods.append( onDelete)
- return current
- else:
- base = super( BoundMethodWeakref, cls).__new__( cls )
- cls._allInstances[key] = base
- base.__init__( target, onDelete, *arguments,**named)
- return base
- def __init__(self, target, onDelete=None):
- """Return a weak-reference-like instance for a bound method
-
- target -- the instance-method target for the weak
- reference, must have and attributes
- and be reconstructable via:
- target..__get__( target. )
- which is true of built-in instance methods.
- onDelete -- optional callback which will be called
- when this weak reference ceases to be valid
- (i.e. either the object or the function is garbage
- collected). Should take a single argument,
- which will be passed a pointer to this object.
- """
- def remove(weak, self=self):
- """Set self.isDead to true when method or instance is destroyed"""
- methods = self.deletionMethods[:]
- del self.deletionMethods[:]
- try:
- del self.__class__._allInstances[ self.key ]
- except KeyError:
- pass
- for function in methods:
- try:
- if hasattr(function, '__call__' ):
- function( self )
- except Exception, e:
- try:
- traceback.print_exc()
- except AttributeError:
- print '''Exception during saferef %s cleanup function %s: %s'''%(
- self, function, e
- )
- self.deletionMethods = [onDelete]
- self.key = self.calculateKey( target )
- self.weakSelf = weakref.ref(getattr(target,im_self), remove)
- self.weakFunc = weakref.ref(getattr(target,im_func), remove)
- self.selfName = getattr(target,im_self).__class__.__name__
- self.funcName = str(getattr(target,im_func).__name__)
- def calculateKey( cls, target ):
- """Calculate the reference key for this reference
-
- Currently this is a two-tuple of the id()'s of the
- target object and the target function respectively.
- """
- return (id(getattr(target,im_self)),id(getattr(target,im_func)))
- calculateKey = classmethod( calculateKey )
- def __str__(self):
- """Give a friendly representation of the object"""
- return """%s( %s.%s )"""%(
- self.__class__.__name__,
- self.selfName,
- self.funcName,
- )
- __repr__ = __str__
- def __nonzero__( self ):
- """Whether we are still a valid reference"""
- return self() is not None
- def __cmp__( self, other ):
- """Compare with another reference"""
- if not isinstance (other,self.__class__):
- return cmp( self.__class__, type(other) )
- return cmp( self.key, other.key)
- def __call__(self):
- """Return a strong reference to the bound method
-
- If the target cannot be retrieved, then will
- return None, otherwise returns a bound instance
- method for our object and function.
-
- Note:
- You may call this method any number of times,
- as it does not invalidate the reference.
- """
- target = self.weakSelf()
- if target is not None:
- function = self.weakFunc()
- if function is not None:
- return function.__get__(target)
- return None
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/setup.cfg b/software/openvisualizer/PyDispatcher-2.0.3/setup.cfg
deleted file mode 100644
index 861a9f554..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/setup.cfg
+++ /dev/null
@@ -1,5 +0,0 @@
-[egg_info]
-tag_build =
-tag_date = 0
-tag_svn_revision = 0
-
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/setup.py b/software/openvisualizer/PyDispatcher-2.0.3/setup.py
deleted file mode 100644
index 0fbd003e4..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/setup.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/env python
-"""Installs PyDispatcher using distutils (or setuptools/distribute)
-
-Run:
- python setup.py install
-to install the package from the source archive.
-"""
-import sys, os
-try:
- from setuptools import setup
-except ImportError:
- from distutils.core import setup
-
-extra_commands = {}
-extra_arguments = {}
-
-if sys.hexversion >= 0x2030000:
- # work around distutils complaints under Python 2.2.x
- extra_arguments = {
- 'classifiers': [
- """License :: OSI Approved :: BSD License""",
- """Programming Language :: Python""",
- """Programming Language :: Python :: 3""",
- """Topic :: Software Development :: Libraries :: Python Modules""",
- """Intended Audience :: Developers""",
- ],
- #'download_url': "http://sourceforge.net/projects/pydispatcher/files/pydispatcher/",
- 'keywords': 'dispatcher,dispatch,pydispatch,event,signal,sender,receiver,propagate,multi-consumer,multi-producer,saferef,robustapply,apply',
- 'long_description' : """Dispatcher mechanism for creating event models
-
-PyDispatcher is an enhanced version of Patrick K. O'Brien's
-original dispatcher.py module. It provides the Python
-programmer with a robust mechanism for event routing within
-various application contexts.
-
-Included in the package are the robustapply and saferef
-modules, which provide the ability to selectively apply
-arguments to callable objects and to reference instance
-methods using weak-references.
-""",
- 'platforms': ['Any'],
- }
-if sys.hexversion >= 0x3000000:
- try:
- from distutils.command.build_py import build_py_2to3
- extra_commands['build_py'] = build_py_2to3
- except ImportError:
- pass
-
-version = [
- (line.split('=')[1]).strip().strip('"').strip("'")
- for line in open(os.path.join('pydispatch','__init__.py'))
- if line.startswith( '__version__' )
-][0]
-
-if __name__ == "__main__":
- ### Now the actual set up call
- setup (
- name = "PyDispatcher",
- version = version,
- description= "Multi-producer-multi-consumer signal dispatching mechanism",
- author = "Patrick K. O'Brien",
- maintainer = "Mike C. Fletcher",
- author_email = "pydispatcher-devel@lists.sourceforge.net",
- maintainer_email = "pydispatcher-devel@lists.sourceforge.net",
- url = "http://pydispatcher.sourceforge.net",
- license = "BSD-style, see license.txt for details",
-
- package_dir = {
- 'pydispatch':'pydispatch',
- },
-
- packages = [
- 'pydispatch',
- ],
-
- options = {
- 'sdist':{'use_defaults':0, 'force_manifest':1,'formats': ['gztar','zip'],},
- 'bdist_rpm':{
- 'group':'Libraries/Python',
- 'provides':'python-dispatcher',
- 'requires':"python",
- },
- },
- cmdclass = extra_commands,
- use_2to3 = True,
- # registration metadata
- **extra_arguments
- )
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/tests/__init__.py b/software/openvisualizer/PyDispatcher-2.0.3/tests/__init__.py
deleted file mode 100644
index b112ba530..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/tests/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-"""Unit-tests for the dispatch project
-"""
-
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/tests/test_dispatcher.py b/software/openvisualizer/PyDispatcher-2.0.3/tests/test_dispatcher.py
deleted file mode 100644
index c2d45349d..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/tests/test_dispatcher.py
+++ /dev/null
@@ -1,130 +0,0 @@
-from pydispatch.dispatcher import *
-from pydispatch import dispatcher, robust
-
-import unittest, pprint
-def x(a):
- return a
-
-class Dummy( object ):
- pass
-class Callable(object):
- def __call__( self, a ):
- return a
- def a( self, a ):
- return a
-
-class DispatcherTests(unittest.TestCase):
- """Test suite for dispatcher (barely started)"""
-
- def _isclean( self ):
- """Assert that everything has been cleaned up automatically"""
- assert len(dispatcher.sendersBack) == 0, dispatcher.sendersBack
- assert len(dispatcher.connections) == 0, dispatcher.connections
- assert len(dispatcher.senders) == 0, dispatcher.senders
-
- def testExact (self):
- a = Dummy()
- signal = 'this'
- connect( x, signal, a )
- expected = [(x,a)]
- result = send('this',a, a=a)
- assert result == expected,"""Send didn't return expected result:\n\texpected:%s\n\tgot:%s"""% (expected, result)
- disconnect( x, signal, a )
- assert len(list(getAllReceivers(a,signal))) == 0
- self._isclean()
- def testAnonymousSend(self):
- a = Dummy()
- signal = 'this'
- connect( x, signal )
- expected = [(x,a)]
- result = send(signal,None, a=a)
- assert result == expected,"""Send didn't return expected result:\n\texpected:%s\n\tgot:%s"""% (expected, result)
- disconnect( x, signal )
- assert len(list(getAllReceivers(None,signal))) == 0
- self._isclean()
- def testAnyRegistration(self):
- a = Dummy()
- signal = 'this'
- connect( x, signal, Any )
- expected = [(x,a)]
- result = send('this',object(), a=a)
- assert result == expected,"""Send didn't return expected result:\n\texpected:%s\n\tgot:%s"""% (expected, result)
- disconnect( x, signal, Any )
- expected = []
- result = send('this',object(), a=a)
- assert result == expected,"""Send didn't return expected result:\n\texpected:%s\n\tgot:%s"""% (expected, result)
- assert len(list(getAllReceivers(Any,signal))) == 0
-
- self._isclean()
-
- def testAnyRegistration2(self):
- a = Dummy()
- signal = 'this'
- connect( x, Any, a )
- expected = [(x,a)]
- result = send('this',a, a=a)
- assert result == expected,"""Send didn't return expected result:\n\texpected:%s\n\tgot:%s"""% (expected, result)
- disconnect( x, Any, a )
- assert len(list(getAllReceivers(a,Any))) == 0
- self._isclean()
- def testGarbageCollected(self):
- a = Callable()
- b = Dummy()
- signal = 'this'
- connect( a.a, signal, b )
- expected = []
- del a
- result = send('this',b, a=b)
- assert result == expected,"""Send didn't return expected result:\n\texpected:%s\n\tgot:%s"""% (expected, result)
- assert len(list(getAllReceivers(b,signal))) == 0, """Remaining handlers: %s"""%(getAllReceivers(b,signal),)
- self._isclean()
- def testGarbageCollectedObj(self):
- class x:
- def __call__( self, a ):
- return a
- a = Callable()
- b = Dummy()
- signal = 'this'
- connect( a, signal, b )
- expected = []
- del a
- result = send('this',b, a=b)
- assert result == expected,"""Send didn't return expected result:\n\texpected:%s\n\tgot:%s"""% (expected, result)
- assert len(list(getAllReceivers(b,signal))) == 0, """Remaining handlers: %s"""%(getAllReceivers(b,signal),)
- self._isclean()
-
-
- def testMultipleRegistration(self):
- a = Callable()
- b = Dummy()
- signal = 'this'
- connect( a, signal, b )
- connect( a, signal, b )
- connect( a, signal, b )
- connect( a, signal, b )
- connect( a, signal, b )
- connect( a, signal, b )
- result = send('this',b, a=b)
- assert len( result ) == 1, result
- assert len(list(getAllReceivers(b,signal))) == 1, """Remaining handlers: %s"""%(getAllReceivers(b,signal),)
- del a
- del b
- del result
- self._isclean()
- def testRobust( self ):
- """Test the sendRobust function"""
- def fails( ):
- raise ValueError( 'this' )
- a = object()
- signal = 'this'
- connect( fails, Any, a )
- result = robust.sendRobust('this',a, a=a)
- err = result[0][1]
- assert isinstance( err, ValueError )
- assert err.args == ('this',)
-
-def getSuite():
- return unittest.makeSuite(DispatcherTests,'test')
-
-if __name__ == "__main__":
- unittest.main ()
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/tests/test_robustapply.py b/software/openvisualizer/PyDispatcher-2.0.3/tests/test_robustapply.py
deleted file mode 100644
index 914e3a681..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/tests/test_robustapply.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from pydispatch.robustapply import *
-
-import unittest
-def noArgument():
- pass
-def oneArgument (blah):
- pass
-def twoArgument(blah, other):
- pass
-class TestCases( unittest.TestCase ):
- def test01( self ):
- robustApply(noArgument )
- def test02( self ):
- self.assertRaises( TypeError, robustApply, noArgument, "this" )
- def test03( self ):
- self.assertRaises( TypeError, robustApply, oneArgument )
- def test04( self ):
- """Raise error on duplication of a particular argument"""
- self.assertRaises( TypeError, robustApply, oneArgument, "this", blah = "that" )
-
-def getSuite():
- return unittest.makeSuite(TestCases,'test')
-
-
-if __name__ == "__main__":
- unittest.main()
-
diff --git a/software/openvisualizer/PyDispatcher-2.0.3/tests/test_saferef.py b/software/openvisualizer/PyDispatcher-2.0.3/tests/test_saferef.py
deleted file mode 100644
index 8f7b21058..000000000
--- a/software/openvisualizer/PyDispatcher-2.0.3/tests/test_saferef.py
+++ /dev/null
@@ -1,76 +0,0 @@
-from pydispatch.saferef import *
-
-import unittest
-class T1( object):
- def x( self ):
- pass
-def t2(obj):
- pass
-class T2( object ):
- def __call__( self, obj ):
- pass
-class Tester (unittest.TestCase):
- def setUp (self):
- ts = []
- ss = []
- for x in range( 5000 ):
- t = T1()
- ts.append( t)
- s = safeRef(t.x, self._closure )
- ss.append( s)
- ts.append( t2 )
- ss.append( safeRef(t2, self._closure) )
- for x in range( 30 ):
- t = T2()
- ts.append( t)
- s = safeRef(t, self._closure )
- ss.append( s)
- self.ts = ts
- self.ss = ss
- self.closureCount = 0
- def tearDown( self ):
- del self.ts
- del self.ss
- def testIn(self):
- """Test the "in" operator for safe references (cmp)"""
- for t in self.ts[:50]:
- assert safeRef(t.x) in self.ss
- def testValid(self):
- """Test that the references are valid (return instance methods)"""
- for s in self.ss:
- assert s()
- def testShortCircuit (self):
- """Test that creation short-circuits to reuse existing references"""
- sd = {}
- for s in self.ss:
- sd[s] = 1
- for t in self.ts:
- if hasattr( t, 'x'):
- assert safeRef(t.x) in sd
- else:
- assert safeRef(t) in sd
- def testRepresentation (self):
- """Test that the reference object's representation works
-
- XXX Doesn't currently check the results, just that no error
- is raised
- """
- repr( self.ss[-1] )
-
- def test(self):
- self.closureCount = 0
- wholeI = len(self.ts)
- for i in range( len(self.ts)-1, -1, -1):
- del self.ts[i]
- if wholeI-i != self.closureCount:
- """Unexpected number of items closed, expected %s, got %s closed"""%( wholeI-i,self.closureCount)
-
- def _closure(self, ref):
- """Dumb utility mechanism to increment deletion counter"""
- self.closureCount +=1
-
-def getSuite():
- return unittest.makeSuite(Tester,'test')
-
-if __name__ == "__main__":
- unittest.main ()
diff --git a/software/openvisualizer/README.txt b/software/openvisualizer/README.txt
new file mode 100644
index 000000000..1c4f99da4
--- /dev/null
+++ b/software/openvisualizer/README.txt
@@ -0,0 +1,58 @@
+.. Formatted as reStructuredText
+
+OpenVisualizer is part of UC Berkeley's OpenWSN project. It provides
+monitoring, visualization, and debugging for an OpenWSN-based wireless sensor
+network. See the project `home page`_ for more information.
+
+Installation
+------------
+You may install OpenVisualizer with the standard pip command line, as shown
+below. See the pip `installation instructions`_ if it is not installed
+already. You must be logged in with Windows administrator or Linux superuser
+privileges to install to system-level directories.
+
+::
+
+ > pip install openVisualizer
+
+Alternatively, you may download the OpenVisualizer archive, extract it, and
+install with the standard Python setup.py command line, as shown below. This
+command uses pip to retrieve other required Python libraries.
+
+::
+
+ > python setup.py install
+
+Dependencies
+------------
+You also may need to separately install a driver for a USB-connected mote.
+On Windows, a couple of other tools are required. See the OpenVisualizer
+`installation page`_ for a list.
+
+Running, etc.
+-------------
+Once everything is installed, you may run the web interface, GUI, or command
+line utiltity as described on the OpenVisualizer home page.
+
+To uninstall a pip-based installation, use the command line::
+
+ > pip uninstall openVisualizer
+
+Please contact us via the `mailing list`_ or an `issue report`_ if you
+have any questions or suggestions.
+
+| Thanks!
+| The OpenWSN Team
+
+.. _home page:
+ https://openwsn.atlassian.net/wiki/display/OW/OpenVisualizer
+
+.. _installation instructions:
+ http://www.pip-installer.org/en/latest/installing.html
+
+.. _installation page:
+ https://openwsn.atlassian.net/wiki/display/OW/Installation+and+Dependencies
+
+.. _mailing list: https://openwsn.atlassian.net/wiki/display/OW/Mailing+List
+
+.. _issue report: https://openwsn.atlassian.net
diff --git a/software/openvisualizer/SConstruct b/software/openvisualizer/SConstruct
new file mode 100644
index 000000000..bb49d28a0
--- /dev/null
+++ b/software/openvisualizer/SConstruct
@@ -0,0 +1,310 @@
+# Copyright (c) 2010-2013, Regents of the University of California.
+# All rights reserved.
+#
+# Released under the BSD 3-Clause license as published at the link below.
+# https://openwsn.atlassian.net/wiki/display/OW/License
+
+import os
+import platform
+import subprocess
+import sys
+import SCons
+import sconsUtils
+
+#============================ banner ==========================================
+
+banner = [""]
+banner += [" ___ _ _ _ ___ _ _ "]
+banner += ["| . | ___ ___ ._ _ | | | |/ __>| \ |"]
+banner += ["| | || . \/ ._>| ' || | | |\__ \| |"]
+banner += ["`___'| _/\___.|_|_||__/_/ <___/|_\_|"]
+banner += [" |_| openwsn.org"]
+banner += [""]
+
+print '\n'.join(banner)
+
+#============================ SCons environment ===============================
+
+#===== help text
+
+Help('''
+Usage:
+ scons [options]
+ scons copy-simfw
+ scons
+ scons unittests
+ scons docs
+
+Targets:
+ rungui/runcli/runweb:
+ Run OpenVisualizer with GUI, command line, or web interface,
+ respectively.
+ The application is run in the build/runui/ directory. Since it accesses
+ your computer's network interfaces, it must be run as
+ superuser/administrator.
+
+ Options
+ --sim Run in simulator mode with default count of motes.
+ --simCount=n Run in simulator mode with 'n' motes.
+ --simTopology=
+ Force a certain topology for simulation.
+ --nosimcopy Skips copying simulation firmware at startup from the
+ openwsn-fw directory.
+ --ovdebug Enable debug mode; more detailed logging
+
+ Web UI only
+ --host= Web server listens on IP address;
+ default 0.0.0.0 (all interfaces)
+ --port=n Web server listens on port number 'n';
+ default 8080
+
+ copy-simfw:
+ Copy files for the simulator, generated from an OpenWSN firmware
+ build on this host. Assumes firmware top-level directory is
+ '../../../openwsn-fw'.
+
+ Options
+ --simhost=
+ Platform and OS for firmware; supports creation of a
+ setup package with multiple variants. Defaults to the
+ platform-OS on which SCons is running. Valid entries:
+ amd64-linux, x86-linux, amd64-windows, x86-windows
+
+ sdist:
+ Generate a standard Python source distribution archive (for
+ setup.py) in build{0}dist directory. Installs data files to the
+ openvisualizer package directory.
+
+ upload:
+ Uploads sdist archive to PyPI. The user must be registered as an
+ Owner or Maintainer of OpenVisualizer. The user's PyPI credentials
+ must be stored in their home directory .pypirc file.
+
+ sdist-native:
+ Linux only
+ Generate a standard Python source distribution archive (for
+ setup.py) in build{0}dist directory. Installs to native directories
+ for the OS on which this command is run. This command *must* be
+ run on a Linux host to generate a Linux target archive. Installs
+ data files to /usr/local/share.
+
+ docs:
+ Generate source documentation in build{0}html directory
+
+'''.format(os.sep))
+# Help for trace option on next line. Removed from help because trace
+# implementation is not working.
+# --trace Run yappi-based memory trace
+
+
+# Define base environment
+env = Environment(
+ ENV = {'PATH' : os.environ['PATH']}
+)
+# Must define with absolute path since SCons construction may occur in a
+# subdirectory via SConscript.
+env['ROOT_BUILD_DIR'] = os.path.join(os.getcwd(), 'build')
+
+# External openwsn-fw repository directory. An environment variable makes it
+# easy to change since it depends on the host running this script.
+env['FW_DIR'] = os.path.join('..', '..', '..', 'openwsn-fw')
+
+def default(env,target,source):
+ print SCons.Script.help_text
+
+Default(env.Command('default', None, default))
+
+
+# Define environment and options common to all run... targets
+runnerEnv = env.Clone()
+
+AddOption('--sim',
+ dest = 'simOpt',
+ default = False,
+ action = 'store_true')
+runnerEnv['SIMOPT'] = GetOption('simOpt')
+
+AddOption('--simCount',
+ dest = 'simCount',
+ default = 0,
+ type = 'int')
+runnerEnv['SIMCOUNT'] = GetOption('simCount')
+
+AddOption('--simTopology',
+ dest = 'simTopology',
+ default = '',
+ type = 'string')
+runnerEnv['SIMTOPOLOGY'] = GetOption('simTopology')
+
+AddOption('--nosimcopy',
+ dest = 'simcopyOpt',
+ default = True,
+ action = 'store_true')
+runnerEnv['SIMCOPYOPT'] = GetOption('simcopyOpt')
+
+AddOption('--trace',
+ dest = 'traceOpt',
+ default = False,
+ action = 'store_true')
+runnerEnv['TRACEOPT'] = GetOption('traceOpt')
+
+AddOption('--ovdebug',
+ dest = 'debugOpt',
+ default = False,
+ action = 'store_true')
+runnerEnv['DEBUGOPT'] = GetOption('debugOpt')
+
+
+# These options are used only by the web runner. We define them here for
+# simplicity, but they must be removed from non-web use in the runner
+# SConscript.
+AddOption('--host',
+ dest = 'hostOpt',
+ default = '0.0.0.0',
+ type = 'string')
+runnerEnv['HOSTOPT'] = GetOption('hostOpt')
+
+AddOption('--port',
+ dest = 'portOpt',
+ default = 8080,
+ type = 'int')
+runnerEnv['PORTOPT'] = GetOption('portOpt')
+
+#============================ SCons targets ===================================
+
+#===== copy-simfw
+
+simhosts = ['amd64-linux','x86-linux','amd64-windows','x86-windows']
+if os.name == 'nt':
+ defaultIndex = 2 if platform.architecture()[0]=='64bit' else 3
+else:
+ defaultIndex = 0 if platform.architecture()[0]=='64bit' else 1
+
+AddOption('--simhost',
+ dest = 'simhostOpt',
+ default = simhosts[defaultIndex],
+ type = 'choice',
+ choices = simhosts)
+
+# Must copy SIMHOSTOPT to runner environment since it also reads sconsUtils.py.
+env['SIMHOSTOPT'] = GetOption('simhostOpt')
+runnerEnv['SIMHOSTOPT'] = env['SIMHOSTOPT']
+
+Alias('copy-simfw', sconsUtils.copySimfw(env, 'simcopy'))
+
+#===== rungui, runcli, runweb
+
+# Must define run targets below the copy-simfw target so SIMHOSTOPT is available.
+# Run targets may copy simulation firmware before starting.
+
+appdir = os.path.join('bin', 'openVisualizerApp')
+
+SConscript(
+ os.path.join(appdir, 'SConscript'),
+ exports = {"env": runnerEnv},
+)
+
+# Copy variables for data files out of runner environment, to be used in
+# dist targets below.
+env['CONF_FILES'] = runnerEnv['CONF_FILES']
+env['DATA_DIRS'] = runnerEnv['DATA_DIRS']
+
+#===== sdist
+
+def makeTreeSdist(env, target):
+ '''
+ Creates a target that requires creation of a source distribution. Uses
+ the target name as a phony target to force the build. Supports 'sdist' and
+ 'upload' targets.
+
+ First, copies the data files from the openVisualizerApp directory as data
+ for the openvisualizer package. Then creates the source dist archive.
+ Cleans up the temporary package data file.
+ '''
+ datadir = os.path.join('openvisualizer', 'data')
+ appdir = os.path.join('bin', 'openVisualizerApp')
+ distdir = os.path.join('build', 'dist')
+ topdir = os.path.join('..', '..')
+ cmdlist = []
+
+ cmdlist.append(Delete(distdir))
+ cmdlist.append(Delete(datadir))
+ cmdlist.append(Delete('openVisualizer.egg-info'))
+
+ cmdlist.append(Mkdir(datadir))
+ cmdlist.append(Copy(os.path.join(datadir, 'requirements.pip'),
+ os.path.join(topdir, 'requirements.pip')))
+ for conf in env['CONF_FILES']:
+ cmdlist.append(Copy(os.path.join(datadir, conf), os.path.join(appdir, conf)))
+ for data in env['DATA_DIRS']:
+ cmdlist.append(Copy(os.path.join(datadir, data), os.path.join(appdir, data)))
+
+ sdistLines = ['python setup.py sdist',
+ '--formats=gztar,zip',
+ '--dist-dir {0}'.format(distdir)]
+ if target == 'sdist':
+ cmdlist.append(' '.join(sdistLines))
+ elif target == 'upload':
+ # Must first run sdist before upload
+ cmdlist.append(' '.join(sdistLines + ['upload']))
+ else:
+ print 'Target "{0}" not supported'.format(target)
+
+ cmdlist.append(Delete(datadir))
+ cmdlist.append(Delete('openVisualizer.egg-info'))
+
+ return env.Command(target, '', cmdlist)
+
+Alias('sdist', makeTreeSdist(env, 'sdist'))
+Alias('upload', makeTreeSdist(env, 'upload'))
+
+#===== sdist-native
+
+def makeNativeSdist(env):
+ '''
+ Creates the source dist archive for a OS-native install. Uses a
+ phony target to force build.
+ '''
+ distdir = os.path.join('build', 'dist')
+
+ return env.Command('native', '',
+ [
+ Delete(distdir),
+ Delete('MANIFEST'),
+ Copy('setup.py', 'nativeSetup.py'),
+ 'python setup.py sdist --dist-dir {0}'.format(distdir),
+ Delete('setup.py'),
+ Delete('MANIFEST'),
+ ])
+
+Alias('sdist-native', makeNativeSdist(env))
+
+#===== unittest
+
+# scan for SConscript contains unit tests
+dirs = [
+ os.path.join('openvisualizer', 'moteProbe'),
+ os.path.join('openvisualizer', 'openLbr'),
+ os.path.join('openvisualizer', 'RPL'),
+]
+for d in dirs:
+ SConscript(
+ os.path.join(d, 'SConscript'),
+ exports = {"env": env},
+ )
+
+Alias(
+ 'unittests',
+ [
+ 'unittests_moteProbe',
+ 'unittests_openLbr',
+ 'unittests_RPL',
+ ]
+)
+
+#===== docs
+
+SConscript(
+ os.path.join('docs', 'SConscript'),
+ exports = {"env": env},
+)
diff --git a/software/openvisualizer/bin/moteProbeCli/moteProbeCli.py b/software/openvisualizer/bin/moteProbeCli/moteProbeCli.py
index d73748c04..b25b41305 100644
--- a/software/openvisualizer/bin/moteProbeCli/moteProbeCli.py
+++ b/software/openvisualizer/bin/moteProbeCli/moteProbeCli.py
@@ -1,86 +1,82 @@
-import os
-import sys
-if __name__=='__main__':
- cur_path = sys.path[0]
- sys.path.insert(0, os.path.join(cur_path, '..', '..')) # openvisualizer/
- sys.path.insert(0, os.path.join(cur_path, '..', '..', '..', 'openCli')) # openCli/
- sys.path.insert(0, os.path.join(cur_path, '..', '..','PyDispatcher-2.0.3'))# PyDispatcher-2.0.3/
-
-from moteProbe import moteProbe
-from OpenCli import OpenCli
-
-TCP_PORT_START = 8090
-
-class moteProbeCli(OpenCli):
-
- def __init__(self,moteProbe_handlers):
-
- # store params
- self.moteProbe_handlers = moteProbe_handlers
-
- # initialize parent class
- OpenCli.__init__(self,"mote probe CLI",self.quit_cb)
-
- # add commands
- self.registerCommand('status',
- 's',
- 'print status',
- [],
- self._handlerStatus)
-
- #======================== public ==========================================
-
- #======================== private =========================================
-
- #===== callbacks
-
- def _handlerStatus(self,params):
- output = []
-
- for mp in self.moteProbe_handlers:
- output += [' - serial port {0}@{1} presented on TCP port {2}'.format(
- mp.getSerialPortName(),
- mp.getSerialPortBaudrate(),
- mp.getTcpPort())]
-
- print '\n'.join(output)
-
- #===== helpers
-
- def quit_cb(self):
- for mb in self.moteProbe_handlers:
- mb.quit()
-
-def main():
-
- moteProbe_handlers = []
-
- # create a moteProbe for each mote connected to this computer
- serialPortNames = moteProbe.utils.findSerialPorts()
- port_numbers = [TCP_PORT_START+i for i in range(len(serialPortNames))]
- for (serialPortName,port_number) in zip(serialPortNames,port_numbers):
- moteProbe_handlers.append(moteProbe.moteProbe(serialPortName,port_number))
-
- # create an open CLI
- cli = moteProbeCli(moteProbe_handlers)
- cli.start()
-
-#============================ application logging =============================
-import logging
-import logging.handlers
-logHandler = logging.handlers.RotatingFileHandler('moteProbe.log',
- maxBytes=2000000,
- backupCount=5,
- mode='w')
-logHandler.setFormatter(logging.Formatter("%(asctime)s [%(name)s:%(levelname)s] %(message)s"))
-for loggerName in ['moteProbe',
- 'moteProbeSerialThread',
- 'moteProbeSocketThread',
- 'moteProbeUtils',
- ]:
- temp = logging.getLogger(loggerName)
- temp.setLevel(logging.DEBUG)
- temp.addHandler(logHandler)
-
-if __name__=="__main__":
+import os
+import sys
+if __name__=='__main__':
+ cur_path = sys.path[0]
+ sys.path.insert(0, os.path.join(cur_path, '..', '..')) # openvisualizer/
+ sys.path.insert(0, os.path.join(cur_path, '..', '..', '..', 'openCli')) # openCli/
+ sys.path.insert(0, os.path.join(cur_path, '..', '..','PyDispatcher-2.0.3'))# PyDispatcher-2.0.3/
+
+from moteProbe import moteProbe
+from OpenCli import OpenCli
+
+TCP_PORT_START = 8090
+
+class moteProbeCli(OpenCli):
+
+ def __init__(self,moteProbe_handlers):
+
+ # store params
+ self.moteProbe_handlers = moteProbe_handlers
+
+ # initialize parent class
+ OpenCli.__init__(self,"mote probe CLI",self.quit_cb)
+
+ # add commands
+ self.registerCommand('status',
+ 's',
+ 'print status',
+ [],
+ self._handlerStatus)
+
+ #======================== public ==========================================
+
+ #======================== private =========================================
+
+ #===== callbacks
+
+ def _handlerStatus(self,params):
+ output = []
+
+ for mp in self.moteProbe_handlers:
+ output += [' - serial port {0}@{1} presented on TCP port {2}'.format(
+ mp.getSerialPortName(),
+ mp.getSerialPortBaudrate(),
+ mp.getTcpPort())]
+
+ print '\n'.join(output)
+
+ #===== helpers
+
+ def quit_cb(self):
+ for mb in self.moteProbe_handlers:
+ mb.quit()
+
+def main():
+
+ moteProbe_handlers = []
+
+ # create a moteProbe for each mote connected to this computer
+ serialPortNames = moteProbe.utils.findSerialPorts()
+ port_numbers = [TCP_PORT_START+i for i in range(len(serialPortNames))]
+ for (serialPortName,port_number) in zip(serialPortNames,port_numbers):
+ moteProbe_handlers.append(moteProbe.moteProbe(serialPortName,port_number))
+
+ # create an open CLI
+ cli = moteProbeCli(moteProbe_handlers)
+ cli.start()
+
+#============================ application logging =============================
+import logging
+import logging.handlers
+logHandler = logging.handlers.RotatingFileHandler('moteProbe.log',
+ maxBytes=2000000,
+ backupCount=5,
+ mode='w')
+logHandler.setFormatter(logging.Formatter("%(asctime)s [%(name)s:%(levelname)s] %(message)s"))
+for loggerName in ['moteProbe']:
+ temp = logging.getLogger(loggerName)
+ temp.setLevel(logging.DEBUG)
+ temp.addHandler(logHandler)
+
+if __name__=="__main__":
main()
\ No newline at end of file
diff --git a/software/openvisualizer/bin/moteResExperimentCli/moteResExperiementCli.py b/software/openvisualizer/bin/moteResExperimentCli/moteResExperiementCli.py
index 6addc4c05..6f0265120 100644
--- a/software/openvisualizer/bin/moteResExperimentCli/moteResExperiementCli.py
+++ b/software/openvisualizer/bin/moteResExperimentCli/moteResExperiementCli.py
@@ -1,150 +1,150 @@
-import sys
-import os
-import struct
-import binascii
-if __name__=='__main__':
- cur_path = sys.path[0]
- sys.path.insert(0, os.path.join(cur_path, '..', '..')) # openvisualizer/
- sys.path.insert(0, os.path.join(cur_path, '..', '..', '..', 'openCli')) # openCli/
-
-import logging
-class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-log = logging.getLogger('MoteStateCli')
-log.setLevel(logging.DEBUG)
-log.addHandler(NullHandler())
-
-from moteProbe import moteProbe
-from moteConnector import moteConnector
-from moteState import moteState
-from OpenCli import OpenCli
-
-LOCAL_ADDRESS = '127.0.0.1'
-TCP_PORT_START = 8090
-
-class MoteStateCli(OpenCli):
-
- def __init__(self,moteProbe_handlers,moteConnector_handlers,moteState_handlers):
-
- # store params
- self.moteProbe_handlers = moteProbe_handlers
- self.moteConnector_handlers = moteConnector_handlers
- self.moteState_handlers = moteState_handlers
-
- # initialize parent class
- OpenCli.__init__(self,"Reservation Experiment CLI",self._quit_cb)
-
- # add commands
- self.registerCommand('list',
- 'l',
- 'list available states',
- [],
- self._handlerList)
- self.registerCommand('state',
- 's',
- 'prints some state',
- ['state parameter'],
- self._handlerState)
- self.registerCommand('reserve',
- 'r',
- 'reserve cells; e.g. "r e6 eb 2 10032"',
- ['mote_addr','neighbor_addr','num_of_links','start_at_asn'],
- self._handlerRes)
-
- #======================== public ==========================================
-
- #======================== private =========================================
-
- #===== callbacks
-
- def _handlerList(self,params):
- for ms in self.moteState_handlers:
- output = []
- output += ['available states:']
- output += [' - {0}'.format(s) for s in ms.getStateElemNames()]
- print '\n'.join(output)
-
- def _handlerState(self,params):
- for ms in self.moteState_handlers:
- try:
- print ms.getStateElem(params[0])
- except ValueError as err:
- print err
-
- def _handlerRes(self,params):
- for ms in self.moteState_handlers:
- try:
- myid = str(ms.getStateElem("IdManager").data[0]['my16bID'])
- myid=myid[3:5]
- if myid==params[0]:#match the ID and then send command to mote
- print(params)
- input = struct.pack('
-
- OpenWSN tables
-
-
-