send_msg_to_device.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. import os
  4. import sys
  5. from contextlib import closing
  6. # from base import init_env
  7. #
  8. # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "configs.production")
  9. #
  10. # init_env(interactive = False)
  11. #
  12. # from apps.web.device.models import Group
  13. from gevent import socket
  14. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'configs.testing')
  15. PROJECT_ROOT = os.path.join(os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + "/.."), '..')
  16. sys.path.insert(0, PROJECT_ROOT)
  17. from script.base import init_env, get_logger
  18. init_env(interactive = False)
  19. logger = get_logger(__name__)
  20. import simplejson as json
  21. # 启动2个线程,一个线程用于维持心跳,一个线程专门用于监听并处理事件。每分钟一次心跳,如果心跳失败,就重新建立连接。
  22. #
  23. server = '127.0.0.1'
  24. port = 8768
  25. def send_via_tcpip(server, port, message, timeout=0):
  26. # type:(str, int, dict)->dict
  27. payload = json.dumps(message)
  28. result = {"cmd": message["cmd"], "IMEI": str(message["IMEI"]), "rst": -1}
  29. try:
  30. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
  31. if timeout:
  32. s.settimeout(timeout)
  33. s.connect((str(server), int(port)))
  34. s.sendall(payload)
  35. if timeout:
  36. result = json.loads(s.recv(2048))
  37. else:
  38. return {"cmd": message["cmd"], "IMEI": str(message["IMEI"]), "rst": 0}
  39. logger.info(
  40. '[old device(devNo=%s)] request device manager success. result = %s' %
  41. (message['IMEI'], json.dumps(result)))
  42. except Exception, e:
  43. logger.exception('[old device(devNo=%s)] request device manager exception. exception = %s' %
  44. (message['IMEI'], e))
  45. return result
  46. # 回复设备登录成功 {"cmd":"01","sqNo":"0000","IMEI":"55031412782305","data":"680C000000025503141278230500"}
  47. # 读取离线统计数据 {"cmd":"01","sqNo":"1A03","IMEI":"55031412782305","data":"680C1A0300125503141278230501"}
  48. try:
  49. while True:
  50. try:
  51. strSendMsg = raw_input(u"请输入发送给设备的消息: ") #
  52. timeout = raw_input(u"请输入超时时间: ")
  53. jsonData = json.loads(strSendMsg)
  54. send_via_tcpip(server, port, jsonData,int(timeout))
  55. except Exception,e:
  56. continue
  57. except Exception as ex:
  58. print(ex)
  59. print 'I am OVER'