Ejemplo n.º 1
0
 def test_decode_ieee(self):
     # test IEEE NaN
     self.assertTrue(math.isnan(utils.decode_ieee(0x7fffffff)))
     # test +/- infinity
     self.assertTrue(math.isinf(utils.decode_ieee(0xff800000)))
     self.assertTrue(math.isinf(utils.decode_ieee(0x7f800000)))
     # test some values
     self.assertAlmostEqual(utils.decode_ieee(0x3e99999a), 0.3)
     self.assertAlmostEqual(utils.decode_ieee(0xbe99999a), -0.3)
Ejemplo n.º 2
0
 def read_float(self, address, number=1):
     reg_l = self.read_holding_registers(address, number * 2)
     if reg_l:
         return [
             utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l)
         ]
     else:
         reg_l = [16000, 16000]
         return [
             utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l)
         ]
Ejemplo n.º 3
0
    def __readModbus(self, address, data_format="Float"):

        # open the Modbus connection if neccessary
        if not self.modbus.is_open():
            self.modbus.open()

        # default data length is 1 ('U16')
        length = 1

        # if we are retreiving floats, its two bytes
        if data_format == "Float":
            length = 2

        # for strings its either 8, 16 or 32 byte, depending on the register
        elif data_format == "String":
            if address in [8, 14, 38, 46, 420, 428, 436, 446, 454, 517]:
                length = 8
            elif address in [535, 559]:
                length = 16
            else:
                length = 32

        # read the raw data from the given Modbus address
        raw = self.modbus.read_holding_registers(address, length)
        if raw is None:
            return False

        # decode the raw_data
        if data_format == "U16":
            return int(raw[0])

        elif data_format == "Float":
            if self.byteorder == ENDIAN_BIG:
                return float(utils.decode_ieee((raw[0] << 16) + raw[1]))
            else:
                return float(utils.decode_ieee((raw[1] << 16) + raw[0]))

        elif data_format == "String":
            data_string = ""
            for value in raw:
                hex_value = str(hex(value)[2:])
                left = int(str(hex_value)[:2], 16)
                right = int(str(hex_value)[-2:], 16)
                data_string += chr(left) + chr(right)

            return str(data_string)

        # if all failed, return false
        return False
Ejemplo n.º 4
0
 def read_all_tags(self):
     try:
         c = ModbusClient(host="192.168.2.11", port=502, debug=False)
         c.open()
         
         for name, tag in self.tag_db.items():
             mb0 = tag['modbus_start'] -1
             mb1 = tag['modbus_stop'] -1
             size = 1+mb1-mb0
             #print(name, mb0, mb1, size)
             #print(tag)
             if 0 <= mb0 < 100000:
                 val = c.read_coils(mb0)[0]
             elif 100000 <= mb0 < 200000:
                 val = c.read_discrete_inputs(mb0-100000)[0]
             elif 300000 <= mb0 < 400000:
                 val = c.read_input_registers(mb0-300000,  size)
                 if size == 1: val = val[0]
                 elif size == 2:
                     val = utils.word_list_to_long(val, big_endian=False)[0]
             elif 400000 <= mb0 < 500000:
                 val = c.read_holding_registers(mb0-400000,  size )
                 if size == 1: val = val[0]
                 elif size == 2:
                     val = utils.word_list_to_long(val, big_endian=False)[0]
             
             if tag['dtype'] == 'float32':
                 val = utils.decode_ieee(val)
             
             #print(name, val)
             self.settings[name] = val
                 
     except Exception as err:
         print("Error in read_all_tags", err)
         c.close()        
Ejemplo n.º 5
0
 def read_float(self, address, number=1):
     reg_1 = self.read_holding_registers(address, number * 2)
     if reg_1:
         print(reg_1)
         return [utils.decode_ieee(f) for f in utils.word_list_to_long(reg_1)]
     else:
         return None
Ejemplo n.º 6
0
 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
Ejemplo n.º 7
0
 def get_floats(cls, address, number=1):
     reg_l = cls.get_words(address, number * 2)
     if reg_l:
         return [
             utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l)
         ]
     else:
         return None
