esp_local_ctrl.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. from __future__ import print_function
  18. from future.utils import tobytes
  19. from builtins import input
  20. import os
  21. import sys
  22. import struct
  23. import argparse
  24. import ssl
  25. import proto
  26. # The tools directory is already in the PATH in environment prepared by install.sh which would allow to import
  27. # esp_prov as file but not as complete module.
  28. sys.path.insert(0, os.path.join(os.environ['IDF_PATH'], 'tools/esp_prov'))
  29. import esp_prov # noqa: E402
  30. # Set this to true to allow exceptions to be thrown
  31. config_throw_except = False
  32. # Property types enum
  33. PROP_TYPE_TIMESTAMP = 0
  34. PROP_TYPE_INT32 = 1
  35. PROP_TYPE_BOOLEAN = 2
  36. PROP_TYPE_STRING = 3
  37. # Property flags enum
  38. PROP_FLAG_READONLY = (1 << 0)
  39. def prop_typestr(prop):
  40. if prop["type"] == PROP_TYPE_TIMESTAMP:
  41. return "TIME(us)"
  42. elif prop["type"] == PROP_TYPE_INT32:
  43. return "INT32"
  44. elif prop["type"] == PROP_TYPE_BOOLEAN:
  45. return "BOOLEAN"
  46. elif prop["type"] == PROP_TYPE_STRING:
  47. return "STRING"
  48. return "UNKNOWN"
  49. def encode_prop_value(prop, value):
  50. try:
  51. if prop["type"] == PROP_TYPE_TIMESTAMP:
  52. return struct.pack('q', value)
  53. elif prop["type"] == PROP_TYPE_INT32:
  54. return struct.pack('i', value)
  55. elif prop["type"] == PROP_TYPE_BOOLEAN:
  56. return struct.pack('?', value)
  57. elif prop["type"] == PROP_TYPE_STRING:
  58. return tobytes(value)
  59. return value
  60. except struct.error as e:
  61. print(e)
  62. return None
  63. def decode_prop_value(prop, value):
  64. try:
  65. if prop["type"] == PROP_TYPE_TIMESTAMP:
  66. return struct.unpack('q', value)[0]
  67. elif prop["type"] == PROP_TYPE_INT32:
  68. return struct.unpack('i', value)[0]
  69. elif prop["type"] == PROP_TYPE_BOOLEAN:
  70. return struct.unpack('?', value)[0]
  71. elif prop["type"] == PROP_TYPE_STRING:
  72. return value.decode('latin-1')
  73. return value
  74. except struct.error as e:
  75. print(e)
  76. return None
  77. def str_to_prop_value(prop, strval):
  78. try:
  79. if prop["type"] == PROP_TYPE_TIMESTAMP:
  80. return int(strval)
  81. elif prop["type"] == PROP_TYPE_INT32:
  82. return int(strval)
  83. elif prop["type"] == PROP_TYPE_BOOLEAN:
  84. return bool(strval)
  85. elif prop["type"] == PROP_TYPE_STRING:
  86. return strval
  87. return strval
  88. except ValueError as e:
  89. print(e)
  90. return None
  91. def prop_is_readonly(prop):
  92. return (prop["flags"] & PROP_FLAG_READONLY) != 0
  93. def on_except(err):
  94. if config_throw_except:
  95. raise RuntimeError(err)
  96. else:
  97. print(err)
  98. def get_transport(sel_transport, service_name, check_hostname):
  99. try:
  100. tp = None
  101. if (sel_transport == 'http'):
  102. example_path = os.environ['IDF_PATH'] + "/examples/protocols/esp_local_ctrl"
  103. cert_path = example_path + "/main/certs/rootCA.pem"
  104. ssl_ctx = ssl.create_default_context(cafile=cert_path)
  105. ssl_ctx.check_hostname = check_hostname
  106. tp = esp_prov.transport.Transport_HTTP(service_name, ssl_ctx)
  107. elif (sel_transport == 'ble'):
  108. tp = esp_prov.transport.Transport_BLE(
  109. devname=service_name, service_uuid='0000ffff-0000-1000-8000-00805f9b34fb',
  110. nu_lookup={'esp_local_ctrl/version': '0001',
  111. 'esp_local_ctrl/session': '0002',
  112. 'esp_local_ctrl/control': '0003'}
  113. )
  114. return tp
  115. except RuntimeError as e:
  116. on_except(e)
  117. return None
  118. def version_match(tp, expected, verbose=False):
  119. try:
  120. response = tp.send_data('esp_local_ctrl/version', expected)
  121. return (response.lower() == expected.lower())
  122. except Exception as e:
  123. on_except(e)
  124. return None
  125. def get_all_property_values(tp):
  126. try:
  127. props = []
  128. message = proto.get_prop_count_request()
  129. response = tp.send_data('esp_local_ctrl/control', message)
  130. count = proto.get_prop_count_response(response)
  131. if count == 0:
  132. raise RuntimeError("No properties found!")
  133. indices = [i for i in range(count)]
  134. message = proto.get_prop_vals_request(indices)
  135. response = tp.send_data('esp_local_ctrl/control', message)
  136. props = proto.get_prop_vals_response(response)
  137. if len(props) != count:
  138. raise RuntimeError("Incorrect count of properties!")
  139. for p in props:
  140. p["value"] = decode_prop_value(p, p["value"])
  141. return props
  142. except RuntimeError as e:
  143. on_except(e)
  144. return []
  145. def set_property_values(tp, props, indices, values, check_readonly=False):
  146. try:
  147. if check_readonly:
  148. for index in indices:
  149. if prop_is_readonly(props[index]):
  150. raise RuntimeError("Cannot set value of Read-Only property")
  151. message = proto.set_prop_vals_request(indices, values)
  152. response = tp.send_data('esp_local_ctrl/control', message)
  153. return proto.set_prop_vals_response(response)
  154. except RuntimeError as e:
  155. on_except(e)
  156. return False
  157. if __name__ == '__main__':
  158. parser = argparse.ArgumentParser(add_help=False)
  159. parser = argparse.ArgumentParser(description="Control an ESP32 running esp_local_ctrl service")
  160. parser.add_argument("--version", dest='version', type=str,
  161. help="Protocol version", default='')
  162. parser.add_argument("--transport", dest='transport', type=str,
  163. help="transport i.e http or ble", default='http')
  164. parser.add_argument("--name", dest='service_name', type=str,
  165. help="BLE Device Name / HTTP Server hostname or IP", default='')
  166. parser.add_argument("--dont-check-hostname", action="store_true",
  167. # If enabled, the certificate won't be rejected for hostname mismatch.
  168. # This option is hidden because it should be used only for testing purposes.
  169. help=argparse.SUPPRESS)
  170. parser.add_argument("-v", "--verbose", dest='verbose', help="increase output verbosity", action="store_true")
  171. args = parser.parse_args()
  172. if args.version != '':
  173. print("==== Esp_Ctrl Version: " + args.version + " ====")
  174. if args.service_name == '':
  175. args.service_name = 'my_esp_ctrl_device'
  176. if args.transport == 'http':
  177. args.service_name += '.local'
  178. obj_transport = get_transport(args.transport, args.service_name, not args.dont_check_hostname)
  179. if obj_transport is None:
  180. print("---- Invalid transport ----")
  181. exit(1)
  182. if args.version != '':
  183. print("\n==== Verifying protocol version ====")
  184. if not version_match(obj_transport, args.version, args.verbose):
  185. print("---- Error in protocol version matching ----")
  186. exit(2)
  187. print("==== Verified protocol version successfully ====")
  188. while True:
  189. properties = get_all_property_values(obj_transport)
  190. if len(properties) == 0:
  191. print("---- Error in reading property values ----")
  192. exit(4)
  193. print("\n==== Available Properties ====")
  194. print("{0: >4} {1: <16} {2: <10} {3: <16} {4: <16}".format(
  195. "S.N.", "Name", "Type", "Flags", "Value"))
  196. for i in range(len(properties)):
  197. print("[{0: >2}] {1: <16} {2: <10} {3: <16} {4: <16}".format(
  198. i + 1, properties[i]["name"], prop_typestr(properties[i]),
  199. ["","Read-Only"][prop_is_readonly(properties[i])],
  200. str(properties[i]["value"])))
  201. select = 0
  202. while True:
  203. try:
  204. inval = input("\nSelect properties to set (0 to re-read, 'q' to quit) : ")
  205. if inval.lower() == 'q':
  206. print("Quitting...")
  207. exit(5)
  208. invals = inval.split(',')
  209. selections = [int(val) for val in invals]
  210. if min(selections) < 0 or max(selections) > len(properties):
  211. raise ValueError("Invalid input")
  212. break
  213. except ValueError as e:
  214. print(str(e) + "! Retry...")
  215. if len(selections) == 1 and selections[0] == 0:
  216. continue
  217. set_values = []
  218. set_indices = []
  219. for select in selections:
  220. while True:
  221. inval = input("Enter value to set for property (" + properties[select - 1]["name"] + ") : ")
  222. value = encode_prop_value(properties[select - 1],
  223. str_to_prop_value(properties[select - 1], inval))
  224. if value is None:
  225. print("Invalid input! Retry...")
  226. continue
  227. break
  228. set_values += [value]
  229. set_indices += [select - 1]
  230. if not set_property_values(obj_transport, properties, set_indices, set_values):
  231. print("Failed to set values!")