コード例 #1
0
def server_stop(host, port):
    # parse args
    #parser = argparse.ArgumentParser()
    #parser.add_argument('-H', '--host', type=str, default='localhost', help='Host')
    #parser.add_argument('-p', '--port', type=int, default=502, help='TCP port')
    #args = parser.parse_args()
    # start modbus server
    #print("humo")
    server = ModbusServer(host, int(port), no_block=False)
    server.stop()
コード例 #2
0
ファイル: server.py プロジェクト: samuel-cavalcanti/EIMOZAO
def main():
    ip, port = load_serve_config('server_info.json')
    server = ModbusServer(ip, port)
    print('PAI TA ÔN')
    print(f'IP: {ip} port {port}')

    try:
        server.start()

    except Exception as e:
        print(f'shutdown server with exception: {e}')
        server.stop()
        print('server is offline')
コード例 #3
0
def main():
    """ Main method to run the pyModbusTCP server for the test modbus endpoint.
    """
    try:
        print('modbus main start')
        # Set holding register data to their address.
        # Set coils to address % 3 == 0.
        for i in range(0x4000):
            print('Setting word {} to {}'.format(i, i))
            print('Setting bits {} to {}'.format(i, i % 3 == 0))
            DataBank.set_words(i, [i])
            DataBank.set_bits(i, [i % 3 == 0])

        server = ModbusServer(host='', port=1502, no_block=True)
        server.start()
        print('started modbus server')
        global STOP_SERVER
        while not STOP_SERVER:
            time.sleep(.01)
        server.stop()
        print('stopped modbus server')
    except Exception:
        traceback.print_exc()
コード例 #4
0
#!/bin/python

from pyModbusTCP.server import ModbusServer, DataBank
from time import sleep
from random import uniform

# Create an instance of ModbusServer
server = ModbusServer("127.0.0.1", 502, no_block=True)

try:
    print("Start server...")
    server.start()
    print("Server is online")
    state = [0]
    while True:
        DataBank.set_words(0, [int(uniform(0, 100))])
        if state != DataBank.get_words(1):
            state = DataBank.get_words(1)
            print("Value of Register 1 has changed to " + str(state))
        sleep(0.5)

except:
    print("Shutdown server ...")
    server.stop()
    print("Server is offline")
コード例 #5
0
class AsyncModbusServer(object):
    """Asynchronous Modbus TCP Server."""
    def __init__(
        self,
        *,
        host='127.0.0.1',
        bit_adr=0,
        bit_num=1,
        word_adr=0,
        word_num=1,
        timeout=1,
        name='Modbus Server',
    ):
        """Init server."""
        self.port = mdb.PORT
        self.host = host
        self.bit_adr = bit_adr
        self.bit_num = bit_num
        self.word_adr = word_adr
        self.word_num = word_num
        self.timeout = timeout
        self.name = name
        self.connection = None
        try:
            self.connection = ModbusServer(
                host=self.host,
                port=self.port,
                no_block=True,
            )
            self.connection.start()
        except Exception as err:
            raise ServerError('Error with server', err)

    async def run_task(self):
        """Run asyncio server."""
        executor = concurrent.futures.ThreadPoolExecutor(max_workers=3, )
        task = asyncio.create_task(self._awaitable(executor))
        await task

    def stop(self):
        """Stop server."""
        self.connection.stop()

    def _setup(self):
        cryptogen = SystemRandom()
        while True:
            bits_value = [
                bool(cryptogen.randrange(2)) for indx in range(self.bit_num)
            ]
            words_value = [
                cryptogen.randrange(10) for _ in range(self.word_num)
            ]
            try:
                DataBank.set_bits(self.bit_adr, bits_value)
                DataBank.set_words(self.word_adr, words_value)
            except Exception as err:
                raise ServerError('Error with writing', err)

    async def _awaitable(self, executor):
        loop = asyncio.get_event_loop()
        while True:
            await loop.run_in_executor(
                executor,
                self._setup(),
            )
            await asyncio.sleep(self.timeout)