Example #1
0
def oneRXTX(intAddress, strCmd):
	rq = '\x00'+convert(intAddress)+strCmd
	rq = rq + convert(crc16.calcString(rq, crc16.INITIAL_MODBUS))[::-1]
	ser.write(rq)
	rs = ser.read(size=100)
	if convert( crc16.calcString(rs[:-2], crc16.INITIAL_MODBUS) ) == rs[-2:][::-1]:
		crcCheck = "CRC OK"
	else:
		crcCheck = "CRC BAD!!!"
	print "request:\t", hexString(rq), "\nresponse:\t", hexString(rs), '\n',crcCheck
Example #2
0
def oneRXTX(intAddress, strCmd):
    rq = '\x00' + convert(intAddress) + strCmd
    rq = rq + convert(crc16.calcString(rq, crc16.INITIAL_MODBUS))[::-1]
    ser.write(rq)
    rs = ser.read(size=100)
    if convert(crc16.calcString(rs[:-2],
                                crc16.INITIAL_MODBUS)) == rs[-2:][::-1]:
        crcCheck = "CRC OK"
    else:
        crcCheck = "CRC BAD!!!"
    print "request:\t", hexString(rq), "\nresponse:\t", hexString(
        rs), '\n', crcCheck
Example #3
0
def oneRXTX(intAddress, strCmd):
    rq = convert(intAddress)+strCmd
    rq = rq + convert(crc16.calcString(rq, crc16.INITIAL_MODBUS))[::-1]
    ser.write(rq)
    rs = ser.read(size=100)
    tstamp = datetime.now()
    if convert(crc16.calcString(rs[:-2], crc16.INITIAL_MODBUS)) == rs[-2:][::-1]:
        crcCheck = "CRC OK"
        crcCheckOK = True
        logger_level = 10  # debug
    else:
        crcCheck = "CRC BAD!!!"
        crcCheckOK = False
        logger_level = 30 # warning
    logger.log(level=logger_level, msg="request:\t{}\tresponse:\t{}\t{}".format(hexString(rq),hexString(rs), crcCheck))
    return crcCheckOK, rs, tstamp
Example #4
0
 def make_req(self, addr, cmd):
 # make request: add address and CRC to the command binary string
 # addr - counter's address (0 - 0xef, 0xfe)
 # cmd - command binary string
 # return: request binary string
     req=pack("=B", addr)+cmd
     crc=crc16.calcString(req, crc16.INITIAL_MODBUS)
     req+=pack("=H", crc)
     return req
Example #5
0
def oneRXTX(intAddress, strCmd):
    rq = convert(intAddress) + strCmd
    rq = rq + convert(crc16.calcString(rq, crc16.INITIAL_MODBUS))[::-1]
    ser.write(rq)
    rs = ser.read(size=100)
    tstamp = datetime.now()
    if convert(crc16.calcString(rs[:-2],
                                crc16.INITIAL_MODBUS)) == rs[-2:][::-1]:
        crcCheck = "CRC OK"
        crcCheckOK = True
        logger_level = 10  # debug
    else:
        crcCheck = "CRC BAD!!!"
        crcCheckOK = False
        logger_level = 30  # warning
    logger.log(level=logger_level,
               msg="request:\t{}\tresponse:\t{}\t{}".format(
                   hexString(rq), hexString(rs), crcCheck))
    return crcCheckOK, rs, tstamp
 def get_slave_id_request(self, mbtcp=True):
     if self._trace: print "get_slave_id_request"
     if self.__req_slaveid is None:
         # then refresh cache
         req = chr(self._addr) + '\x11'
         if self._mbtcp:
             req = chr(self.get_next_seqno()) + '\x00\x00\x00\x00\x02' + req
         else:
             crc = crc16.calcString(req)
             req += chr(crc & 0xFF) + chr((crc >> 8) & 0xFF)
         self.__req_slaveid = req
     return self.__req_slaveid
