Example #1
0
def write_MEASURE_CYCLE( ser, address,time):
    #check if the serial port is open
    if ser.is_open==False:
        print("write_MEASURE_CYCLE: serial port not open.")
        return 0
    #reset the output buffer before send new data    
    ser.reset_output_buffer   
    out=[address, MODBUS_WRITE_SINGLE_REGISTER, 0x0, MODBUS_STATE_REGISTER_MEASURE_CYCLE, 0, time]
    #calculate and add the CRC
    out=out + list(struct.pack("<H", libscrc.modbus(bytes(out))))     
    #send data and read the answer. If any error send the message again before give up.        
    j=0;
    while j<MAX_ITERATION:
        write_message(ser,out,address)
        #read the return message
        read_data=read_message(address, MODBUS_WRITE_SINGLE_REGISTER,ser)
        if not(read_data[0]==0 and len(read_data)==1):
            #force loop exit
            j=MAX_ITERATION+1
        else:
            j=j+1
        
    if read_data[0]==0:
        print("write_MEASURE_CYCLE: error in reading data")
        return read_data
    #if no error return ok
    if (error_in_message_check(read_data)[0]!=0):
        return bytes ([1])
    return bytes ([0])
Example #2
0
def mainRun():
    server=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    #server.bind(("192.168.22.167", 9534))

    # POWER={"on": 0x55,"off": 0xAA}
    # MODE={"cold": 0x11,"hot": 0x22,"auto" 0x33,"fan": 0x44,"dry": 0x55}
    # FAN={"fan1": 0x01,"fan2": 0x02,"fan3": 0x03,"autofan": 0x00}
    # TEMP={16: 0x00A0, 17: 0x00AA, 18: 0x00B4, 19: 0x00BE, 20: 0x00C8, 21: 0x00D2, 22: 0x00DC, 23: 0x00E6, 24: 0x00F0, 25: 0x00FA, 26: 0x0104, 27: 0x010E, 28: 0x0118, 29: 0x0122, 30: 0x012C, 31: 0x0136, 32: 0x0140}
    POWER_CODE="on"
    MODE_CODE ="cold"
    FAN_CODE  ="fan3"
    TEMP_CODE =16
    POWER = {"on": "55", "off": "AA"}
    MODE = {"cold": "11", "hot": "22", "auto" "33", "fan": "44", "dry": "55"}
    FAN = {"fan1": "01", "fan2": "02", "fan3": "03", "autofan": "00"}
    TEMP = {16: "00A0", 17: "00AA", 18: "00B4", 19: "00BE", 20: "00C8", 21: "00D2", 22: "00DC", 23: "00E6", 24: "00F0",
            25: "00FA", 26: "0104", 27: "010E", 28: "0118", 29: "0122", 30: "012C", 31: "0136", 32: "0140"}


    command="01109C4000081000"+POWER[POWER_CODE]+"000000"+MODE[MODE_CODE]+"00"+FAN[FAN_CODE]+"00000000"+TEMP[TEMP_CODE]+"0B01"
    print(command)
    crc16 = libscrc.modbus(bytes.fromhex('01109C4000081000550000001100010000000000A00B01'))

    addr = ("192.168.1.105", 20740)
    a = bytes.fromhex('01109C4000081000550000001100010000000000A00B0158d6')
    #     # while data!='q':

    server.sendto(a,addr)
Example #3
0
def read_SERIAL_NUMBER( ser, address):
    #check if the serial port is open
    if ser.is_open==False:
        print("read_SERIAL_NUMBER: serial port not open.")
        return bytes ([0])
    #reset the output buffer before send new data
    ser.reset_output_buffer
    #build the modbus message to send
    out=[address, MODBUS_READ_SINGLE_REGISTER, 0x0, MODBUS_STATE_REGISTER_SERIAL_NUMBER, 0x0, 0x0]
    #calculate and add the CRC
    out=out + list(struct.pack("<H", libscrc.modbus(bytes(out))))    
    #send data and read the answer. If any error send the message again before give up.        
    j=0;
    while j<MAX_ITERATION:
        write_message(ser,out,address)
        #read the return message
        read_data=read_message(address, MODBUS_READ_SINGLE_REGISTER,ser)
        #if read data byte 1 is zero that means error
        if not(read_data[0]==0 and len(read_data)==1):
            #information is contained in the following bytes of the valid answer
            data_in_result=read_data[4:8]
            return data_in_result
        else:
            j=j+1
    print("read_SERIAL_NUMBER: error in reading data")
    return read_data
