Subversion Repositories HomeAutomation

Rev

Blame | Last modification | View Log | SVN | RSS feed

  1. #!/bin/env python
  2.  
  3. import os
  4. import sys
  5. import logging as log
  6. import getopt
  7. import atexit
  8.  
  9. from CanPktHandlerBase import CanPktHandlerBase
  10. from CanPktHandler1 import CanPktHandler1
  11.  
  12. from NodeIfBase import NodeIfBase
  13. from NodeIfCanStim import NodeIfCanStim
  14. from NodeIfSerial import NodeIfSerial
  15.  
  16. from DaemonConfig import DaemonConfig
  17.  
  18. daemonApp = None
  19.  
  20. class CanDaemon():
  21.    
  22.     nodeIf = None
  23.    
  24.     def __init__ (self):
  25.         pass
  26.    
  27.    
  28.     def usage(self):
  29.         pass
  30.    
  31.    
  32.     def helpCommands(self):
  33.         print 'quit, exit     : shutdown CanDaemon'
  34.         print 'help           : display help'
  35.    
  36.    
  37.     def exitHelper(self):
  38.         if self.nodeIf is not None:
  39.             self.nodeIf.stop()
  40.    
  41.    
  42.     def exceptHelper(self, type, value, tb):
  43.        if hasattr(sys, 'ps1') or not sys.stderr.isatty():
  44.           # we are in interactive mode or we don't have a tty-like
  45.           # device, so we call the default hook
  46.           sys.__excepthook__(type, value, tb)
  47.        else:
  48.           import traceback, pdb
  49.           # we are NOT in interactive mode, print the exception...
  50.           traceback.print_exception(type, value, tb)
  51.           print 'ERROR ERROR ERROR'
  52.           self.exitHelper()
  53.          
  54.          
  55. #    def install_thread_excepthook(self):
  56. #        """Workaround for sys.excepthook thread bug
  57. #           (https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1230540&group_id=5470).
  58. #           Call once from __main__ before creating any threads.
  59. #           If using psyco, call psyco.cannotcompile(threading.Thread.run)
  60. #           since this replaces a new-style class method.
  61. #        """
  62. #        import sys, threading
  63. #        run_old = threading.Thread.run
  64. #        def run(*args, **kwargs):
  65. #            try:
  66. #                run_old(*args, **kwargs)
  67. #            except (KeyboardInterrupt, SystemExit):
  68. #                raise
  69. #            except:
  70. #                sys.excepthook(*sys.exc_info())
  71. #        threading.Thread.run = run
  72.        
  73.    
  74.     def run(self):
  75.         try:
  76.             demoPath = os.path.dirname(__file__)
  77.             os.chdir(demoPath)
  78.         except:
  79.             return
  80.        
  81.         print 'Start logging'
  82.         log.basicConfig(level=log.DEBUG)
  83.        
  84.         print 'Get config options from command line or config file'
  85.         cfg = DaemonConfig()
  86.        
  87.         try:
  88.             opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
  89.         except getopt.GetoptError:
  90.             print 'Invalid usage'
  91.             usage()
  92.             sys.exit(2)
  93.      #   output = None
  94.      #   verbose = False
  95.         for o, a in opts:
  96.             if o == "-v":
  97.                 pass
  98.      #           verbose = True
  99.             if o in ("-h", "--help"):
  100.                 usage()
  101.                 sys.exit()
  102.             if o in ("-o", "--output"):
  103.                 pass
  104.     #            output = a
  105.    
  106.         print 'Init and load filters and spaces'
  107.     #    cfg.filterCfg.importFilter('DefaultFilter')
  108.     #    cfg.stateSpaceCfg.importSpace('DefaultStateSpace')
  109.         cfg.stateSpaceCfg.loadSpaces()
  110.         cfg.filterCfg.loadFilters()
  111.         cfg.setupFilterBindings()
  112.         cfg.setupFilterChain()
  113.          
  114.         print 'Start selected can interface'
  115.         ''' nodeif thread launch '''
  116.         pktHandler = CanPktHandler1(cfg)
  117.        
  118.      #   cfg = NodeIfCanStim.DEFAULT_CONFIG
  119.      #   nodeif = NodeIfCanStim(cfg, pkthandler)
  120.         ifConfig = NodeIfSerial.DEFAULT_CONFIG
  121.    
  122.         self.nodeIf = NodeIfSerial(pktHandler, self.exceptHelper, ifConfig)
  123.        
  124.         if not self.nodeIf.start():
  125.             print 'FATAL: Failed to initialize node interface'
  126.             sys.exit(-1)
  127.         else:
  128.             atexit.register(self.exitHelper)
  129.             sys.excepthook = self.exceptHelper
  130.  
  131.         print 'Initialize/gather info on connected can nodes and load associated state'
  132.         print 'Start selected TCP and UDP server(s)'
  133.         # server threads launch
  134.        
  135.         print 'CanDaemon v1 ready'
  136.         print 'Enter command or type \"help\" for a list of commands'
  137.         terminated = False
  138.         while not terminated:
  139.             input = raw_input('> ').strip().lower()
  140.             if input == 'quit' or input == 'exit':
  141.                 terminated = True
  142.             elif input == 'help':
  143.                 helpCommands()
  144.        
  145.         print 'Shutdown'
  146.         self.nodeIf.stop()
  147.         cfg.stateSpaceCfg.saveSpaces()
  148.         cfg.filterCfg.saveFilters()
  149.  
  150. #---------------------------------------------------------------------------
  151.  
  152. def main():
  153.     daemonApp = CanDaemon()
  154. #    daemon.install_thread_excepthook()
  155.     daemonApp.run()
  156.  
  157. #---------------------------------------------------------------------------
  158.  
  159. if __name__ == '__main__':
  160.     __name__ = 'Main'
  161.     main()
  162.