因python2.5与python3编码解码区别, 需要更新

# -*- coding: utf-8 -*-"""
"""
import struct
import socket
import re
import binascii
import logging
import ctypesclass FinsTcp(object):def __init__(self, ip, plc_ip, plc_port):super(FinsTcp, self).__init__()self.ip = ipself.plc_ip = plc_ipself.plc_port = plc_portself.s = Noneself.FINS = '46494E53'self.command_err_code = ['0000000000000000', '0000000100000000', '0000000200000000']self.ICF_RSV_GCT = ['800002', 'C00002']self.SID = 'FF'self.send = ''self.receive = ''logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')self.logger = logging.getLogger(__name__)self.logger.disabled = Falsedef try_connect(self, keep=False):"""FINSTcp 握手:param keep: 保持连接:return:"""try:self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.s.settimeout(3)self.s.connect((self.plc_ip, self.plc_port))except TimeoutError:self.logger.error('connect fail')return Falseother_data_send = ''.join([self.command_err_code[0],self.__node(self.ip).rjust(8, '0')])self.send = ''.join([self.FINS, self.data_length(other_data_send), other_data_send]).upper()send = self.send.decode('hex')self.logger.error("send:".format(self.send))self.s.send(send)receive_data = self.s.recv(1024)self.receive = self.str_to_str_hex(receive_data).upper()self.logger.info('receive: '.format(self.receive))if receive_data:other_data_recv = ''.join([self.command_err_code[1],self.__node(self.ip).rjust(8, '0'),self.__node(self.plc_ip).rjust(8, '0')])expect_data = ''.join([self.FINS, self.data_length(other_data_recv),other_data_recv]).upper()if self.receive != expect_data:self.logger.error('fins connected fail {0} {1}'.format(self.receive, expect_data))self._disconnect()return Falseself.logger.info('a fins client connected...')if not keep:self._disconnect()return Truereturn Truedef _disconnect(self):self.s.close()self.logger.info('disconnected')def __del__(self):self._disconnect()@staticmethoddef __node(ip):"""hexstring ip node:param ip: :return: """return hex(int(ip.split('.')[-1]))[2:].rjust(2, '0')@staticmethoddef int_to_str_hex(data):"""fiction: int 转化为hex字符串:param data::return:"""if data:return hex(data)[2:].rjust(2, '0')return ''@staticmethoddef str_to_str_hex(data):"""fiction: 接收到的Str转化为Hex字符串:param data:  接收到Str:return:"""if data:return data.encode('hex').rjust(2, '0')return ''@staticmethoddef check_fins_data(data):""":param data: 报文反馈检查:return: """self.logger.info("check fins data is ".format(data))if data[:8] != "46494E53":          # Fins header checkself.logger.error("Data Fins Type Error")return Falsedata_length =  int(data[8:16], 16)if len(data)/2 != 8 + data_length:self.logger.error("Data length Error")return Falsefins_err = int(data[24:32], 16)if fins_err != 0:self.logger.error("Data Other Error, Fins_err number is ".format(fins_err))if fins_err == 1:self.logger.error("The header is not FINS")elif fins_err == 2:self.logger.error("The data length is too long")elif fins_err == 3:self.logger.error("The command is not supported")elif fins_err == 32:self.logger.error("All connections are in use")elif fins_err == 33:self.logger.error("The Specified node is already connected")elif fins_err == 34:self.logger.error("Attempt to access a protected node from an unspecified IP address")elif fins_err == 35:self.logger.error("The client FINS node address is out of range")elif fins_err == 36:self.logger.error("The same FINS node address is being used by the client and server")elif fins_err == 37:self.logger.error("All the node addresses available for allocation have being used")else:self.logger.error("Other error")return Falsereturn Truedef to_str_hex(self, data, data_length):s = struct.Struct('>i')if not isinstance(data_length, int):s = struct.Struct(''.join(['>', data_length]))else:if str(data) in ['False', 'True']:s = struct.Struct('>h')self.logger.info('data is bool')if isinstance(data, str):data = eval(data)data = 1 if data is True else 0elif isinstance(data, int):if data_length == 1:s = struct.Struct('>h')elif data_length == 2:s = struct.Struct('>i')elif data_length == 4:s = struct.Struct('>l')elif isinstance(data, float):if data_length == 4:s = struct.Struct('>d')else:s = struct.Struct('>f')elif isinstance(data, str):s = struct.Struct('%rs' % len(data))else:self.logger.error('del this data type fail')return Falseprebuffer = ctypes.create_string_buffer(s.size)if isinstance(data, list):s.pack_into(prebuffer, 0, *data)else:s.pack_into(prebuffer, 0, data)str_hex = binascii.hexlify(prebuffer)str_hex = self.chang_long_for_plc(str_hex=str_hex, data_type=data_length)return str_hex.rjust(4, '0'),  len(str_hex)/4 + 1 if len(str_hex)%4 else len(str_hex)/4def chang_long_for_plc(self, str_hex, data_type):"""针对在plc中显示做处理:param str_hex: :param data_type: :return: """if 'l' in data_type or 'f' in data_type:str_hex_list1 = []str_hex_list2 = []for i in range(0, len(str_hex), 4):if not i % 4:str_hex_list1.append(str_hex[i: i + 4])if len(str_hex_list1) % 2:str_hex_list1.insert(-1, '0000')for j in range(0, len(str_hex_list1), 2):if not j % 2:str_hex_list2.append(str_hex_list1[j + 1])str_hex_list2.append(str_hex_list1[j])str_hex = ''.join(str_hex_list2)elif 's' in data_type:str_hex_list1 = []str_hex_list2 = []for i in range(0, len(str_hex), 2):if not i % 2:str_hex_list1.append(str_hex[i: i + 2])for j in range(0, len(str_hex_list1), 2):if not j % 2:str_hex_list2.append(str_hex_list1[j + 1])str_hex_list2.append(str_hex_list1[j])str_hex = ''.join(str_hex_list2)return str_hex@staticmethoddef data_length(hex_str):return hex(int(len(hex_str)/2))[2:].rjust(8, '0')def fins_nodes(self, da, ca='', connect=False):da = da.center(6, '0')if ca:ca = ca.center(6, '0')if connect:return ''.join([da, ca])return ''.join([da, ca, self.SID])def address_change(self, address, is_bit):""":param address: 'DM100' :type str:param is_bit: type:bool:return:"""temp = re.match('(\D+)(\d+)', address)if temp and len(temp.groups()) == 2:era, num = temp.groups()else:return ''era = era.upper()num = self.int_to_str_hex(int(num))if not num:return ''index = 0 if not is_bit else 1dict_address = {"CI": ['B0', '30'], "W": ['B1', '31'], "D": ['82', '02'],"H": ['B2', '32'], "T": ['89', '09'], "A": ['B3', '33'],"CN": ['89', '09'],"CIO": ['B0', '30'], "WR": ['B1', '31'], "DM": ['82', '02'],"HR": ['B2', '32'], "TIM": ['89', '09'], "AR": ['B3', '33'],"CNT": ['89', '09']}if era in dict_address.keys():return ''.join([dict_address[era][index], num.rjust(4, '0'), '00'])else:self.logger.error('Address error')return ''@staticmethoddef read_or_write(is_read):return '0101' if is_read else '0102'def read_or_write_length(self, length):if isinstance(length, int):return self.int_to_str_hex(length).rjust(4, '0')elif isinstance(length, str):return length.rjust(4, '0')else:return ''def write_data(self, data):if isinstance(data, int):return self.int_to_str_hex(data).rjust(4, '0')elif isinstance(data, str):return data.rjust(4, '0')return ''def fins_send_receive(self, address, is_read, is_bit, length, data):"""发送及接收命令返回:param address: ‘DM100’:param is_read: 0 or 1:param is_bit: 0 or 1:param length: 10进制数(字节数):param data: 写入数据字符串  is_bite 一位01 或00, not is_bit 一字为两字节16位:FFFF:return:"""is_read = int(is_read)is_bit = int(is_bit)length = int(length)data = '' if is_read else dataother_data_send = ''.join([self.command_err_code[-1],self.ICF_RSV_GCT[0],self.fins_nodes(da=self.__node(self.plc_ip),ca=self.__node(self.ip)),self.read_or_write(is_read),self.address_change(address, is_bit),self.int_to_str_hex(length).rjust(4, '0'),data])if len(other_data_send) < 44:return ''self.send = ''.join([self.FINS, self.data_length(other_data_send), other_data_send]).upper()if not self.check_fins_data(self.send):return ''self.s.send(self.send.decode('hex'))self.logger.info("send data:".format(self.send))self.logger.info("receiving")receive_data = self.s.recv(1024)rece_data = self.str_to_str_hex(receive_data).upper()self.receive = rece_dataself.logger.info("receive data: ".format(rece_data))if not self.check_receive_data(receive_data=rece_data, is_read=is_read):return ''if is_read:if is_bit and len(rece_data[60:])/2 != length:self.logger.error('Read Data Error')return ''if not is_bit and len(rece_data[60:])/4 != length:self.logger.error('Read Data Error2')return ''return rece_data[60:]return Truedef check_receive_data(self, receive_data, is_read):rece_data = receive_dataself.logger.error("Check receive data now")if rece_data[:8] != self.FINS:self.logger.error('FINS Tcp Heard Error:\n{0}\n{1}'.format(rece_data[:8], self.FINS))return ''if rece_data[8:16] != self.int_to_str_hex(len(rece_data[16:])/2).rjust(8, '0').upper():self.logger.error("FINS Length Error \n{0}\n{1}".format(self.int_to_str_hex(len(rece_data[16:])/2).rjust(8, '0').upper(), rece_data[8:16]))return ''if rece_data[16:32] != self.command_err_code[-1]:self.logger.error("FINS Command ErrCode Error {0}\n {1} ".format(rece_data[16:24], self.command_err_code[-1]))return ''if rece_data[32:38] != self.ICF_RSV_GCT[-1]:self.logger.error("FINS ICF_RCV_GCT Error {0} \n {1} ".format(rece_data[32:28], self.ICF_RSV_GCT[-1]))return ''if rece_data[38:52] != self.fins_nodes(da=self.__node(self.ip), ca=self.__node(self.plc_ip)).upper():self.logger.error("FINS SA DA Error {0} {1}".format(rece_data[38:52],self.fins_nodes(da=self.__node(self.ip),ca=self.__node(self.plc_ip)).upper()))return ''if rece_data[52:56] != self.read_or_write(is_read):self.logger.error('FINS Read Or Write Error{0} {1}'.format(rece_data[52:56], self.read_or_write(is_read)))return ''if not is_read and rece_data[-4:] != '0000':self.logger.error('Write Receive Is Error {0}  {1}'.format(rece_data[-4:], '0000'))return ''return Truedef write_to_plc(self, address, data, data_type_bytes):""":function : 按字数写入:param datas: [[address. data, data_type_bytes)=4]:return:"""self.logger.info('write informaion :{0} {1} {2}'.format(address, data, data_type_bytes))write_data, length = self.to_str_hex(data, data_type_bytes)if not self.fins_send_receive(address, 0, 0, length, write_data):return Falsereturn Truedef read_from_plc(self, address, struct_type):s = struct.Struct(''.join(['>', struct_type]))length = s.size/2 + 1 if s.size%2 else s.size/2info = self.fins_send_receive(address, 1, 0, length, '')if info:info = self.chang_long_for_plc(str_hex=info, data_type=struct_type)return s.unpack(info.decode('hex'))return infodef check_is_same(self, data1, data2):if type(data1) != type(data2):return Falseif isinstance(data1, list):for num, each1 in enumerate(data1):if isinstance(each1, list):return self.check_is_same(each1, data2[num])if __name__ == '__main__':fins = FinsTcp(ip='192.168.250.2', plc_ip='192.168.250.1', plc_port=9600)fins.try_connect(keep=True)new = Truedata = []while True:read = raw_input('IS READ')if read == '1':address = raw_input('input write address DM100:')length = raw_input('input read word num')data_type = raw_input('input read data_type')info = fins.fins_send_receive(address, 1, 0, length=int(length), data='')if info:print(info, info.decode('hex'))# print(fins.read_from_plc(address, data_type))

FINSTCP python2.5相关推荐

  1. 通过anaconda2安装python2.7和安装pytorch

    ①由于官网下载anaconda2太慢,最好去byrbt下载,然后安装就行 ②安装完anaconda2会自动安装了python2.7(如终端输入python即进入python模式) 但是可能没有设置环境 ...

  2. python2 安装faiss-gpu 报错 faiss/faiss/python/swigfaiss.i:241: Error: Unable to find ‘faiss/impl/platfo

    1. 安装报错 $ sudo pip install faiss-gpu --default-timeout=1000 -i https://pypi.douban.com/simple DEPREC ...

  3. Python2 与 Python3 区别

    Python2.x 与 Python3.x 区别 1. print 函数 Python2 中 print 是语句(statement),Python3 中 print 则变成了函数.在 Python3 ...

  4. python2转python3文件

    python37 -m 2to3.py -w C:\Users\Administrator\Desktop\搜狗细胞词库处理.py 命令 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA ...

  5. 手抖把Python2.7卸载了,导致了自己的yum不可用

    摘要: 从标题就能看到我有多心如死灰了,简单介绍下我是如何自残的过程. ①首先因为需要部署爬虫程序,然后安装Python3. ②Python3系列和Python2系列版本不向下兼容,所以我就卸载了机器 ...

  6. CentOS7安装Python3详细步骤与Python2共用方法

    本人使用的是centos7,该系统已经自带了python2,但是由于python3和python2在很多使用上还存在着较大区别,并且本着学习的态度决定尝试安装一次. 由于一开始忘了截图,所以本文只有所 ...

  7. Djang1.8+Python2.0迁移到Django2.0+Python3.6注意事项(转)

    Djang1.8+Python2.0迁移到Django2.0+Python3.6注意事项 参考:https://blog.csdn.net/weixin_40475396/article/detail ...

  8. Depends, python2.7-minimal (= 2.7.15_rc1-1) 问题解决方法使用 aptitude 安装以及与 apt-get 的区别

    1. 问题现象 使用命令 sudo apt install python2.7 安装 Python2 时报如下错误 wohu@ubuntu1804:/etc/apt$ sudo apt install ...

  9. Python2 与 Python3 共存,pip2 与 pip3 共存切换设置

    1. Python2 与 Python3 软链接设置 wohu@ubuntu:/usr/bin$ ll /usr/bin/python* lrwxrwxrwx 1 root root 9 4月 16 ...

  10. python2.7升3.7_升级python2.7至python3.7

    最近在centos7下执行命令时,出现以下提示: DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020 ...

最新文章

  1. C语言易错题--求最大公约数与最小公倍数之和(辗转相除法)
  2. 向上累积频数怎么算_天天向上:王一博单人cut只有7分钟,给了高天鹤最后的疼爱...
  3. Visual studio中编译和使用libpng和zlib
  4. 003_Maven插件
  5. 于谦一共收了几个徒弟,为什么?
  6. php windows svn,windows下安装svnmanager
  7. 新冠全球蔓延,AI+大数据拿什么拯救全人类? | AI 技术生态论
  8. [导入]MsAjax Lib- Date.parseInvariant 函数
  9. java异常机制throwable
  10. linux硬件开发学习,硬件学习该从何下手
  11. Android 热补丁实践之路
  12. 对特殊字符编码js与c#中的处理方法
  13. 如何有效的进行项目文档管理
  14. 三维重建笔记_基于图像的大规模场景三维建模overview
  15. Excel如何将文本中间的数值提取出来
  16. 树莓派4B 8G安装日志(1)——基础环境安装
  17. linux目录或文件颜色
  18. 1139: 神奇的fans
  19. poj2942 圆桌骑士(点双连通分量+二分图染色法判奇环)
  20. 用ScreenToGif录屏并生成gif动图

热门文章

  1. 计算机表格布局,修改Word2007的表格布局
  2. 计算机acm国际排名,acm(中国大学acm综合排名)
  3. linux 分区怎样缩小,如何缩小磁盘分区大小
  4. 国内搜索引擎技术现状
  5. 【Java】Java学习笔记(5)——Java泛型作业函数题
  6. 关于sip软电话嵌入到网页web端的学习----第一天(2)(高手指点)遇到问题了jssip
  7. UE4 碰撞射线检测
  8. 篮球/NBA 英语词汇大全
  9. JavaScript实现动态显示时间
  10. 论BOM管理的若干重要问题