def GetCRC16Modbus(inputHex):
	myBytes = bytes.fromhex(inputHex)
	crc16 = libscrc.modbus(myBytes)
	crc16Hex = HexToGroup(IntToHex(crc16))
	crc16Hex.reverse()
	outputHex = ' '.join(crc16Hex)
	return outputHex
Example #5
0
def crcCheck(serialMessage):
    """Check if the serial message have a valid CRC.

  Parameters
  -----------
  serialMessage:
    bytearray which contents the serial message send by the FT300.
    [0x20,0x4e,LSBdata1,MSBdata2,...,LSBdata6,MSBdata6,crc1,crc2]
    Check FT300 manual for details.

  Return
  ------
  checkResult:
    bool, return True if the message have a valid CRC and False if not.
  """
    checkResult = False

    #CRC from serial message
    crc = int.from_bytes(serialMessage[14:16],
                         byteorder='little',
                         signed=False)
    #calculated CRC
    crcCalc = libscrc.modbus(serialMessage[0:14])

    if crc == crcCalc:
        checkResult = True

    return checkResult
Example #6
0
def read_READY(ser, address):
    #check if the serial port is open
    if ser.is_open==False:
        print("read_READY: serial port not open.")
        return bytes ([0])
    #reset the output buffer before send new data    
    ser.reset_output_buffer
    #build the modbus message to send
    out=[address, MODBUS_READ_SINGLE_REGISTER, 0x0, MODBUS_STATE_REGISTER_READY, 0, 0]
    #calculate and add the CRC
    out=out + list(struct.pack("<H", libscrc.modbus(bytes(out))))       
    #send data and read the answer. If any error send the message again before give up.        
    j=0;
    while j<MAX_ITERATION:        
        write_message(ser,out,address)
        #read the return message
        read_data=read_message(address, MODBUS_READ_SINGLE_REGISTER,ser)
        if not(read_data[0]==0 and len(read_data)==1):
            #force loop exit
            j=MAX_ITERATION+1
        else:
            j=j+1         
    if (read_data[0]==0):
        print("read_READY: error in reading data")
        return read_data
    #the string is valid, check the result. if the data bytes are 0x1 0x0 ready is ok
    if (read_data[4]==1 and read_data[5]==0):
        return bytes ([1])
    return bytes ([0])
Example #7
0
 def mbytes(self, cmd, pars, reserved_bytes=0):
     bss = cmd.encode('ascii') + b''.join(
         [int(p[1]).to_bytes(p[0], 'little', signed=True) for p in pars])
     if reserved_bytes:
         bss += reserved_bytes * b'\xcc'
     bss += modbus(bss[4:]).to_bytes(2, 'little')
     return bss
    def crc16(byte):

        byte = bytes(byte)

        crc16 = libscrc.modbus(
            byte
        )  #b'\x07\x05\x00\x00\xFF\x00')  # Estrutura para calculo do CRC

        bin2str = (hex(crc16))
        bin2str = str(bin2str)

        p = "0x"

        a1 = bin2str[-2]
        a2 = bin2str[-1]
        if a1 == "x":
            a1 = "0"
        a = p + a1 + a2

        b1 = bin2str[-4]
        b2 = bin2str[-3]
        if b1 == "x":
            b1 = "0"
        b = p + b1 + b2

        return (a, b)
