Subversion Repositories HomeAutomation

Rev

Rev 737 | Rev 739 | Go to most recent revision | Show entire file | Regard whitespace | Details | Blame | Last modification | View Log | SVN | RSS feed

Rev 737 Rev 738
Line 3... Line 3...
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
import time
8
 
9
 
9
from CanPktHandlerBase import CanPktHandlerBase
10
from CanPktHandlerBase import CanPktHandlerBase
10
from CanPktHandler1 import CanPktHandler1
11
from CanPktHandler1 import CanPktHandler1
11
 
12
 
12
from NodeIfBase import NodeIfBase
13
from NodeIfBase import NodeIfBase
Line 18... Line 19...
18
daemonApp = None
19
daemonApp = None
19
 
20
 
20
class CanDaemon():
21
class CanDaemon():
21
   
22
   
22
    nodeIf = None
23
    nodeIf = None
-
 
24
    ifNotifier = None
-
 
25
    terminated = False
-
 
26
   
-
 
27
    class IfNotifier():
-
 
28
   
-
 
29
        UNDEFINED = 0
-
 
30
        TERMINATE = 1
-
 
31
   
-
 
32
        def notify(self, msg):
-
 
33
            if msg == self.TERMINATE:
-
 
34
                print 'Main terminate notify'
-
 
35
                self.terminated = True
-
 
36
            else:
-
 
37
                print 'UNDEFINED NOTIFY'
23
   
38
       
24
    def __init__ (self):
39
    def __init__ (self):
25
        pass
40
        pass
26
   
41
   
27
   
42
   
Line 35... Line 50...
35
   
50
   
36
   
51
   
37
    def exitHelper(self):
52
    def exitHelper(self):
38
        if self.nodeIf is not None and self.nodeIf.running():
53
        if self.nodeIf is not None and self.nodeIf.running():
39
            self.nodeIf.stop()
54
            self.nodeIf.stop()
40
   
-
 
41
   
-
 
42
    def exceptHelper(self, type, value, tb):
-
 
43
          import traceback
-
 
44
          traceback.print_exc()
-
 
45
          print 'Exception in main program, shutting down threads'
-
 
46
          self.exitHelper()
-
 
47
   
55
         
48
   
56
   
49
    def run(self):
57
    def run(self):
50
        try:
58
        try:
51
            demoPath = os.path.dirname(__file__)
59
            demoPath = os.path.dirname(__file__)
52
            os.chdir(demoPath)
60
            os.chdir(demoPath)
53
        except:
61
        except:
54
            return
62
            return
55
       
63
       
56
        print 'INIT: Start logging'
64
        print 'INIT: Start logging'
57
        log.basicConfig(level=log.DEBUG)
65
        log.basicConfig(level=log.DEBUG)
58
       
66
       
59
        print 'INIT: Get config options from command line / config file'
67
        print 'INIT: Get config options from command line / config file'
60
        cfg = DaemonConfig()
68
        cfg = DaemonConfig()
61
       
69
       
62
        try:
70
        try:
63
            opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
71
            opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
64
        except getopt.GetoptError:
72
        except getopt.GetoptError:
65
            print 'Invalid usage'
73
            print 'Invalid usage'
66
            usage()
74
            usage()
67
            sys.exit(2)
75
            sys.exit(2)
68
     #   output = None
76
     #   output = None
69
     #   verbose = False
77
     #   verbose = False
70
        for o, a in opts:
78
        for o, a in opts:
71
            if o == "-v":
79
            if o == "-v":
72
                pass
80
                pass
73
     #           verbose = True
81
     #           verbose = True
74
            if o in ("-h", "--help"):
82
            if o in ("-h", "--help"):
75
                usage()
83
                usage()
76
                sys.exit()
84
                sys.exit()
77
            if o in ("-o", "--output"):
85
            if o in ("-o", "--output"):
Line 86... Line 94...
86
        cfg.setupFilterBindings()
94
        cfg.setupFilterBindings()