Example #7
0
 def run(self):
     sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     sock.bind(MADDR)
     sock.settimeout(self.TIME_OUT)
     state=STATE_IDLE
     slave_id=0
     retry=0
     while True:
         if state==STATE_IDLE:
             try:
                 rid, req, delay, qres = self.q1.get(False)
             except:
                 try:
                     rid, req, delay, qres = self.q0.get(False)
                 except:
                     pass
                 else:
                     state=STATE_SEND_DATA
             else:
                 state=STATE_SEND_DATA
             if state==STATE_SEND_DATA:
                 if req=='--close--': break
                 if delay>0.0: time.sleep(delay)
                 retry=0
         if state==STATE_SEND_DATA:
             slave_id=req[0]
             sock.sendto(req, SADDR)
             retry+=1
             state=STATE_WAIT_DATA
         if state==STATE_WAIT_DATA:
             try:
                 data, addr = sock.recvfrom(512)
             except:
                 if retry < self.MAX_RETRY:
                     state=STATE_SEND_DATA
                 else:
                     qres.put((0, rid, req))
                     state=STATE_IDLE
             else:
                 crc=crc16.calcString(data, crc16.INITIAL_MODBUS)
                 if (crc==0):
                     d=map(ord, data)
                     if len(d)==4 and (d[1] & 0x0f)==0x06:
                         state=STATE_SEND_DATA
                         retry-=1
                     else:
                         qres.put((1, rid, d))
                         state=STATE_IDLE
                 else:
                     qres.put((0, rid, req))
                     state=STATE_IDLE
     sock.close()
Example #8
0
def read_co2():
    try:
        ser_write(s8_co2)
        sleep(.2)
        d = ser_read(7)
        checksum = crc16.calcString(str(d[:5]), 0xffff)
        if checksum != d[5] + d[6] * 256:
            return None
        co2 = d[3] * 256 + d[4]
        return co2
    except Exception as e:
        print e
        pass
Example #9
0
def read_input_register(dev, reg):
    command = chr(dev) + '\x04' + struct.pack('>H',reg) + '\x00\x01'
    crc =  crc16.calcString(command, 0xFFFF)
    command = command + struct.pack('<H',crc) 

    print 'Register: ' +  str(reg)
    print ":".join("{:02x}".format(ord(c)) for c in command)
    
    ser.rts = True
    ser.write(command)
    time.sleep(0.008)
    ser.rts = False

    time.sleep(1)        
    
    return ser.readline()
Example #10
0
    def SendCmd(self, cmd, crcflag=False , _debug=False):
        if not _debug:
            if crcflag == True:
                __crc = crc16.calcString(cmd, crc16.INITIAL_MODBUS)
                __crc_H = chr((__crc & 0xff00) >> 8)
                __crc_L = chr(__crc & 0xff)
                try:
                    _cmd = cmd + __crc_L + __crc_H
                    print 'Send Command:', b2a_hex(_cmd)
                    self.sokt.send(_cmd)

                except socket.error, e:
                    print 'Socket Error: %s' % e
            else:
                try:
                    self.sokt.send(cmd + '\x00\x00')
                except socket.error, e:
                    print 'Socket Error: %s' % e
Example #11
0
def fetch_sensor_value(cmd):
    ser.write(str(bytearray(cmd)))
    ser.flush()
    time.sleep(0.5)
    value = ser.read(7)
    
    crcCheck = ord(value[6])*256 + ord(value[5]) 
    #print (crcCheck)
    
    crcCalculation = crc16.calcString(value[:5], 0xFFFF) 
    #print (crcCalculation)
       
    if crcCheck == crcCalculation:
        #print ('CRC check pass.')
        return (ord(value[3])*256 + ord(value[4])) * 0.1
    else: 
        print ('CRC check failed.')
        return None