Example #9
0
def mainRun():
    server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    #server.bind(("192.168.22.167", 9534))
    addr = ("192.168.43.78", 20740)

    POWER_CODE = "off"
    MODE_CODE = "cold"
    FAN_CODE = "fan3"
    TEMP_CODE = 27
    POWER = {"on": "55", "off": "AA"}
    MODE = {"cold": "11", "hot": "22", "auto": "33", "fan": "44", "dry": "55"}
    FAN = {"fan1": "01", "fan2": "02", "fan3": "03", "autofan": "00"}
    TEMP = {
        16: "00A0",
        17: "00AA",
        18: "00B4",
        19: "00BE",
        20: "00C8",
        21: "00D2",
        22: "00DC",
        23: "00E6",
        24: "00F0",
        25: "00FA",
        26: "0104",
        27: "010E",
        28: "0118",
        29: "0122",
        30: "012C",
        31: "0136",
        32: "0140"
    }

    if POWER_CODE == "off":
        command = "01069C4000AA2631"
        print(command)
    elif POWER_CODE == "on":
        command = "01069C4000556671"
        print(command)
    else:
        command = "01109C4000081000" + POWER["on"] + "000000" + MODE[MODE_CODE] + "00" + FAN[FAN_CODE] + "00000000" + \
                  TEMP[TEMP_CODE] + "0B01"
        print(command)
        crc16 = str(hex(libscrc.modbus(bytes.fromhex(command))))
        crc16 = crc16[4:] + crc16[2:4]
        command = command + crc16

    print(command)
    print(len(command))
    a = bytes.fromhex(
        command
    )  # a = bytes.fromhex('01109C4000081000550000001100010000000000A00B0158d6')
    #     # while data!='q':
    print(a)
    server.sendto(a, addr)
Example #10
0
def gen_packet(packet):
    checksum = libscrc.modbus(
        bytearray(packet))  #[0x01, 0x03, 0xD0, 0x00, 0x00, 0x26,]))
    # print("Checksum:{:02x}".format((checksum % 0xFFFF),2))
    packet.append(int(checksum & 0xFF))
    packet.append(int(checksum >> 8))

    #res = ""
    #for x in packet:
    #    res += "0x{:02x}, ".format(x,2)
    #print("Packet:"+res)
    return packet
Example #11
0
    def emuart_unframe(self, bytes):
        datas = re.findall(b"\xa5\x06([\s\S]*)\xb6\x07", bytes)
        for data in datas:
            re_crc = struct.unpack(">H", bytes[-4:-2])
            data = data[2:-2]
            # print(data)
            # print("crc", re_crc)
            if re_crc[0] != libscrc.modbus(data):
                return 0

            return data
            pass
Example #12
0
    def processRequest(self, req_msg, logged_user):
        msgs = req_msg.split(';')

        print("processRequest: ", msgs)

        if msgs[0] == ">000L":
            # print("------------ check_login ----------")
            user_id, err_msg = self.db_custom_user.check_login(
                msgs[1], msgs[2])
            if user_id:
                print('user_id = ', user_id)
                reply = "000L;OK;0"
                crc16 = format(libscrc.modbus(reply.encode()), '04x')
                return user_id, "<" + reply + ";" + crc16 + '\n', err_msg
            else:
                # print('------ bad login or password --------')
                reply = "000L;Err;2"
                crc16 = format(libscrc.modbus(reply.encode()), '04x')
                return None, "<" + reply + ";" + crc16 + '\n', err_msg

        elif msgs[0] == ">00SD":
            # print("----------->>> transport_data ----> logged_user = "******"00SD;OK;0"
                    crc16 = format(libscrc.modbus(reply.encode()), '04x')
                    return logged_user, "<" + reply + '\n', err_msg
                else:
                    # print('---- data nit saved - error ----')
                    reply = "00SD;Err;1"
                    crc16 = format(libscrc.modbus(reply.encode()), '04x')
                    return logged_user, "<" + reply + '\n', err_msg
            else:
                # print('--- user not logged ----')
                reply = "00SD;Err;3"
                crc16 = format(libscrc.modbus(reply.encode()), '04x')
                global_vars.main_logger.error("Error: not logged.")
                return logged_user, "<" + reply + '\n', None
        else:
            reply = "00SD;Err;4"
            crc16 = format(libscrc.modbus(reply.encode()), '04x')
            return logged_user, "<" + reply + '\n', None
