Subversion Repositories HomeAutomation

Rev

Rev 736 | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | SVN | RSS feed

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