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.

225 lines
7.0 KiB

  1. #!/usr/bin/env python
  2. #-------------------------------------------------------------------------------
  3. # ESPurna OTA manager
  4. # xose.perez@gmail.com
  5. #
  6. # Requires PlatformIO Core
  7. #-------------------------------------------------------------------------------
  8. import sys
  9. import re
  10. import logging
  11. import socket
  12. import argparse
  13. import subprocess
  14. from time import sleep
  15. from zeroconf import ServiceBrowser, ServiceStateChange, Zeroconf
  16. #-------------------------------------------------------------------------------
  17. devices = []
  18. description = "ESPurna OTA Manager v0.1"
  19. #-------------------------------------------------------------------------------
  20. def on_service_state_change(zeroconf, service_type, name, state_change):
  21. '''
  22. Callback that adds discovered devices to "devices" list
  23. '''
  24. if state_change is ServiceStateChange.Added:
  25. info = zeroconf.get_service_info(service_type, name)
  26. if info:
  27. hostname = info.server.split(".")[0]
  28. device = {
  29. 'hostname': hostname.upper(),
  30. 'ip': socket.inet_ntoa(info.address)
  31. }
  32. device['app'] = info.properties.get('app_name', '')
  33. device['version'] = info.properties.get('app_version', '')
  34. device['device'] = info.properties.get('target_board', '')
  35. if 'mem_size' in info.properties:
  36. device['mem_size'] = info.properties.get('mem_size')
  37. if 'sdk_size' in info.properties:
  38. device['sdk_size'] = info.properties.get('sdk_size')
  39. if 'free_space' in info.properties:
  40. device['free_space'] = info.properties.get('free_space')
  41. devices.append(device)
  42. def list():
  43. '''
  44. Shows the list of discovered devices
  45. '''
  46. output_format="{:>3} {:<25}{:<25}{:<15}{:<15}{:<30}{:<10}{:<10}{:<10}"
  47. print(output_format.format(
  48. "#",
  49. "HOSTNAME",
  50. "IP",
  51. "APP",
  52. "VERSION",
  53. "DEVICE",
  54. "MEM_SIZE",
  55. "SDK_SIZE",
  56. "FREE_SPACE"
  57. ))
  58. print "-" * 146
  59. index = 0
  60. for device in devices:
  61. index = index + 1
  62. print(output_format.format(
  63. index,
  64. device.get('hostname', ''),
  65. device.get('ip', ''),
  66. device.get('app', ''),
  67. device.get('version', ''),
  68. device.get('device', ''),
  69. device.get('mem_size', ''),
  70. device.get('sdk_size', ''),
  71. device.get('free_space', ''),
  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'] = raw_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'] = raw_input("Authorization key of the device to flash: ")
  134. board['flags'] = raw_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("-c", "--core", help="flash ESPurna core", default=0, action='count')
  146. parser.add_argument("-f", "--flash", help="flash device", default=0, action='count')
  147. parser.add_argument("-s", "--sort", help="sort devices list by field", default='hostname')
  148. args = parser.parse_args()
  149. print
  150. print description
  151. print
  152. # Enable logging if verbose
  153. #logging.basicConfig(level=logging.DEBUG)
  154. #logging.getLogger('zeroconf').setLevel(logging.DEBUG)
  155. # Look for sevices
  156. zeroconf = Zeroconf()
  157. browser = ServiceBrowser(zeroconf, "_arduino._tcp.local.", handlers=[on_service_state_change])
  158. sleep(5)
  159. zeroconf.close()
  160. if len(devices) == 0:
  161. print "Nothing found!\n"
  162. sys.exit(0)
  163. # Sort list
  164. field = args.sort.lower()
  165. if field not in devices[0]:
  166. print "Unknown field '%s'\n" % field
  167. sys.exit(1)
  168. devices = sorted(devices, key=lambda device: device.get(field, ''))
  169. # List devices
  170. list()
  171. # Flash device
  172. if args.flash > 0:
  173. device = flash()
  174. if device:
  175. # Flash core version?
  176. if args.core > 0:
  177. device['flags'] = "-DESPURNA_CORE " + device['flags']
  178. env = "esp8266-%sm-ota" % device['size']
  179. # Summary
  180. print
  181. print "ESPURNA_IP = %s" % device['ip']
  182. print "ESPURNA_BOARD = %s" % device['board']
  183. print "ESPURNA_AUTH = %s" % device['auth']
  184. print "ESPURNA_FLAGS = %s" % device['flags']
  185. print "ESPURNA_ENV = %s" % env
  186. response = raw_input("\nAre these values right [y/N]: ")
  187. print
  188. if response == "y":
  189. run(device, env)