Example #13
0
def onRelay(slaveID,chanel,delay):
    list_of_values = [slaveID, 0x06, 0x00, chanel, 0x06, delay]
    bytes_of_values = bytes(list_of_values)
    crc16 = libscrc.modbus(bytes_of_values)
    crc_lo = crc16 & 0x00ff
    crc_hi = (crc16 & 0xff00) >> 8

    ser = serial.Serial()
    ser.port = config.comport
    ser.baudrate = 9600
    ser.bytesize = serial.EIGHTBITS
    ser.parity = serial.PARITY_NONE
    ser.stopbits = serial.STOPBITS_ONE
    ser.open()
    ser.write(serial.to_bytes([slaveID, 0x06, 0x00, chanel, 0x06, delay, crc_lo, crc_hi]))
    ser.close()
Example #14
0
def calc_crc16(inputcommand):
    """
    Calculates the CRC16 error check for the command provided as an argument

    :param inputcommand: Motor controller command string without any error checking bytes
    :type inputcommand: string

    :returns: The CRC16 bytes to append to the end of the command string
    :rtype: str
    """
    # Uses the libscrc.modbus function to calculate the CRC16 string for input command
    crc16_modbus = hex(int(crc.modbus(codecs.decode(inputcommand,
                                                    'hex'))))[2:].zfill(4)
    # Strips the hex string of the 0x and reverses the pair order
    converted_crc16_modbus = ''.join([crc16_modbus[2:4], crc16_modbus[0:2]])

    return converted_crc16_modbus
Example #15
0
def CalculateCRC(Packet):
    ModbusData = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
    #Read Received Modbus Packet
    ModbusData[0] = Packet[2]
    ModbusData[1] = Packet[3]
    ModbusData[2] = Packet[4]
    ModbusData[3] = Packet[5]
    ModbusData[4] = Packet[6]
    ModbusData[5] = Packet[7]
    #Read Received Modbus Packet
    crc16 = libscrc.modbus(ModbusData)
    CRC1 = (crc16 >> 8) & 0x00FF
    CRC2 = (crc16) & 0x00FF
    if Packet[8] == CRC1 and Packet[9] == CRC2:
        return True
    else:
        return False
def writeAndVerify(serialPort, cmd, sleeptime, debugMode=True):
    # Write command
    serialPort.write(cmd)
    # Wait
    time.sleep(sleeptime)
    # Read back same # bytes
    readback = serialPort.read(len(cmd))
    if debugMode:
        print("\twrote %s / read %s" %
              (binascii.hexlify(cmd), binascii.hexlify(readback)))
    # Confirm checksum ok
    data = readback[:-2]
    crc1 = readback[-2:]
    crc2 = struct.pack('H', libscrc.modbus(data))
    #if debugMode: print("\t\tCRC = %s / %s" % (binascii.hexlify(crc1),binascii.hexlify(crc2)))

    return crc1 == crc2