Ejemplo n.º 8
0
def make_summary():
    SERVER_HOST = "192.168.43.239"
    SERVER_PORT = 502
    SERVER_UNIT_ID = 2

    c = ModbusClient()
    c.host(SERVER_HOST)
    c.port(SERVER_PORT)
    c.unit_id(SERVER_UNIT_ID)
    if not c.is_open():
            if not c.open():
                print("cannot connect ....")

    if c.is_open():
    # read 54 registers at address 0, store result in regs list
            regs = c.read_input_registers(0,54)
    # if success change register value to float
            if regs:
                abc = [utils.decode_ieee(f) for f in utils.word_list_to_long(regs)]
                data = {
                "Power KWH" : "%0.3f"%abc[0],
                "Power KVAH" : "%0.3f"%abc[1],
                "Power KVArP" : "%0.3f"%abc[2],
                "Power KVArN" : "%0.3f"%abc[3],
                "Line Voltages V RY" : "%0.3f"%abc[4],
                "Line Voltages V YB" : "%0.3f"%abc[5],
                "Line Voltages V BR" : "%0.3f"%abc[6],
                "Line Current IR" : "%0.3f"%abc[7],
                "Line Current IY" : "%0.3f"%abc[8],
                "Line Current IB" : "%0.3f"%abc[9],
                "Active Power Consumed" : "%0.3f"%abc[10],
                "Reactive Power Consumed" : "%0.3f"%abc[11],
                "Apparent Power Consumed" : "%0.3f"%abc[12],
                "Phase Voltages VRN" : "%0.3f"%abc[13],
                "Phase Voltages VYN" : "%0.3f"%abc[14],
                "Phase Voltages VBN" : "%0.3f"%abc[15],
                "Power Factor" : "%0.3f"%abc[16],
                "Frequency" : "%0.3f"%abc[17],
                "Real Power on R" : "%0.3f"%abc[18],
                "Real Power on Y" : "%0.3f"%abc[19],
                "Real Power on B" : "%0.3f"%abc[20],
                "Reactive Power on R" : "%0.3f"%abc[21],
                "Reactive Power on Y" : "%0.3f"%abc[22],
                "Reactive Power on B" : "%0.3f"%abc[23],
                "Apparent Power on R" : "%0.3f"%abc[24],
                "Apparent Power on Y" : "%0.3f"%abc[25],
                "Apparent Power on B" : "%0.3f"%abc[26] 
                }
                mydate = datetime.datetime.now()
                date=datetime.datetime.strftime(mydate,'%Y/%m/%d--%H:%M:%S')
                abc.insert(27,date)
                myfile = open('data.csv','a')
                with myfile:
                    writer = csv.writer(myfile, delimiter=',', quoting=csv.QUOTE_ALL)
                    writer.writerow(abc)
                return data
Ejemplo n.º 9
0
 def __read_32_bit(self, address, number=1):
     if not self.c.is_open():
         self.c.open()
     reg_l = self.c.read_holding_registers(address, number * 2)
     if reg_l:
         return [
             utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l)
         ][0]
     else:
         return None
Ejemplo n.º 10
0
def decimal_list_to_float_bigEndian(values):
    p1 = decoder.word_list_to_long(values, big_endian=True)
    l1 = list()
    for register in p1:
        tmp = decoder.decode_ieee(register)
        if str(tmp) != 'nan':
            tmp = round(float(tmp), 4)
            l1.append(tmp)
        else:
            l1.append(None)
    return l1
Ejemplo n.º 11
0
def rewrite_modbus_read(list):
    new_list = dict()
    for i in range(1,len(list)):
        if i%2:
            new_list[(i+1)/2] =  hex(list[i]) + hex(list[i-1])[2:]
        # else:
            # new_list[i-1] =  hex(list[i+1]) + hex(list[i])[2:]
        # print(i)
    
            # print(utils.decode_ieee(int(new_list[i+1], 16)))
            new_list[(i+1)/2] = utils.decode_ieee(int(new_list[(i+1)/2], 16))
    return new_list