Example #12
0
    def get_data_request(self, seq_str=None):
        # if self._trace: print "get_data_request"
        
        if self.__req_data is None:
            req = chr(self._addr) + '\x03\x01\x00\x00'
            if  self.__8035:
                # then short request
                req += chr(6)

            elif self._chn_enabled & self.ENB_CHN_AVGMINMAX:
                # get all - even last 3 floats for avg/min/max
                req += chr(54)

            elif self._chn_enabled & (self.ENB_CHN_PHASES | self.ENB_CHN_SPLIT):
                # get up to last of phase data, no avg/min/max
                # note for split phase we need phase data to 'repair' the Volt_LL and LN values
                req += chr(48)

            else:
                # get up to Current, none of the phase data
                req += chr(18)

            if self._mbtcp:
                # we save missing the two bytes
                req = '\x00\x00\x00\x06' + req
            else:
                crc = crc16.calcString(req)
                req += chr(crc & 0xFF) + chr((crc >> 8) & 0xFF)
            self.__req_data = req
            
        if self._mbtcp:
            if seq_str is None:
                self.__last_seq = chr(self.get_next_seqno()) + '\x00'
            else:
                self.__last_seq = seq_str[:2]
            return self.__last_seq + self.__req_data
            
        else: # is modbus/RTU
            return self.__req_data
Example #13
0
def read_input_register(dev, reg):
    command = chr(dev) + '\x04' + struct.pack('>H',reg) + '\x00\x01'
    crc =  crc16.calcString(command, 0xFFFF)
    command = command + struct.pack('<H',crc) 

    #print 'Register: ' +  str(reg)
    #print ":".join("{:02x}".format(ord(c)) for c in command)
    
    ser.rts = True
    ser.write(command)
    time.sleep(0.008)
    ser.rts = False

    time.sleep(1)        
 
    response = ser.readline()


    #TODO: Implement check of checksum(CRC), and handle any modbus error messages
    #checksum = ord(response[5:7])
    #comp_checksum = struct.pack('<H',crc16.calcString(response[1:5], 0xFFFF))
    #print 'chk: ' + str(comp_checksum) 
    return response 
Example #14
0
    def import_binary(self, buf):
        if self._trace: print "import_binary"

        # confirm the basic form of the packet
        if self._mbtcp:
            # confirm basic Modbus/TCP
            if len(buf) < 8:
                return { 'error':
                    'Error: Bad MB/TCP length, too short, was only %d bytes, need 8 or more' % \
                    len(buf) }
                    
            # check the sequence number
            if self.__last_seq != buf[:2]:
                return { 'error':
                    'Error: Bad MB/TCP seq no' }

            if buf[2:5] != '\x00\x00\x00':
                return { 'error':
                    'Error: Bad MB/TCP header zeros' }

            x = ord(buf[5])
            if x != (len(buf) - 6):
                return { 'error':
                    'Error: Bad MB/TCP header - len=%d does not match buffer len()=%d' % \
                        (x, (len(buf) - 6))}

            buf = buf[6:] # normalize to PDU only, remove header

        else:
            # confirm basic Modbus/RTU
            if len(buf) < 5:
                return { 'error':
                    'Error: Bad MB/RTU length, too short, was only %d bytes' % \
                    len(buf) }

            crcCalc = crc16.calcString(buf[:-2])
            crcRecv = ord(buf[-2]) + (ord(buf[-1]) * 256)

            if crcCalc != crcRecv:
                return { 'error':
                    'Error: Bad MB/RTU CRC16' }

            buf = buf[:-2] # normalize to PDU only, remove CRC16

        # we now have the response, which will be:
        # - an error/exception
        # - slave_id response
        # - reg response of 3 floats
        # - reg response of 26 floats

        x = ord(buf[0])
        if x != self._addr:
            return { 'error': 'Error: Bad Modbus Unit Id/Slave Address' }

        fnc = ord(buf[1])
        if fnc & 0x80:
            x = ord(buf[2])
            return { 'error': 'Error: Exception Response, code:%d' % x}

        # all of our good responses have byte-count in 3rd byte
        x = ord(buf[2])
        if x != (len(buf) - 3):
            return { 'error': 'Error: byte count of %d incorrect' % x}

        if fnc == 0x11:
            # then slave id response
            return self.import_slave_id(buf)

        elif fnc == 0x03:
            # then reg response
            self._last_timestamp = digitime.time()
            if self.__8035:
                return self.import_8035(buf)
            else:
                return self.import_8036(buf)

        else:
            return { 'error': 'Error: unexpected function code %d in response' % fnc }
Example #15
0
def stCRC(msg):
    crc = calcString(msg, 0xFFFF)
    crc = swapLoHi(crc)
    return dec2hex(crc)