Example #17
0
def read_command(motor_serial_port, slave_id, function_code, register_address,
                 no_of_registers):
    """
    Read multiple registers
    e.g. read temperature of driver and motor = read_command(1, 3, 248, 4)
    """
    id = hex(slave_id)[2:].zfill(2)
    fun_code = hex(function_code)[2:].zfill(2)
    reg_address = hex(register_address)[2:].zfill(4)
    n_regs = hex(no_of_registers)[2:].zfill(4)

    initial_command = "".join([id, fun_code, reg_address, n_regs])
    # update crc16
    crc16_modbus = hex(int(crc.modbus(codecs.decode(initial_command,
                                                    'hex'))))[2:].zfill(4)
    crc16_check = ''.join([crc16_modbus[2:4], crc16_modbus[0:2]])

    command = "".join([id, fun_code, reg_address, n_regs, crc16_check])

    # Send the command to the controller
    motor_serial_port.flushInput()
    motor_serial_port.flushOutput()
    motor_serial_port.write(codecs.decode(command, 'hex'))
    # Read the response
    time.sleep(0.2)
    a = motor_serial_port.in_waiting

    # read response of location
    response = motor_serial_port.read(size=a)

    # convert the response into step num
    #motor_pos = codecs.encode(motor_pos, 'hex')
    #motor_pos = motor_pos[6:14]
    #if motor_pos[0:4] == b'ffff':
    #    motor_pos = -1 * (65535 - int(motor_pos[4:], 16))
    #else:
    #    try:
    #        motor_pos = int(motor_pos, 16)
    #    except ValueError:
    #        log.info("No response from motor")
    #        motor_pos = None
    return response
def GetDataFromInverter(txt, len_return):
    #    StartTime=datetime.datetime.now()
    #    local_msg=bytearray()
    count = 0
    while 1:
        Tx_Enable.on()
        #        time.sleep(0.06)
        ser.write(txt)
        ser.flush()
        Tx_Enable.off()
        #        time.sleep(0.01)

        local_msg = (
            b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        )
        local_msg = ser.read(80)
        #        print('Checksum: ',libscrc.modbus(local_msg,0xFFFF),' - ',end='')
        #        print(local_msg)
        #        print(len(local_msg))
        """
        Here we should check for valid checksum
        Modbus function expect an array of bytes and not a bytearry
        My function needs to be adjusted to use array of bytes before the check can be implemented
        """

        if libscrc.modbus(local_msg, 0xFFFF) == 0:  # Validate checksum
            return local_msg
        count = count + 1
        if count > 5:
            return (b'\x00')
        ser.close()
        time.sleep(0.1)
        ser.open()
        ser.reset_input_buffer()
        ser.reset_output_buffer()
        time.sleep(0.08)


#    EndTime=datetime.datetime.now()
#    TimeUsed=EndTime-StartTime
#    print("Time Used ", TimeUsed.microseconds/1000, " ms")
    return (b'\x00')
Example #19
0
    def create_poll_request(self, cmd):
        logging.debug("{} {}".format("create_poll_request", cmd))
        data = None
        function = self.function_READ
        device_id = self.PowerDevice.device_id
        self.poll_register = cmd
        if cmd == 'SolarPanelAndBatteryState':
            regAddr = self.SolarPanelAndBatteryState.REG_ADDR
            readWrd = self.SolarPanelAndBatteryState.READ_WORD
        elif cmd == 'BatteryParamInfo':
            regAddr = self.BatteryParamInfo.REG_ADDR
            readWrd = self.BatteryParamInfo.READ_WORD
        elif cmd == 'SolarPanelInfo':
            regAddr = self.SolarPanelInfo.REG_ADDR
            readWrd = self.SolarPanelInfo.READ_WORD
        elif cmd == 'ParamSettingData':
            regAddr = self.ParamSettingData.REG_ADDR
            readWrd = self.ParamSettingData.READ_WORD
        elif cmd == 'RegulatorPowerOn':
            regAddr = self.RegulatorPower.REG_ADDR
            readWrd = self.RegulatorPower.on
            function = self.function_WRITE
        elif cmd == 'RegulatorPowerOff':
            regAddr = self.RegulatorPower.REG_ADDR
            readWrd = self.RegulatorPower.off
            function = self.function_WRITE

        if regAddr:
            data = []
            data.append(self.PowerDevice.device_id)
            data.append(function)
            data.append(self.Int2Bytes(regAddr, 0))
            data.append(self.Int2Bytes(regAddr, 1))
            data.append(self.Int2Bytes(readWrd, 0))
            data.append(self.Int2Bytes(readWrd, 1))

            crc = libscrc.modbus(bytearray(data))
            data.append(self.Int2Bytes(crc, 1))
            data.append(self.Int2Bytes(crc, 0))
            logging.debug("{} {} => {}".format("create_poll_request", cmd,
                                               data))
        return data