87
        cfg.setupFilterChain()
95
        cfg.setupFilterChain()
88
       
96
       
89
        print 'INIT: Starting selected can interface'
97
        print 'INIT: Starting selected can interface'
90
        ''' nodeif thread launch '''
98
        ''' nodeif thread launch '''
-
 
99
        self.ifNotifier = self.IfNotifier()
91
        pktHandler = CanPktHandler1(cfg)
100
        pktHandler = CanPktHandler1(cfg)
92
       
101
       
93
     #   cfg = NodeIfCanStim.DEFAULT_CONFIG
102
        ifConfig = NodeIfCanStim.DEFAULT_CONFIG
94
     #   nodeif = NodeIfCanStim(cfg, pkthandler)
103
        self.nodeIf = NodeIfCanStim(ifConfig, pktHandler, self.ifNotifier)
95
        ifConfig = NodeIfSerial.DEFAULT_CONFIG
104
 #       ifConfig = NodeIfSerial.DEFAULT_CONFIG
96
   
105
   
97
        atexit.register(self.exitHelper)
106
        atexit.register(self.exitHelper)
98
        sys.excepthook = self.exceptHelper
107
 #       sys.excepthook = self.exceptHelper
99
   
-
 
100
        self.nodeIf = NodeIfSerial(pktHandler, ifConfig)
108
 #       self.nodeIf = NodeIfSerial(pktHandler, ifConfig)
101
       
109
       
102
        if not self.nodeIf.start():
110
        if not self.nodeIf.start():
103
            print 'FATAL: Failed to initialize node interface.'
111
            print 'FATAL: Failed to initialize node interface.'
104
            print 'This may indicate that the interface is busy or that you don\'t have ' \
112
            print 'This may indicate that the interface is unavailable, ' \
105
                  'permission to access it.'
113
                  'or that you do not have permission to access it.'
106
            sys.exit(-1)
114
            sys.exit(-1)
107
 
115
 
108
        print 'Initialize/gather info on connected can nodes and load associated state'
116
        print 'Initialize/gather info on connected can nodes and load associated state'
109
        print 'Start selected TCP and UDP server(s)'
117
        print 'Start selected TCP and UDP server(s)'
110
        # server threads launch
118
        # server threads launch
111
       
119
       
112
        print 'CanDaemon v1 ready'
120
        print 'CanDaemon v1 ready'
113
        print 'Enter command or type \"help\" for a list of commands'
121
        print 'Enter command or type \"help\" for a list of commands'
114
        terminated = False
-
 
-
 
122
 
115
        while not terminated:
123
        while not self.terminated:
116
            input = raw_input('> ').strip().lower()
124
            input = raw_input('> ').strip().lower()
117
            if input == 'quit' or input == 'exit':
125
            if input == 'quit' or input == 'exit':
118
                terminated = True
126
                self.terminated = True
119
            elif input == 'help':
127
            elif input == 'help':
120
                helpCommands()
128
                self.helpCommands()
-
 
129
            else:
-
 
130
                print 'Unknown command: ' + input
121
       
131
       
122
        print 'Shutdown'
132
        print 'Shutdown'
-
 
133
        if self.nodeIf.running():
123
        self.nodeIf.stop()
134
            self.nodeIf.stop()
-
 
135
 
124
        cfg.stateSpaceCfg.saveSpaces()
136
        cfg.stateSpaceCfg.saveSpaces()
125
        cfg.filterCfg.saveFilters()
137
        cfg.filterCfg.saveFilters()
126
 
138
       
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.
139
        time.sleep(0.1) # wait for threads
133
#       If using psyco, call psyco.cannotcompile(threading.Thread.run)
140
        sys.exit(0) # will except if there are threads remaining
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
-
 
147
       
141
 
148
#---------------------------------------------------------------------------
142
#---------------------------------------------------------------------------
149
 
143
 
150
def main():
144
def main():
151
    daemonApp = CanDaemon()
145
    daemonApp = CanDaemon()