client.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. from socket import *
  2. from utils import *
  3. from sys import argv
  4. import time
  5. import colorama
  6. from colorama import Fore, Back, Style
  7. import os
  8. TCP_PORT = 80
  9. HEAD = 'POST /api.php HTTP/1.1\r\nHost: 192.168.10.10'
  10. REQ_ID = {'getSpState':'7000000', 'getPpRegs':'3000000', 'getPp':'4000000',
  11. 'getHv':'8000000', 'getIp': '9000000', 'getPreset': '10000000',
  12. 'getPwr':'5000000', 'getMonRegs':'2000000', 'getMon':'1000000',
  13. 'getInfo':'11000000', 'getSp':'7000000', 'setSys':'7000000',
  14. 'setSpState': '7000000', 'setUpdate': '99999', 'getUpdate': '99999'}
  15. time_request = TimeIt()
  16. time_connect = TimeIt()
  17. error_no_answer = 0
  18. erorr_brackets = 0
  19. error_connection = 0
  20. class SBS_client:
  21. def __init__(self, ip='192.168.10.10', port=80, debug=False):
  22. self.DEBUG = debug
  23. self.ip = ip
  24. self.HEAD = 'POST /api.php HTTP/1.1\r\nHost: ' + self.ip + ':' \
  25. + str(port) + '\r\nContent-Length: '
  26. self.addr = (ip, int(port))
  27. def send_recv(self, data):
  28. data = str.encode(data)
  29. try:
  30. self.tcp_socket.send(data)
  31. except:
  32. pass
  33. rec = bytes()
  34. while True:
  35. try:
  36. chank = self.tcp_socket.recv(8000)
  37. rec += chank
  38. if not chank:
  39. break
  40. except:
  41. break
  42. if len(rec) == 0:
  43. error_no_answer += 1
  44. # Проверяем ответ на наличие открывающих и закрывающих скобок
  45. result_str = rec.decode()
  46. open_brackets = result_str.count('{')
  47. close_brackets = result_str.count('}')
  48. if (open_brackets != close_brackets) or open_brackets == 0:
  49. erorr_brackets += 1
  50. if self.DEBUG:
  51. print(Fore.YELLOW + 'Received answer:')
  52. print(Fore.GREEN + rec.decode())
  53. @timeit(time_request)
  54. def http_request(self, method, params):
  55. # foo = '{"jsonrpc":"2.0","method":"' + method + '","params":' + \
  56. # params + ',"id":' + REQ_ID[method] + '}'
  57. # request = self.HEAD + str(len(foo)) + '\r\n\r\n' + foo
  58. # if self.DEBUG:
  59. # print(Fore.YELLOW + 'Send HTTP request:')
  60. # print(Fore.BLUE + request)
  61. if self.connect():
  62. # self.send_recv(request)
  63. self.close()
  64. @timeit(time_connect)
  65. def connect(self):
  66. self.tcp_socket = socket(AF_INET, SOCK_STREAM)
  67. self.tcp_socket.settimeout(15.0)
  68. try:
  69. self.tcp_socket.connect(self.addr)
  70. except:
  71. print("Ошибка соединения")
  72. error_connection += 1
  73. return False
  74. return True
  75. def close(self):
  76. self.tcp_socket.close()
  77. # ---------------------------------------------------------------------
  78. # Обновление
  79. def set_update(self):
  80. params = '{"spID":"0", "update":{"serverIp":"172.16.2.8:9000","fileName":"/dir/fw.bin"}}'
  81. # params = '{"spID":"0", "update":{"serverIp":"172.16.2.8:9000","fileName":"E:\Greenstar\nSBS-ethernet-prime\bin\fw.bin"}}'
  82. self.http_request('setUpdate', params)
  83. def get_update(self):
  84. params = '{"spID":"0"}'
  85. self.http_request('getUpdate', params)
  86. # ---------------------------------------------------------------------
  87. # Уставки
  88. # setPreset
  89. def set_preset(self):
  90. self.send_recv('POST /api\r\n\r\n{{"id":1,"jsonrpc":2.0,"method":\
  91. "setPreset","params":{"mode":"manual"}}')
  92. # ---------------------------------------------------------------------
  93. # Отправка группы команд в начале работы с прибором
  94. def startup(self):
  95. self.http_request('getSpState', 'null')
  96. self.http_request('getPpRegs', 'null')
  97. self.http_request('getPp', 'null')
  98. self.http_request('getHv', 'null')
  99. self.http_request('getIp', 'null')
  100. self.http_request('getPreset', 'null')
  101. self.http_request('getPwr', 'null')
  102. self.http_request('getMonRegs', 'null')
  103. self.http_request('getMon', 'null')
  104. self.http_request('getInfo', 'null')
  105. # Периодический опрос прибора
  106. def periodic_request(self, count=0):
  107. def procedure():
  108. self.http_request('getMon', 'null')
  109. time.sleep(1)
  110. self.http_request('getSpState', 'null')
  111. time.sleep(1)
  112. if count == 0:
  113. while True:
  114. procedure()
  115. else:
  116. for _ in range(count):
  117. procedure()
  118. # Включить демо-данные
  119. def set_demo_data(self):
  120. self.http_request('setSys', '{"demo":true}')
  121. # Управление набором спектра
  122. # start/stop/clear
  123. def set_spectrum_state(self, state: str):
  124. foo = '{"acqState":"' + state + '"}'
  125. self.http_request('setSpState', foo)
  126. self.http_request('getPp', 'null')
  127. # Запрос спектра
  128. def get_spectrum_data(self):
  129. # while True:
  130. # if self.connect():
  131. # self.close()
  132. for i in range(20):
  133. self.http_request('getSp', 'null')
  134. time.sleep(0.1)
  135. # self.http_request('getMon', 'null')
  136. # time.sleep(0.05)
  137. self.info()
  138. def info(self):
  139. print("\033[H\033[J", end="")
  140. print("Время соединения :", round(time_connect.cur_time, 5), round(time_connect.max_time, 5))
  141. print("Время запроса-ответа:", round(time_request.cur_time, 5), round(time_request.max_time, 5))
  142. print("Ошибки. Скобки:", erorr_brackets)
  143. print("Ошибки. Пустой ответ:", error_no_answer)
  144. print("Ошибки. Таймаут соединения:", error_connection)
  145. # Тесты
  146. def processing(ip, port):
  147. colorama.init(autoreset=True)
  148. client = SBS_client(ip, port)
  149. client.DEBUG = False
  150. # client.startup()
  151. # # usb_client.periodic_request(5)
  152. # client.set_demo_data()
  153. # client.set_spectrum_state('start')
  154. client.get_spectrum_data()
  155. def update():
  156. colorama.init(autoreset=True)
  157. dev = SBS_client('172.16.2.101', 80)
  158. dev.set_update()
  159. # dev.get_update()
  160. def test_time():
  161. print(time.time())
  162. time.sleep(1)
  163. print(time.time())
  164. def main():
  165. # test_time()
  166. '''Получение данных спектра'''
  167. processing(argv[1], argv[2])
  168. '''Обновление FW'''
  169. # update()
  170. # client.set_update()
  171. # client.get_update()
  172. # print('{"spID":"0", "update":{"serverIp":"192.168.0.25:80","fileNmae":"полный/путь/к/файлу.bin"}}')
  173. '''
  174. if len(argv) == 2:
  175. print("Укажите IP-адрес и порт устройства")
  176. else:
  177. colorama.init(autoreset=True)
  178. '''
  179. if __name__ == "__main__":
  180. main()