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