Example #20
0
def read_REBOOT(ser, address):
    #check if the serial port is open
    if ser.is_open==False:
        return 0
    #reset the output buffer before send new data    
    ser.reset_output_buffer   
    out=[address, MODBUS_READ_SINGLE_REGISTER, 0x0, MODBUS_STATE_REGISTER_REBOOT, 0, 0]
    #calculate and add the CRC
    out=out + list(struct.pack("<H", libscrc.modbus(bytes(out))))          
    write_message(system,ser,out,address)
    time.sleep(5)       
    #close the serial port to be sure it can be used again after sending the reboot command
    ser.close()
    #add a delay to be sure the port has been closed
    time.sleep(2)
    #re-open serial port
    ser.open()
    #add a delay to be sure the port has been opened
    time.sleep(2)          
    return
Example #21
0
def mainRun():
    POWER_CODE = "on"
    MODE_CODE = "cold"
    FAN_CODE = "fan3"
    TEMP_CODE = 20
    POWER = {"on": "55", "off": "AA"}
    MODE = {"cold": "11", "hot": "22", "auto": "33", "fan": "44", "dry": "55"}
    FAN = {"fan1": "01", "fan2": "02", "fan3": "03", "autofan": "00"}
    TEMP = {
        16: "00A0",
        17: "00AA",
        18: "00B4",
        19: "00BE",
        20: "00C8",
        21: "00D2",
        22: "00DC",
        23: "00E6",
        24: "00F0",
        25: "00FA",
        26: "0104",
        27: "010E",
        28: "0118",
        29: "0122",
        30: "012C",
        31: "0136",
        32: "0140"
    }
    commandTX = "01109C4000081000" + POWER[POWER_CODE] + "000000" + MODE[
        MODE_CODE] + "00" + FAN[FAN_CODE] + "00000000" + TEMP[
            TEMP_CODE] + "0B01"
    print(commandTX)
    crc16 = str(
        hex(
            libscrc.modbus(
                bytes.fromhex(
                    '01109C4000081000550000001100010000000000A00B01'))))
    crc16 = crc16[4:] + crc16[2:4]
    commandTX = commandTX + crc16
    print(commandTX)
    k = bytes.fromhex(commandTX)
    print(k.decode('utf-8'))
Example #22
0
def basic_check(data_in, address, modbus_function):
    data_len=len(data_in)
    #basic check on data lenght: if the read_data is zero lenght it is an error. Return 0
    if data_len==0:
        #return 0 as error flag
        return bytes([0])   
    #consider the last two bytes as the incoming CRC information (calculated by the uC)
    crc_in=bytes([data_in[data_len-2],data_in[data_len-1]])
    #format into an unsigned integer number
    [crc_in]=struct.unpack('>H', crc_in)
    #calculate the CRC of the received data
    crc_calc=libscrc.modbus(data_in[0:data_len-2])
    #if the CRC is not correct generate an error
    if (crc_in!=crc_calc):
        #return 0 as error flag
        return bytes([0])
    #now check that the multisensor address and function echoed by the mulstisensor match the reqeusted one
    if data_in[0]!=address or data_in[1]!=modbus_function:
        return bytes([0])
    #the basic check was ok. Return data
    return data_in
Example #23
0
    def Validate(self, bs):
        header = 3
        checksum = 2
        if bs == None or len(bs) < header + checksum:
            logging.warning("Invalid BS {}".format(bs))
            return False

        function = bs[1]
        if function == 6:
            # Response to write-function.  Ignore
            return True
        length = bs[2]
        if len(bs) - (header + checksum) != int(length):
            logging.warning("Invalid BS (wrong length) {}".format(bs))
            return False

        crc = libscrc.modbus(bytearray(bs[:-2]))
        check = self.Bytes2Int(bs, offset=len(bs) - 1, length=-2)
        if crc == check:
            return True
        logging.warning("CRC Failed: {} - Check: {}".format(crc, check))
        return False
