~ubuntu-branches/ubuntu/raring/pymodbus/raring-proposed

« back to all changes in this revision

Viewing changes to examples/common/modbus-simulator.py

  • Committer: Package Import Robot
  • Author(s): Thomas Bechtold
  • Date: 2012-10-27 12:55:45 UTC
  • mfrom: (1.1.2)
  • Revision ID: package-import@ubuntu.com-20121027125545-60e94bpztv8vx8om
Tags: 1.1.0-1
* New upstream release.
* debian/control: Add Thomas Bechtold to Uploaders.
* debian/watch: Use github tags for new releases.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/env python
2
 
'''
3
 
An example of creating a fully implemented modbus server
4
 
with read/write data as well as user configurable base data
5
 
'''
6
 
 
7
 
import pickle
8
 
from optparse import OptionParser
9
 
from twisted.internet import reactor
10
 
 
11
 
from pymodbus.server.async import StartTcpServer
12
 
from pymodbus.datastore import ModbusServerContext,ModbusSlaveContext
13
 
 
14
 
#--------------------------------------------------------------------------#
15
 
# Logging
16
 
#--------------------------------------------------------------------------#
17
 
import logging
18
 
logging.basicConfig()
19
 
 
20
 
server_log   = logging.getLogger("pymodbus.server")
21
 
protocol_log = logging.getLogger("pymodbus.protocol")
22
 
 
23
 
#---------------------------------------------------------------------------#
24
 
# Extra Global Functions
25
 
#---------------------------------------------------------------------------#
26
 
# These are extra helper functions that don't belong in a class
27
 
#---------------------------------------------------------------------------#
28
 
import getpass
29
 
def root_test():
30
 
    ''' Simple test to see if we are running as root '''
31
 
    return True # removed for the time being as it isn't portable
32
 
    #return getpass.getuser() == "root"
33
 
 
34
 
#--------------------------------------------------------------------------#
35
 
# Helper Classes
36
 
#--------------------------------------------------------------------------#
37
 
class ConfigurationException(Exception):
38
 
    ''' Exception for configuration error '''
39
 
 
40
 
    def __init__(self, string):
41
 
        ''' Initializes the ConfigurationException instance
42
 
 
43
 
        :param string: The message to append to the exception
44
 
        '''
45
 
        Exception.__init__(self, string)
46
 
        self.string = string
47
 
 
48
 
    def __str__(self):
49
 
        ''' Builds a representation of the object
50
 
 
51
 
        :returns: A string representation of the object
52
 
        '''
53
 
        return 'Configuration Error: %s' % self.string
54
 
 
55
 
class Configuration:
56
 
    '''
57
 
    Class used to parse configuration file and create and modbus
58
 
    datastore.
59
 
 
60
 
    The format of the configuration file is actually just a
61
 
    python pickle, which is a compressed memory dump from
62
 
    the scraper.
63
 
    '''
64
 
 
65
 
    def __init__(self, config):
66
 
        '''
67
 
        Trys to load a configuration file, lets the file not
68
 
        found exception fall through
69
 
 
70
 
        :param config: The pickled datastore
71
 
        '''
72
 
        try:
73
 
            self.file = open(config, "r")
74
 
        except Exception:
75
 
            raise ConfigurationException("File not found %s" % config)
76
 
 
77
 
    def parse(self):
78
 
        ''' Parses the config file and creates a server context
79
 
        '''
80
 
        handle = pickle.load(self.file)
81
 
        try: # test for existance, or bomb
82
 
            dsd = handle['di']
83
 
            csd = handle['ci']
84
 
            hsd = handle['hr']
85
 
            isd = handle['ir']
86
 
        except Exception:
87
 
            raise ConfigurationException("Invalid Configuration")
88
 
        slave = ModbusSlaveContext(d=dsd, c=csd, h=hsd, i=isd)
89
 
        return ModbusServerContext(slaves=slave)
90
 
 
91
 
#--------------------------------------------------------------------------#
92
 
# Main start point
93
 
#--------------------------------------------------------------------------#
94
 
def main():
95
 
    ''' Server launcher '''
96
 
    parser = OptionParser()
97
 
    parser.add_option("-c", "--conf",
98
 
                    help="The configuration file to load",
99
 
                    dest="file")
100
 
    parser.add_option("-D", "--debug",
101
 
                    help="Turn on to enable tracing",
102
 
                    action="store_true", dest="debug", default=False)
103
 
    (opt, arg) = parser.parse_args()
104
 
 
105
 
    # enable debugging information
106
 
    if opt.debug:
107
 
        try:
108
 
            server_log.setLevel(logging.DEBUG)
109
 
            protocol_log.setLevel(logging.DEBUG)
110
 
        except Exception, e:
111
 
            print "Logging is not supported on this system"
112
 
 
113
 
    # parse configuration file and run
114
 
    try:
115
 
        conf = Configuration(opt.file)
116
 
        StartTcpServer(context=conf.parse())
117
 
    except ConfigurationException, err:
118
 
        print err
119
 
        parser.print_help()
120
 
 
121
 
#---------------------------------------------------------------------------#
122
 
# Main jumper
123
 
#---------------------------------------------------------------------------#
124
 
if __name__ == "__main__":
125
 
    if root_test():
126
 
        main()
127
 
    else: print "This script must be run as root!"
128