Exemplo n.º 1
0
class TestClientServer(unittest.TestCase):

    def setUp(self):
        # modbus server
        self.server = ModbusServer(port=5020, no_block=True)
        self.server.start()
        # modbus client
        self.client = ModbusClient(port=5020)
        self.client.open()

    def tearDown(self):
        self.client.close()

    def test_read_and_write(self):
        # word space
        self.assertEqual(self.client.read_holding_registers(0), [0], 'Default value is 0 when server start')
        self.assertEqual(self.client.read_input_registers(0), [0], 'Default value is 0 when server start')
        # single read/write
        self.assertEqual(self.client.write_single_register(0, 0xffff), True)
        self.assertEqual(self.client.read_input_registers(0), [0xffff])
        # multi-write at max size
        words_l = [randint(0, 0xffff)] * 0x7b
        self.assertEqual(self.client.write_multiple_registers(0, words_l), True)
        self.assertEqual(self.client.read_holding_registers(0, len(words_l)), words_l)
        self.assertEqual(self.client.read_input_registers(0, len(words_l)), words_l)
        # write over sized
        words_l = [randint(0, 0xffff)] * 0x7c
        self.assertEqual(self.client.write_multiple_registers(0, words_l), None)
        # bit space
        self.assertEqual(self.client.read_coils(0), [False], 'Default value is False when server start')
        self.assertEqual(self.client.read_discrete_inputs(0), [False], 'Default value is False when server start')
        # single read/write
        self.assertEqual(self.client.write_single_coil(0, True), True)
        self.assertEqual(self.client.read_coils(0), [True])
        self.assertEqual(self.client.read_discrete_inputs(0), [True])
        # multi-write at min size
        bits_l = [getrandbits(1)] * 0x1
        self.assertEqual(self.client.write_multiple_coils(0, bits_l), True)
        self.assertEqual(self.client.read_coils(0, len(bits_l)), bits_l)
        self.assertEqual(self.client.read_discrete_inputs(0, len(bits_l)), bits_l)
        # multi-write at max size
        bits_l = [getrandbits(1)] * 0x7b0
        self.assertEqual(self.client.write_multiple_coils(0, bits_l), True)
        self.assertEqual(self.client.read_coils(0, len(bits_l)), bits_l)
        self.assertEqual(self.client.read_discrete_inputs(0, len(bits_l)), bits_l)
        # multi-write over sized
        bits_l = [getrandbits(1)] * 0x7b1
        self.assertEqual(self.client.write_multiple_coils(0, bits_l), None)
Exemplo n.º 2
0
                    help='RTU port (default is %d)' % DEF_MB_PORT)
parser.add_argument('id_str', type=str,
                    help='ID string')
parser.add_argument('-a', '--id_addr', type=int, default=DEF_ID_ADDR,
                    help='ID address (default is %d)' % DEF_ID_ADDR)
args = parser.parse_args()

# init modbus client
c = ModbusClient(host=args.ip_rtu, port=args.port_rtu)

# open TCP link
if not c.open():
    print("unable to connect to " + args.ip_rtu + ":" + str(args.port_rtu))
    sys.exit(1)

# format id list (8 chars max)
id_list = [ord(x) for x in args.id_str.ljust(8)][:8]

# do modbus write
print('write ID %s at @%d' % (id_list, args.id_addr))
regs = c.write_multiple_registers(args.id_addr, id_list)

# print status
if regs:
    print('ok')
else:
    print('error')

