baseClient.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. #创建ProHeader数据类型
  9. ProHead = np.dtype({'names': ['version', 'len'], 'formats': ['u1', 'u4']})
  10. class BaseClient(object):
  11. __metaclass__ = abc.ABCMeta
  12. def __init__(self):
  13. """设备id"""
  14. self.device_id = 0
  15. '''设备名称'''
  16. self.device_name = ""
  17. '''设备命令'''
  18. self.device_cmd = ""
  19. '''设备通讯超时值:毫秒'''
  20. self.device_timeout = 300
  21. '''通信sock'''
  22. self.sock = None
  23. '''通信端口号'''
  24. self.port = 5566
  25. '''通信状态'''
  26. self.constate = False
  27. def __def__(self):
  28. self.disconnect()
  29. '''连接服务器'''
  30. def connect(self):
  31. try:
  32. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  33. self.sock.connect(('127.0.0.1', self.port)) # 没有返回值;
  34. self.sock.sendall('111')
  35. self.constate = True
  36. except Exception, e:
  37. print "BaseClient=> socket connect error:", e, self.port
  38. self.constate = False
  39. return self.constate
  40. # 发送消息;
  41. def sendmsg(self):
  42. '''是否连接'''
  43. if self.constate is False:
  44. if self.connect() is False:
  45. return None
  46. '''拼装要发送的数据包'''
  47. msg_json = ""
  48. msg_dict = {'device_id': self.device_id, 'device_name': self.device_name, "device_cmd": self.device_cmd, "device_timeout": self.device_timeout}
  49. try:
  50. msg_json = json.dumps(msg_dict)
  51. except Exception:
  52. print "BaseClient=> to json error:", msg_dict
  53. return None
  54. '''发送请求数据'''
  55. try:
  56. self.sock.settimeout(5)
  57. phead = np.array([(0xAA, msg_json.__len__() + np.array([(0xAA, 0)], dtype=ProHead).itemsize)], dtype=ProHead)
  58. '''一次性发送完整包'''
  59. self.sock.sendall(bytearray(phead.tobytes() + bytes(msg_json)))
  60. '''分包发送:头、体'''
  61. # self.sock.sendall(phead.tobytes())
  62. # self.sock.sendall(bytes(msg_json))
  63. self.sock.settimeout(None)
  64. except Exception, e:
  65. print "BaseClient=> send Error:", e
  66. self.disconnect()
  67. self.connect()
  68. return None
  69. '''接收返回数据'''
  70. try:
  71. # 等待数据返回;(串口若请求失败,超时值应该设置在3秒以上)
  72. self.sock.settimeout(10)
  73. data = bytes(self.sock.recv(1024 * 8))
  74. self.sock.settimeout(None)
  75. phead = data[0: np.array([(0xAA, 0)], dtype=ProHead).itemsize]
  76. '''小端<I, 大端>I'''
  77. plen = struct.unpack('<I', phead[1:])[0]
  78. '''返回头是否有效'''
  79. if ord(phead[0]) != 0xAB:
  80. return None
  81. msg_json = data[np.array([(0xAA, 0)], dtype=ProHead).itemsize:]
  82. if plen - 5 != msg_json.__len__():
  83. return None
  84. # print msg_json
  85. msg_json = msg_json.decode('gb2312')
  86. # 解析成json;
  87. msg_dict = json.loads(msg_json)
  88. return msg_dict
  89. except Exception, e:
  90. print "BaseClient=> recv Error:", e
  91. return None
  92. '''断开连接'''
  93. def disconnect(self):
  94. try:
  95. self.sock.shutdown(2)
  96. self.sock.close()
  97. except Exception, e:
  98. print "BaseClient=> socket disconnect error:", e