Example #24
0
def read_MEASUREMENTS_NAME(ser, address,measure_number):
    #check if the serial port is open
    if ser.is_open==False:
        print("read_MEASUREMENTS_NAME: serial port not open.")
        return bytes ([0])
    #reset the output buffer before send new data    
    ser.reset_output_buffer   
    out=[address, MODBUS_READ_SINGLE_REGISTER, 0x0, MODBUS_DATA_MEASURE_NAMES, 0, measure_number]
    #calculate and add the CRC
    out=out + list(struct.pack("<H", libscrc.modbus(bytes(out))))       
    #send data and read the answer. If any error send the message again before give up.        
    j=0;
    while j<MAX_ITERATION: 
        write_message(ser,out,address)
        #read the return message
        read_data=read_message(address, MODBUS_READ_SINGLE_REGISTER,ser)
        if not(read_data[0]==0 and len(read_data)==1):
            return read_data[4:15]
        else:
            j=j+1            
    print("read_MEASUREMENTS_NAME: error in reading data")
    return read_data
Example #25
0
def query(comanda, ser):
    '''
    estructura:
    [SOH=0x01][COMANDA][CR=0x0d][LF=0x0a][CRC16][EOT=0x04]
  '''
    #trama start
    trama = bytearray()
    trama.append(0x01)  #SOH byte
    for ch in comanda:
        trama.append(ord(ch))
    trama.append(0x0d)  #CR byte
    trama.append(0x0a)  #LF byte
    crc = hex(libscrc.modbus(comanda.encode()))[2:]  #remove '0x' string
    for ch in crc:
        trama.append(ord(ch.upper()))
    trama.append(0x04)  #EOT byte
    trama.append(0x0a)  #LF
    #trama end
    print('query =>', trama)
    #write
    ser.flush()
    ser.write(trama)
    print('resposta =>', ser.readlines())
Example #26
0
def read_NUMBER_OF_MEASUREMENTS(ser, address):
    #check if the serial port is open
    if ser.is_open==False:
        print("read_NUMBER_OF_MEASUREMENTS: serial port not open.")
        return bytes ([0])
    #reset the output buffer before send new data    
    ser.reset_output_buffer
    out=[address, MODBUS_READ_SINGLE_REGISTER, 0x0, MODBUS_DATA_NUMBER_OF_MEASURE, 0, 0]
    #calculate and add the CRC
    out=out + list(struct.pack("<H", libscrc.modbus(bytes(out))))       
    #send data and read the answer. If any error send the message again before give up.        
    j=0;
    while j<MAX_ITERATION:   
        write_message(ser,out,address)
        #read the return message
        read_data=read_message(address, MODBUS_READ_SINGLE_REGISTER,ser)
        if not(read_data[0]==0 and len(read_data)==1):
            #the string is valid, check the result. if the data bytes are 0x1 0x0 ready is ok
            return bytes([read_data[4], read_data[5]])
        else:
            j=j+1          
    print("read_NUMBER_OF_MEASUREMENTS: error in reading data")
    return read_data
Example #27
0
 def emuart_frame(self, bytes):
     crc_res = libscrc.modbus(bytes)
     frame = hexStringB2Hex(self.frame_head) + struct.pack('>H', len(bytes)) + bytes + \
             struct.pack('>H', crc_res) + hexStringB2Hex(self.frame_tail)
     return frame