# close TCP link
c.close()
Exemplo n.º 3
0
class modBusWriteRead():
    def __init__(self,client_host):
        self.client_host = client_host
        self.client_port = 502
        self.err_list = []
        self.connect() #buradan bağlantı yapılacak;

    def connect(self):
        self.modbus_c = ModbusClient()
        self.modbus_c.host(self.client_host)
        self.modbus_c.port(self.client_port)
        if not self.modbus_c.is_open():
            if not self.modbus_c.open():
                text="unable to connect to " + self.client_host + ":" + str(self.client_port)
                print(text)

    def write_data_reg(self,address,list):
        if self.modbus_c.open():
            if len(list)>120:
                sent_list = self.hazirla_dizi_to_write(list)
                i = 0
                hedef_reg_taban = address
                for list_to_sent in sent_list:
                    hedef_reg = hedef_reg_taban + (i * 120)
                    a = self.modbus_c.write_multiple_registers(hedef_reg, list_to_sent)
                    if a == None or a == False:
                        self.err_list.append(False)
                    i += 1
            else:
                a = self.modbus_c.write_multiple_registers(address, list)
                if a == None or a == False:
                    self.err_list.append(False)
        if len(self.err_list) > 0:
            self.err_list = []
            pass
            # dikkat
            # print("data göndermede hata oluştu, tekrar deneyin !")

    def hazirla_dizi_to_write(self,d_list):
        # eğer gönderilecek değer 120 den büyük ise aşağıdaki fonksiyon 120 lik diziler döndürüyor
        r_list = []
        g_list = []
        i = 0
        for index in range(len(d_list)):
            g_list.append(d_list[index])
            i += 1
            if i > 119:
                i = 0
                r_list.append(g_list)
                g_list = []
            if (len(d_list) - 1) == index and i < 119:
                r_list.append(g_list)
        return r_list

    def read_data_reg(self,address,reg_count,read_float=False ):
        # burada 16 lık ya da float olarak okunabiliyor
        if self.modbus_c.is_open():
            if read_float == False:
                plc_list_int = self.modbus_c.read_holding_registers(address, reg_count)
                return plc_list_int
            elif read_float == True:
                plc_list_f_16=self.modbus_c.read_holding_registers(address,reg_count)
                if plc_list_f_16 is not None:
                    plc_list_float=self.long_to_float(plc_list_f_16)
                    return plc_list_float

    def long_to_float(self,list_16):
        list_float=[]
        list_16.reverse()
        list_long=utils.word_list_to_long(list_16)
        for any_long in list_long:
            list_float.append(utils.decode_ieee(any_long))
        list_float.reverse()
        return list_float
Exemplo n.º 4
0
if not c.is_open():
    if not c.open():
        print("unable to connect to " + client_host + ":" + str(client_port))


def int32_to_int8(n):
    mask = (1 << 16) - 1
    return [(n >> k) & mask for k in range(0, 32, 16)]


var_int = utils.encode_ieee(7.5)
print(var_int)
sonuc=int32_to_int8(var_int)
print(sonuc)
if c.is_open():
    # read 10 registers at address 0, store result in regs list
    print(var_int)
    c.write_single_register(0,5)
    c.write_multiple_registers(1,sonuc)

    regs = c.read_holding_registers(0,100)
    # if success display registers
    if regs:
        print("reg ad #0 to 9: " , regs)

    bits = c.read_discrete_inputs(0, 16)
    # if success display registers
    if bits:
        print("bit ad #0 to 9: " + str(bits))
Exemplo n.º 5
0
import serial
import subprocess as sp
from pyModbusTCP.client import ModbusClient

global systems

systems={'modbus':False, 'serial':False,'bluetooth':False}


MODBUS_SERVER_IP="192.168.0.200"
c = ModbusClient(host=MODBUS_SERVER_IP, port=502, auto_open=True)
c.host(MODBUS_SERVER_IP)
c.port(502)


if c.write_multiple_registers(133, [1, 0]):
    systems['modbus'] = True
else:
    systems['modbus'] = False

if not systems['modbus']:
    MODBUS_SERVER_IP="127.0.0.1"
    c = ModbusClient(host=MODBUS_SERVER_IP, port=502, auto_open=True)
    c.host(MODBUS_SERVER_IP)
    c.port(502)
    if c.write_multiple_registers(133, [1, 0]):
        systems['modbus'] = True
    # else:
        # import os
        # os.system("sudo python3 sync_server.py")  
        #time.sleep(3)