Ejemplo n.º 12
0
def rewrite_modbus_read(list, var):
    new_list = dict()
    for i in range(1, len(list)):
        if i % 2:
            hex_str = hex(list[i - 1])[2:]
            while (len(hex_str) < 4):
                hex_str = "0" + hex_str
            new_list[(i + 1) / 2] = hex(list[i]) + hex_str
            #print((var+i+1)/2,'hex:',hex(list[i]) ,hex_str,utils.decode_ieee(int(new_list[(i+1)/2], 16)))
            # else:
            # new_list[i-1] =  hex(list[i+1]) + hex(list[i])[2:]
            # print(i)

            #print(utils.decode_ieee(int(new_list[(i+1)/2], 16)))
            new_list[(i + 1) / 2] = utils.decode_ieee(
                int(new_list[(i + 1) / 2], 16))
    #print(new_list.values())
    return new_list
Ejemplo n.º 13
0
    if not c.is_open():
        if not c.open():
            print("unable to connect to " + SERVER_HOST + ":" +
                  str(SERVER_PORT))

    # if open() is ok, read register (modbus function 0x03)
    if c.is_open():

        mydate = datetime.datetime.now()

        print(str(mydate))
        # read 54 registers at address 0, store result in regs list
        regs = c.read_input_registers(0, 54)
        # if success change register value to float
        if regs:
            abc = [utils.decode_ieee(f) for f in utils.word_list_to_long(regs)]
        csvwrite = abc
        l = len(csvwrite)
        #truncate the float value upto 3 decimal places

        #Display real time values on Screen
# 	print(abc)

# Time and Date Formatting
#csvstr = datetime.datetime.strftime(mydate, '%Y/%m/%d -- %H:%M:%S')
#abc[0]=csvstr
#print(abc)
#Send data to a excel file
#myFile = open('csvexample4.csv', 'a')
#with myFile:
#   writer = csv.writer(myFile,delimiter=',',quoting=csv.QUOTE_ALL)
Ejemplo n.º 14
0
				c = ModbusClient(host=n, unit_id=109, auto_open=True, auto_close=True)

				if c.open():
					
				    # 4181 is the FLIR A310 register for the Box 1 Average Temperature
				    # many other options available - see 'Convert EthernetIP to Modbus TCP.pdf' 					    
				    reg = c.read_holding_registers(4181, 2)
				    ts = datetime.datetime.now().timestamp()

				    c.close()

				a= hex(reg[0])
				b= hex(reg[1])
				c = b+a[2:]
				d = int(c,16)

				T_avg_K = utils.decode_ieee(d)
				T_avg_degC = T_avg_K - 273.15

				data_temp.append(ts)
				data_temp.append(round(T_avg_degC,2))

			print(data_temp)

			wr.writerow(data_temp)
			
			# change log interval here
			# FLIR A310 registers only appear to update about three times per second
			time.sleep(1)

Ejemplo n.º 15
0
 def read_float(self, address, number=1):
     reg_l = self.read_holding_registers(address, number * 2)
     if reg_l:
         return [utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l)]
     else:
         return None
Ejemplo n.º 16
0
 def read_float_inp(self, address, number=1):
     reg_l = self.read_input_registers(address, number * 2)
     if reg_l:
         return [utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l)]
Ejemplo n.º 17
0
import paho.mqtt.client as mqtt
import time

c = ModbusClient(host="192.168.1.222", port=502, auto_open=True)

client = mqtt.Client()
client.connect("127.0.0.1")
client.loop_start()

outputs = c.read_holding_registers(
    28680,
    4)  #PLC says address is 428681 so, 400001 must be subtracted from address
print outputs
if outputs:
    outputs = [
        utils.decode_ieee(f) for f in utils.word_list_to_long(outputs, False)
    ]
print outputs

while True:
    analogInputs = c.read_holding_registers(28672, 8)
    #print analogInputs
    if analogInputs:
        analogInputs = [
            utils.decode_ieee(f)
            for f in utils.word_list_to_long(analogInputs, False)
        ]
    i = 0

    scaleAI = [  #scaling of analog inputs from 4 - 20 mA to engineering units
        {