Example #28
0
    def processBinary(self, bstring):
        # Process the device reply
        self._bs = bstring
        if self._debug:
            print("hw bb > %s" % self._bs)
        if len(self.commands):
            if self._debug:
                print("last command which expects reply was:",
                      self.commands[0]['cmd'])
                print("received reply:", self._bs)
            if (b'errc' or b'errd' or b'errv') in self._bs:
                print('command', self.commands[0]['cmd'], 'produced error',
                      self._bs)
                self._buffer = b''  # empty buffer after error

            r_str = None
            while True:
                # check buffer empty and checksum
                if self._buffer != b'':
                    print(
                        'warning buffer not empty after expected number of bytes'
                    )
                    self._buffer = b''  # empty buffer
                if len(self._bs) > 4 and self.commands[0][
                        'status'] == 'sent' and modbus(self._bs[4:]) != 0:
                    r_str = 'checksum failed'
                    self._buffer = b''
                    break
                if self.commands[0]['status'] == 'sync':
                    # sync after failed comand
                    r_str = 'sync'
                    if len(self.commands
                           ) > 1 and self.commands[1]['status'] == 'sent':
                        # remove failed command
                        self.commands.pop(0)
                    break
                r_str = b''
                if self.iscom('gsti'):
                    r_str = self.strb(16) + ' '
                    r_str += self.strb(24)
                    break
                if self.iscom('gmov'):
                    self.object['speed'] = self.sintb(4)
                    self.object['uspeed'] = self.sintb(1)
                    self.object['accel'] = self.sintb(2)
                    self.object['decel'] = self.sintb(2)
                    self.object['anti_play_speed'] = self.sintb(4)
                    self.object['uanti_play_speed'] = self.sintb(1)
                    if self.commands[0]['status'] != 'sent_status':
                        r_str = 'speed:' + self.object['speed'] + ' '
                        r_str += 'uspeed:' + self.object['uspeed'] + ' '
                        r_str += 'accel:' + self.object['accel'] + ' '
                        r_str += 'decel:' + self.object['decel'] + ' '
                        r_str += 'anti_play_speed:' + self.object[
                            'anti_play_speed'] + ' '
                        r_str += 'uanti_play_speed:' + self.object[
                            'uanti_play_speed']
                    break
                if self.iscom('gpos'):
                    self.object['position'] = self.sintb(4)
                    self.object['uposition'] = int(self.sintb(2))
                    self.object['encposition'] = int(self.sintb(8))
                    if self.commands[0]['status'] != 'sent_status':
                        r_str = 'pos:' + self.object['position'] + ' '
                        r_str += 'upos:' + self.object['uposition'] + ' '
                        r_str += 'encpos:' + self.object['encposition']
                    break
                # not recognized command, just pass the output
                r_str = self._bs
                break
            if type(r_str) == str:
                daemon.messageAll(r_str, self.commands[0]['source'])
            elif r_str != b'':
                daemon.messageAll(r_str, self.commands[0]['source'])
        self.commands.pop(0)
        cc = s.readline()
        if len(cc) > 0:
            print("<-", cc.hex())
            if cc.hex().startswith("ff70"):
                # received id from battery
                bat_id = cc[12:15]
                bat_id_hex = bat_id.hex()
                if bat_id_hex in bat_dupes:  # skip duplicates
                    print("skipping duplicate id ", bat_id_hex)
                    continue
                bat_dupes.append(bat_id_hex)

                req = req_bat_active + bat_id + bytes([current_bat_id])
                bat_ids.append(current_bat_id)
                current_bat_id += 1
                req = req + libscrc.modbus(req).to_bytes(2, 'little')
                s.write(req)
                print("-> ", req.hex(),
                      s.readline().hex(), "# received battery id", bat_id_hex,
                      "assigning bus id", current_bat_id - 1)
                print(s.readline().hex(), "# response of set active bat id")

            if len(cc) >= 58 and cc.hex().startswith("0203"):
                evaluate_battery_status()

for reqid in bat_ids:
    req = bytes([reqid]) + req_data
    req = req + libscrc.modbus(req).to_bytes(2, 'little')
    print("->", req.hex(), "# request data from bus id", reqid)
    s.write(req)
    cc = s.readline()
Example #30
0
def calculate_checksum(*args):
    # Filter None and empty lists
    new_args = list(filter(lambda x: x and type(x) is not list, args))
    string = b"".join(new_args)
    return modbus(string)  # 16-bit CRC