Exemplo n.º 6
0
class roebot():
    def __init__(self, threadpool):
        self.tp = Thread(target=self.polling_thread)
        self.threadpool = threadpool
        self.regList = []
        self.tp.start()
        self.pictureIndex = 0
        self.camera = Camera.Camera()
        self.imageCv = imageProcessing2.imageProcessing()
        self.imageList = []

        # self.modbusclient = r_w_float_modbus.FloatModbusClient(ModbusClient)

    def poll_command(self):
        print("Polling server for commands")
        commandpoll = False
        # display loop (in main thread)
        while not commandpoll:

            # print regs list (with thread lock synchronization)

            if self.regList:
                command = self.regList[0]
                if command in range(1, 6):

                    if self.sendIntModbus(0, 0):

                        self.switch_case(command)

    # Takes picture of tray.
    def takePicture(self):
        print("Executing take picture")

        RoeImage = self.camera.takePicture(330, self.pictureIndex)
        self.pictureIndex += 1
        self.imageCv.processingQueue.append(RoeImage)
        self.switch_case(0)

    # modbus polling thread
    def polling_thread(self):
        self.client = ModbusClient(host=SERVER_HOST, port=SERVER_PORT)
        isOpen = False
        # polling loop
        while True:
            # keep TCP open
            if not self.client.is_open():
                print("unable to connect to " + SERVER_HOST + ":" +
                      str(SERVER_PORT))
                self.client.open()

            if self.client.is_open():
                if not isOpen:
                    print("connected to " + SERVER_HOST + ":" +
                          str(SERVER_PORT))
                    isOpen = True

            # do modbus reading on socket
            reg_list = self.client.read_holding_registers(0, 10)
            # if read is ok, store result in regs (with thread lock synchronization)
            if reg_list:
                with regs_lock:
                    self.regList = list(reg_list)
            # 1s before next polling
            time.sleep(0.2)

    # send int to modbusServer
    def sendIntModbus(self, value, address):

        return self.client.write_single_register(address, value)

    # process images by creating a RoeImage adding them to roeimage Queue
    def processImages(self):

        if len(self.imageList) == 0:
            print("processing images")
            imageList1, processing = self.imageCv.processImages()
            self.imageList = imageList1
        else:
            self.imageList = []

        self.switch_case(0)

    def sendcoord(self, arrayX, arrayY):
        sending = False

        if self.client.write_multiple_registers(10, arrayX):
            print("write ok")
            sending = True
        else:
            print("write error")
            sending = False

        return sending

    # generate coordinate list relative to the robot

    def generatecoordinateList(self):
        print("generating cordinate list")
        coordList = []
        for roeImage in self.imageList:
            list = roeImage.getRoePositionMillimeter()

            if len(list) > 0:

                for i in range(len(list)):
                    coordinate = list[i]

                    xpos = coordinate.getxCoor() + (
                        (int(roeImage.getPictureIndex()) + 1) * 300)
                    ypos = coordinate.getyCoor()

                    newcoord = Coordinate.coordinate(xpos, ypos)

                    coordList.append(newcoord)

        return coordList

    def sendCordToPLC(self):
        print("sending to PLC")
        arrayX = []
        arrayY = []
        corrdList = self.generatecoordinateList()
        for cord in corrdList:
            arrayX.append(cord.getxCoor())
            arrayY.append(cord.getyCoor())
        print(arrayX)
        self.client.write_multiple_registers(10, arrayX)

        #sleep so register can be updated
        time.sleep(1)
        self.imageCv.processingQueue = []
        self.imageList = []
        self.switch_case(0)

    def getImageList(self):
        print(len(self.imageList))
        time.sleep(1)
        self.switch_case(0)

    def switch_case(self, command):

        switcher = {
            0: self.poll_command,
            2: self.takePicture,
            3: self.processImages,
            4: self.sendCordToPLC,
            5: self.getImageList
        }
        # Get the function from switcher dictionary
        func = switcher.get(command, lambda: "Invalid command")
        # Execute the function
        return func()
minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True

# TCP auto connect on first modbus request
c = ModbusClient(host="localhost", port=502, auto_open=True)

# TCP auto connect on modbus request, close after it
c = ModbusClient(host="127.0.0.1", auto_open=True, auto_close=True)

c = ModbusClient()
c.host("localhost")
c.port(502)
# managing TCP sessions with call to c.open()/c.close()
c.open()

#Read 2x 16 bits registers at modbus address 0 :
regs = c.read_holding_registers(0, 2)
if regs:
    print(regs)
else:
    print("read error")

#Write value 44 and 55 to registers at modbus address 10 :
if c.write_multiple_registers(10, [44, 55]):
    print("write ok")
else:
    print("write error")

