Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

222 lines
6.6 KiB

  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. # -------------------------------------------------------------------------------
  4. # ESPurna OTA manager
  5. # xose.perez@gmail.com
  6. #
  7. # Requires PlatformIO Core
  8. # -------------------------------------------------------------------------------
  9. from __future__ import print_function
  10. import argparse
  11. import re
  12. import socket
  13. import subprocess
  14. import sys
  15. from time import sleep
  16. from zeroconf import ServiceBrowser, ServiceStateChange, Zeroconf
  17. try:
  18. # noinspection PyUnresolvedReferences
  19. input = raw_input # Python2
  20. except NameError:
  21. pass # Python3
  22. # -------------------------------------------------------------------------------
  23. devices = []
  24. description = "ESPurna OTA Manager v0.1"
  25. # -------------------------------------------------------------------------------
  26. def on_service_state_change(zeroconf, service_type, name, state_change):
  27. """
  28. Callback that adds discovered devices to "devices" list
  29. """
  30. if state_change is ServiceStateChange.Added:
  31. info = zeroconf.get_service_info(service_type, name)
  32. if info:
  33. hostname = info.server.split(".")[0]
  34. device = {
  35. 'hostname': hostname.upper(),
  36. 'ip': socket.inet_ntoa(info.address)
  37. }
  38. device['app'] = info.properties.get('app_name', '')
  39. device['version'] = info.properties.get('app_version', '')
  40. device['device'] = info.properties.get('target_board', '')
  41. device['mem_size'] = info.properties.get('mem_size', '')
  42. device['sdk_size'] = info.properties.get('sdk_size', '')
  43. devices.append(device)
  44. def list():
  45. """
  46. Shows the list of discovered devices
  47. """
  48. output_format = "{:>3} {:<25}{:<25}{:<15}{:<15}{:<30}{:<10}{:<10}"
  49. print(output_format.format(
  50. "#",
  51. "HOSTNAME",
  52. "IP",
  53. "APP",
  54. "VERSION",
  55. "DEVICE",
  56. "MEM_SIZE",
  57. "SDK_SIZE",
  58. ))
  59. print("-" * 135)
  60. index = 0
  61. for device in devices:
  62. index = index + 1
  63. print(output_format.format(
  64. index,
  65. device.get('hostname', ''),
  66. device.get('ip', ''),
  67. device.get('app', ''),
  68. device.get('version', ''),
  69. device.get('device', ''),
  70. device.get('mem_size', ''),
  71. device.get('sdk_size', ''),
  72. ))
  73. print()
  74. def get_boards():
  75. """
  76. Grabs board types fro hardware.h file
  77. """
  78. boards = []
  79. for line in open("espurna/config/hardware.h"):
  80. m = re.search(r'defined\((\w*)\)', line)
  81. if m:
  82. boards.append(m.group(1))
  83. return sorted(boards)
  84. def flash():
  85. """
  86. Grabs info from the user about what device to flash
  87. """
  88. # Choose the board
  89. try:
  90. index = int(input("Choose the board you want to flash (empty if none of these): "))
  91. except:
  92. index = 0
  93. if index < 0 or len(devices) < index:
  94. print("Board number must be between 1 and %s\n" % str(len(devices)))
  95. return None
  96. board = {'board': '', 'ip': '', 'size': 0, 'auth': '', 'flags': ''}
  97. if index > 0:
  98. device = devices[index - 1]
  99. board['board'] = device.get('device', '')
  100. board['ip'] = device.get('ip', '')
  101. board['size'] = int(device.get('mem_size', 0) if device.get('mem_size', 0) == device.get('sdk_size', 0) else 0) / 1024
  102. # Choose board type if none before
  103. if len(board['board']) == 0:
  104. print()
  105. count = 1
  106. boards = get_boards()
  107. for name in boards:
  108. print("%3d\t%s" % (count, name))
  109. count = count + 1
  110. print()
  111. try:
  112. index = int(input("Choose the board type you want to flash: "))
  113. except:
  114. index = 0
  115. if index < 1 or len(boards) < index:
  116. print("Board number must be between 1 and %s\n" % str(len(boards)))
  117. return None
  118. board['board'] = boards[index - 1]
  119. # Choose board size of none before
  120. if board['size'] == 0:
  121. try:
  122. board['size'] = int(input("Board memory size (1 for 1M, 4 for 4M): "))
  123. except:
  124. print("Wrong memory size")
  125. return None
  126. # Choose IP of none before
  127. if len(board['ip']) == 0:
  128. try:
  129. board['ip'] = input("IP of the device to flash (empty for 192.168.4.1): ") or "192.168.4.1"
  130. except:
  131. print("Wrong IP")
  132. return None
  133. board['auth'] = input("Authorization key of the device to flash: ")
  134. board['flags'] = input("Extra flags for the build: ")
  135. return board
  136. def run(device, env):
  137. command = "export ESPURNA_IP=\"%s\"; export ESPURNA_BOARD=\"%s\"; export ESPURNA_AUTH=\"%s\"; export ESPURNA_FLAGS=\"%s\"; platformio run --silent --environment %s -t upload"
  138. command = command % (device['ip'], device['board'], device['auth'], device['flags'], env)
  139. subprocess.check_call(command, shell=True)
  140. # -------------------------------------------------------------------------------
  141. if __name__ == '__main__':
  142. # Parse command line options
  143. parser = argparse.ArgumentParser(description=description)
  144. # parser.add_argument("-v", "--verbose", help="show verbose output", default=0, action='count')
  145. parser.add_argument("-f", "--flash", help="flash device", default=0, action='count')
  146. parser.add_argument("-s", "--sort", help="sort devices list by field", default='hostname')
  147. args = parser.parse_args()
  148. print()
  149. print(description)
  150. print()
  151. # Enable logging if verbose
  152. # logging.basicConfig(level=logging.DEBUG)
  153. # logging.getLogger('zeroconf').setLevel(logging.DEBUG)
  154. # Look for sevices
  155. zeroconf = Zeroconf()
  156. browser = ServiceBrowser(zeroconf, "_arduino._tcp.local.", handlers=[on_service_state_change])
  157. sleep(1)
  158. zeroconf.close()
  159. # Sort list
  160. field = args.sort.lower()
  161. if field not in devices[0]:
  162. print("Unknown field '%s'\n" % field)
  163. sys.exit(1)
  164. devices = sorted(devices, key=lambda device: device.get(field, ''))
  165. # List devices
  166. list()
  167. # Flash device
  168. if args.flash > 0:
  169. device = flash()
  170. if device:
  171. env = "esp8266-%sm-ota" % device['size']
  172. # Summary
  173. print()
  174. print("ESPURNA_IP = %s" % device['ip'])
  175. print("ESPURNA_BOARD = %s" % device['board'])
  176. print("ESPURNA_AUTH = %s" % device['auth'])
  177. print("ESPURNA_FLAGS = %s" % device['flags'])
  178. print("ESPURNA_ENV = %s" % env)
  179. response = input("\nAre these values right [y/N]: ")
  180. print()
  181. if response == "y":
  182. run(device, env)