#Begin Modbus RTU (Serial(Not supported TCP))
#All right reserved Cevahir Holding Company Automation Department 2014
# -*- coding: cp1254 -*-
import time,struct,binascii,array
class _mb_rtu:
def __init__(self):
self.table = []
self.init_table()
self.unit_id = 1
self.convert_flag = "D"
def init_table(self):
if( (len(self.table) == 256) and (self.table[1] == 49345)):
# print "Table already init!"
return
lst = []
i = 0
while( i < 256):
data = (i << 1)
crc = 0
j = 8
while( j > 0):
data >>= 1
if( (data ^ crc) & 0x0001):
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
j -= 1
lst.append( crc)
#print "entry %d = %x" % ( i, table[i])
i += 1
self.table = tuple( lst)
return
def calcString(self, st, crc):
self.init_table()
# print "st = ", list(st)
for ch in st:
crc = (crc >> 8) ^ self.table[(crc ^ ord(ch)) & 0xFF]
# print " crc=%x" % crc
return crc
def swapLoHi(self,n):
lo = n & 0x00FF
hi = (n & 0xFF00) >> 8
return lo << 8 | hi
def stCRC(self,msg):
crc = self.calcString(msg, 0xFFFF)
crc = self.swapLoHi(crc)
return self.dec2hex(crc)
def dec2hex(self,n):
lo = n & 0x00FF
hi = (n & 0xFF00) >> 8
return chr(hi) + chr(lo)
def set_msg(self,station,msg):
_stati= "%02X" %station
def _build(self,station,address,count=1,value=int()):
_stati,_count= "%02X" %station ,"%02X" %count
def to_rtu(self,_word):
a = array.array('B')
_list = []
word=_word
for i in range(len(word)/2) :
_list.append(int((word[(i*2):((i*2)+2)]),16))
a.extend(_list)
_n = a.tostring()
return _n + self.stCRC(_n)