tcp_client.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. # -*- coding:utf-8 -*-
  2. import os, sys, time
  3. import abc
  4. import socket
  5. import json
  6. import numpy as np
  7. import struct
  8. import binascii
  9. #创建ProHeader数据类型
  10. # 定义:
  11. DataHeader = np.dtype({'names': ['protocol', 'len', 'cmd'], 'formats': ['u1', 'u4', 'u1']}, align=False)
  12. UserInfo = np.dtype({'names': ['userName', 'password', 'actuator'], 'formats': ['|S260', '|S260', '|S260']}, align=False)
  13. LoginResp = np.dtype({'names': ['bStatus', 'szMessage'], 'formats': ['?', '|S260']}, align=False)
  14. class BaseClient(object):
  15. __metaclass__ = abc.ABCMeta
  16. def __init__(self):
  17. """设备id"""
  18. self.device_id = 1
  19. '''设备名称'''
  20. self.device_name = "name"
  21. '''设备命令'''
  22. self.device_cmd = "rtn 11;"
  23. '''设备通讯超时值:毫秒'''
  24. self.device_timeout = 300
  25. '''通信sock'''
  26. self.sock = None
  27. '''通信端口号'''
  28. self.port = 5588
  29. '''通信状态'''
  30. self.constate = False
  31. def __def__(self):
  32. self.disconnect()
  33. '''连接服务器'''
  34. def connect(self):
  35. try:
  36. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  37. self.sock.connect(('127.0.0.1', self.port)) # 没有返回值;
  38. self.sock.sendall("2222")
  39. self.constate = True
  40. except Exception, e:
  41. print "BaseClient=> socket connect error:", e, self.port
  42. self.constate = False
  43. return self.constate
  44. # 发送消息;
  45. def sendmsg(self):
  46. '''是否连接'''
  47. if self.constate is False:
  48. if self.connect() is False:
  49. return None
  50. '''拼装要发送的数据包'''
  51. userinfo = np.array([("superAdmin", "123456")], dtype=UserInfo)
  52. '''发送请求数据'''
  53. try:
  54. self.sock.settimeout(5)
  55. phead = np.array([(0xAA, userinfo.itemsize + np.array([(0xAA, 0, 0x01)], dtype=DataHeader).itemsize, 0x00)], dtype=DataHeader)
  56. '''一次性发送完整包'''
  57. # self.sock.sendall(bytearray(phead.tobytes() + bytes(msg_json)))
  58. '''分包发送:头、体'''
  59. self.sock.sendall(phead.tobytes())
  60. self.sock.sendall(userinfo.tobytes())
  61. self.sock.settimeout(None)
  62. except Exception, e:
  63. print "BaseClient=> send Error:", e
  64. self.disconnect()
  65. self.connect()
  66. return None
  67. '''接收返回数据'''
  68. try:
  69. # 等待数据返回;(串口若请求失败,超时值应该设置在3秒以上)
  70. self.sock.settimeout(10)
  71. data = bytes(self.sock.recv(1024 * 8))
  72. print "recv:" + binascii.hexlify(data)
  73. self.sock.settimeout(None)
  74. phead = data[0: np.array([(0xAA, 0, 0x01)], dtype=DataHeader).itemsize]
  75. respone = data[np.array([(0xAA, 0, 0x01)], dtype=DataHeader).itemsize:]
  76. print "respone:" + binascii.hexlify(respone)
  77. '''小端<I, 大端>I, 网络端 !'''
  78. protocol, len, cmd = struct.unpack('<BIB', phead)
  79. status, message = int(struct.unpack('<c', respone))
  80. '''返回头是否有效'''
  81. if protocol != 0xAA and len != data.__len__():
  82. return None
  83. return status
  84. except Exception, e:
  85. print "BaseClient=> recv Error:", e
  86. return None
  87. '''断开连接'''
  88. def disconnect(self):
  89. try:
  90. self.sock.shutdown(2)
  91. self.sock.close()
  92. except Exception, e:
  93. print "BaseClient=> socket disconnect error:", e
  94. class SATClient(object):
  95. __metaclass__ = abc.ABCMeta
  96. def __init__(self):
  97. '''通信sock'''
  98. self.sock = None
  99. '''通信端口号'''
  100. self.port = 5599
  101. '''通信状态'''
  102. self.constate = False
  103. def __def__(self):
  104. self.disconnect()
  105. '''连接服务器'''
  106. def connect(self):
  107. try:
  108. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  109. self.sock.connect(('127.0.0.1', self.port)) # 没有返回值;
  110. self.sock.sendall("2222")
  111. self.constate = True
  112. except Exception, e:
  113. print "BaseClient=> socket connect error:", e, self.port
  114. self.constate = False
  115. return self.constate
  116. # 发送消息;
  117. def sendmsg(self):
  118. '''是否连接'''
  119. if self.constate is False:
  120. if self.connect() is False:
  121. return None
  122. '''拼装要发送的数据包'''
  123. userinfo = np.array([("superAdmin", "123456", "SAT-Admin")], dtype=UserInfo)
  124. '''发送请求数据'''
  125. try:
  126. self.sock.settimeout(5)
  127. phead = np.array([(0xAA, userinfo.itemsize + np.array([(0xAA, 0, 0x01)], dtype=DataHeader).itemsize, 0x00)],
  128. dtype=DataHeader)
  129. '''一次性发送完整包'''
  130. # self.sock.sendall(bytearray(phead.tobytes() + bytes(msg_json)))
  131. '''分包发送:头、体'''
  132. self.sock.sendall(phead.tobytes())
  133. self.sock.sendall(userinfo.tobytes())
  134. self.sock.settimeout(None)
  135. except Exception, e:
  136. print "BaseClient=> send Error:", e
  137. self.disconnect()
  138. self.connect()
  139. return False
  140. # time.sleep(0.1)
  141. # return False
  142. '''接收返回数据'''
  143. try:
  144. # 等待数据返回;(串口若请求失败,超时值应该设置在3秒以上)
  145. self.sock.settimeout(10)
  146. data = bytes(self.sock.recv(1024 * 8))
  147. # print "recv:" + binascii.hexlify(data)
  148. self.sock.settimeout(None)
  149. phead = data[0: np.array([(0xAA, 0, 0x01)], dtype=DataHeader).itemsize]
  150. respone = data[np.array([(0xAA, 0, 0x01)], dtype=DataHeader).itemsize:]
  151. '''
  152. 注意:坑!
  153. 如果respone此时只返回16进制字符 '\x01',Python的字符与C++的不一样,字符就是字符;
  154. 要将16进制字符转成整型,使用ord函数
  155. '''
  156. # print "respone:" + binascii.hexlify(respone)
  157. '''小端<I, 大端>I, 网络端 !'''
  158. protocol, len, cmd = struct.unpack('<BIB', phead)
  159. # loginresult = ord(struct.unpack('<c', respone)[0])
  160. status, message = struct.unpack('<?260s', respone)
  161. '''返回头是否有效'''
  162. if protocol != 0xAA and len != data.__len__():
  163. return False
  164. return status
  165. except Exception, e:
  166. print "BaseClient=> recv Error:", e
  167. return False
  168. '''断开连接'''
  169. def disconnect(self):
  170. try:
  171. self.sock.shutdown(2)
  172. self.sock.close()
  173. except Exception, e:
  174. print "BaseClient=> socket disconnect error:", e
  175. if __name__ == "__main__":
  176. bc = SATClient()
  177. while 1:
  178. print bc.sendmsg()
  179. print "ok!"