data1 = np.zeros(16)
data2 = np.zeros(16)
data3 = np.zeros(8)
d
Exemplo n.º 8
0
def modbus_polling_thread():
    global DATA_TO_HMI_HOLDING, DATA_FROM_HMI_HOLDING, DATA_FROM_HMI_COIL, DATA_TO_HMI_COIL
    global start_addr, test_signal_coil, test_signal_holding
    global addr_num
    c = ModbusClient(host=MODBUS_SPEC['SERVER_HMI_HOST'],
                     port=MODBUS_SPEC['SERVER_HMI_PORT'])
    # polling loop
    while True:
        # keep TCP open
        if not c.is_open():
            c.open()
        # read data from hmi(holding & coil)
        DATA_FROM_HMI_HOLDING = c.read_holding_registers(
            MDS_ADDR_R['addr_start_holding_R'],
            MDS_ADDR_R['addr_num_holding_R'])
        # if read is ok, store result in regs (with thread lock synchronization)
        #time.sleep(0.)
        DATA_FROM_HMI_COIL = c.read_coils(MDS_ADDR_R['addr_start_coil_R'],
                                          MDS_ADDR_R['addr_num_coil_R'])
        print('Holding %s COil %s', DATA_FROM_HMI_HOLDING, DATA_FROM_HMI_COIL)
        print('reading form mds slave')
        if DATA_FROM_HMI_HOLDING:
            with regs_lock:
                print('with regs_lock_holding')
                #for demonstrate usage
                #DATA_FROM_HMI = list(DATA_FROM_HMI_HOLDING)
                ###
                holding_payload_to_ros = {}
                #publish holding register data to ros driver
                if mqtt_client is not None:
                    #insert data from holding register
                    for x in range(0, MDS_ADDR_R['addr_num_holding_R']):
                        holding_payload_to_ros[
                            str(MDS_ADDR_R['addr_start_holding_R'] +
                                x)] = DATA_FROM_HMI_HOLDING[x]
                        #transfer dict to string with json.dumps(payload_)
                    #print('holding payload to ros driver %s',sort_key(holding_payload_to_ros))
                    input_holding = json.dumps(holding_payload_to_ros)
                    #transfer string to string with json.loads(input)
                    mqtt_client.publish(topic='DATA_TO_ROS_DRIVER_HOLDING_R',
                                        payload=input_holding,
                                        qos=2,
                                        retain=False)
                    time.sleep(0.05)
        if DATA_FROM_HMI_COIL:
            #insert data from coil register
            coil_payload_to_ros = {}
            for y in range(0, MDS_ADDR_R['addr_num_coil_R']):
                coil_payload_to_ros[str(MDS_ADDR_R['addr_start_coil_R'] +
                                        y)] = DATA_FROM_HMI_COIL[y]
            input_coil = json.dumps(coil_payload_to_ros)
            #print('coil payload to ros driver %s',sort_key(coil_payload_to_ros))
            if mqtt_client is not None:
                mqtt_client.publish(topic='DATA_TO_ROS_DRIVER_COIL_R',
                                    payload=input_coil,
                                    qos=2,
                                    retain=False)

        else:
            print('listenning to holding register fail')

        #write data to hmi(holding & coil)
        with msg_lock_w:
            print('with msg_lock_coiling')
            print('DATA_TO_HMI_HOLDING %s', DATA_TO_HMI_HOLDING)
            if DATA_TO_HMI_HOLDING is not None and len(
                    DATA_TO_HMI_HOLDING) is not 0 and len(
                        DATA_TO_HMI_HOLDING
                    ) == MDS_ADDR_W['addr_num_holding_W']:
                print('SDSDASD %s', MDS_ADDR_W['addr_start_holding_W'])
                if c.write_multiple_registers(
                        MDS_ADDR_W['addr_start_holding_W'],
                        DATA_TO_HMI_HOLDING):
                    print('write holding ok from addr %s with list %s',
                          MDS_ADDR_W['addr_start_holding_W'],
                          DATA_TO_HMI_HOLDING)
                else:
                    print('write holding error from addr %s with list %s',
                          MDS_ADDR_W['addr_start_holding_W'],
                          DATA_TO_HMI_HOLDING)
            else:
                print('holding data missing with %s with desired len %s',
                      DATA_TO_HMI_HOLDING, MDS_ADDR_W['addr_num_holding_W'])
            time.sleep(0.1)
            if DATA_TO_HMI_COIL is not None and len(
                    DATA_TO_HMI_COIL) is not 0 and len(
                        DATA_TO_HMI_COIL) == MDS_ADDR_W['addr_num_coil_W']:
                print(MDS_ADDR_W['addr_start_coil_W'])
                is_ok = c.write_multiple_coils(MDS_ADDR_W['addr_start_coil_W'],
                                               DATA_TO_HMI_COIL)
                if is_ok:
                    print('write coil ok from addr %s with list %s',
                          MDS_ADDR_W['addr_start_coil_W'], DATA_TO_HMI_COIL)
                else:
                    print('write coil error from addr %s with list %s',
                          MDS_ADDR_W['addr_start_coil_W'], DATA_TO_HMI_COIL)
            else:
                print('coil data missing with %s with desired len %s',
                      DATA_TO_HMI_COIL, MDS_ADDR_W['addr_num_coil_W'])
            #write something to HMI
        time.sleep(0.1)