-
Notifications
You must be signed in to change notification settings - Fork 836
/
Copy pathscrape_supported_devices.py
executable file
·426 lines (376 loc) · 12.7 KB
/
scrape_supported_devices.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#!/usr/bin/env python3
"""Generate SupportedProtocols.md by scraping source code files"""
import pathlib
import argparse
import subprocess
from io import StringIO
import sys
import re
import time
CODE_URL = "https://github.com/crankyoldgit/IRremoteESP8266/blob/master/src/ir_"
BRAND_MODEL = re.compile(r"""
Brand:\s{1,20} # "Brand:" label followd by between 1 and 20 whitespace chars.
\b(?P<brand>.{1,40})\b # The actual brand of the device, max 40 chars.
\s{0,10}, # Followed by at most 10 whitespace chars, then a comma.
\s{1,20} # The between 1 and 20 whitespace chars.
Model:\s{1,20} # "Model:" label followd by between 1 and 20 whitespace chars.
\b(?P<model>.{1,80}) # The model info of the device, max 80 chars.
\s{0,5}$ # Followed by at most 5 whitespaces before the end of line.
""", re.VERBOSE)
ENUMS = re.compile(r"enum (\w{1,60}) {(.{1,5000}?)};", re.DOTALL)
ENUM_ENTRY = re.compile(r"^\s{1,80}(\w{1,80})", re.MULTILINE)
DECODED_PROTOCOLS = re.compile(r"""
.{0,80} # Ignore upto an 80 char line of whitespace/code etc.
# Now look for code that looks like we are assigning the Protocol type.
# There are two typical styles used:
(?:results->decode_type # The first style.
| # Or
typeguess) # The second style
\s{0,5}=\s{0,5} # The assignment operator and potential whitespace
(?:decode_type_t::)? # The protocol could have an optional type prefix.
(\w{1,40}); # Finally, the last word of code should be the Protocol.
""", re.VERBOSE)
AC_FN = re.compile(r"ir_(.{1,80})\.h")
AC_MODEL_ENUM_RE = re.compile(r"(.{1,40})_ac_remote_model_t")
IRSEND_FN_RE = re.compile(r"IRsend\.h")
ALL_FN = re.compile(r"ir_(.{1,80})\.(h|cpp)")
EXCLUDED_PROTOCOLS = ["UNKNOWN", "UNUSED", "kLastDecodeType", "typeguess"]
EXCLUDED_ACS = ["Magiquest", "NEC"]
def getgitcommittime():
"""Call git to get time of last commit
"""
try:
label = subprocess.check_output(\
["git", "show", "-s", "--format=%ct", "HEAD"]).strip()
return int(label)
except FileNotFoundError as err:
print("Git failed, which is ok, no git binary found?:", err)
return None
except subprocess.SubprocessError as err:
print("Git failed, which is ok, see output, maybe no git checkout?:", err)
return None
def getmarkdownheader():
"""Get the generated header
"""
srctime = getgitcommittime()
# pylint: disable=C0209
return """<!--- WARNING: Do NOT edit this file directly.
It is generated by './tools/scrape_supported_devices.py'.
Last generated: {} --->""".format(
time.strftime("%a %d %b %Y %H:%M:%S +0000", time.gmtime(srctime)))
# pylint: enable=C0209
def getallprotocols():
"""Return all protocls configured in IRremoteESP8266.h
"""
irremote = ARGS.directory / "IRremoteESP8266.h"
enums = getenums(irremote)["decode_type_t"]
if not enums:
errorexit("Error getting ENUMS from IRremoteESP8266.h")
return enums
def getdecodedprotocols():
"""All protocols that include decoding support"""
ret = set()
for path in ARGS.directory.iterdir():
if path.suffix != ".cpp":
continue
matches = DECODED_PROTOCOLS.finditer(path.open(encoding="utf-8").read())
for match in matches:
protocol = match.group(1)
if protocol not in EXCLUDED_PROTOCOLS:
ret.add(protocol)
return ret
def getallacs():
"""All supported A/C codes"""
ret = {}
for path in ARGS.directory.iterdir():
match = AC_FN.match(path.name)
if match:
acprotocol = match.group(1)
rawmodels = getenums(path)
models = set()
for model in rawmodels:
model = model.upper()
model = model.replace(f"K{acprotocol.upper()}", "")
if model and model not in EXCLUDED_PROTOCOLS:
models.add(model)
if acprotocol in ret:
ret[acprotocol].update(models)
else:
ret[acprotocol] = models
# Parse IRsend.h's enums
match = IRSEND_FN_RE.match(path.name)
if match:
rawmodels = getenums(path)
for acprotocol, acmodels in rawmodels.items():
models = set()
for model in acmodels:
model = model.upper()
model = model.replace(f"K{acprotocol.upper()}", "")
if model and model not in EXCLUDED_PROTOCOLS:
models.add(model)
if acprotocol in ret:
ret[acprotocol].update(models)
else:
ret[acprotocol] = models
return ret
class FnSets():
"""Container for getalldevices"""
def __init__(self):
self.allcodes = {}
self.fnnomatch = set()
self.allhfileprotos = set()
self.fnhmatch = set()
self.fncppmatch = set()
def add(self, supports, path):
"""add the path to correct set based on supports"""
if path.suffix == ".h":
self.allhfileprotos.add(path.stem)
if supports:
if path.suffix == ".h":
self.fnhmatch.add(path.stem)
elif path.suffix == ".cpp":
self.fncppmatch.add(path.stem)
else:
self.fnnomatch.add(path.stem)
def printwarnings(self):
"""print warnings"""
# all protos with support in .cpp file, when there is a .h file
# meaning that the documentation should probably be moved to .h
# in the future, with doxygen, that might change
protosincppwithh = list(self.fncppmatch & self.allhfileprotos)
if protosincppwithh:
protosincppwithh.sort()
print("The following files has supports section in .cpp, expected in .h")
for path in protosincppwithh:
print(f"\t{path}")
protosincppandh = list(self.fncppmatch & self.fnhmatch)
if protosincppandh:
protosincppandh.sort()
print("The following files has supports section in both .h and .cpp")
for path in protosincppandh:
print(f"\t{path}")
nosupports = self.getnosupports()
if nosupports:
nosupports.sort()
print("The following files had no supports section:")
for path in nosupports:
print(f"\t{path}")
return protosincppwithh or protosincppandh or nosupports
def getnosupports(self):
"""get protos without supports sections"""
return list(self.fnnomatch - self.fnhmatch - self.fncppmatch)
def getalldevices():
"""All devices and associated branding and model information (if available)
"""
sets = FnSets()
for path in ARGS.directory.iterdir():
match = ALL_FN.match(path.name)
if not match:
continue
supports = extractsupports(path)
sets.add(supports, path)
protocol = match.group(1)
for brand, model in supports:
protocolbrand = (protocol, brand)
pbset = sets.allcodes.get(protocolbrand, [])
if model in pbset:
print(f"Model {model} is duplicated for {protocol}, {brand}")
sets.allcodes[protocolbrand] = pbset + [model]
for fnprotocol in sets.getnosupports():
sets.allcodes[(fnprotocol[3:], "Unknown")] = []
return sets
def getenums(path):
"""Returns the keys for the first enum type in path
"""
ret = {}
for enums in ENUMS.finditer(path.open(encoding="utf-8").read()):
if enums:
enum_name = AC_MODEL_ENUM_RE.search(enums.group(1))
if enum_name:
enum_name = enum_name.group(1).capitalize()
else:
enum_name = enums.group(1)
ret[enum_name] = set()
for enum in ENUM_ENTRY.finditer(enums.group(2)):
enum = enum.group(1)
if enum in EXCLUDED_PROTOCOLS:
continue
ret[enum_name].add(enum)
return ret
ARGS = None
def initargs():
"""Init the command line arguments"""
global ARGS # pylint: disable=global-statement
parser = argparse.ArgumentParser()
parser.add_argument(
"-n",
"--noout",
help="generate no output data, combine with --alert to only check",
action="store_true",
)
parser.add_argument(
"-s",
"--stdout",
help="output to stdout rather than SupportedProtocols.md",
action="store_true",
)
parser.add_argument("-v",
"--verbose",
help="increase output verbosity",
action="store_true")
parser.add_argument(
"-a",
"--alert",
help="alert if a file does not have a supports section, "
"non zero exit code if issues where found",
action="store_true",
)
parser.add_argument(
"directory",
nargs="?",
help="directory of the source git checkout",
default=None,
)
ARGS = parser.parse_args()
if ARGS.directory is None:
src = pathlib.Path("../src")
if not src.is_dir():
src = pathlib.Path("./src")
else:
src = pathlib.Path(ARGS.directory) / "src"
if not src.is_dir():
errorexit(f"Directory not valid: {src!s}")
ARGS.directory = src
return ARGS
def getmdfile():
"""Resolves SupportedProtocols.md path"""
foutpath = ARGS.directory / "../SupportedProtocols.md"
return foutpath.resolve()
def errorexit(msg):
"""Print an error and exit on critical error"""
sys.stderr.write(f"{msg}\n")
sys.exit(1)
def extractsupports(path):
"""Extract all of the Supports: sections and associated brands and models
"""
supports = []
insupports = False
for line in path.open(encoding="utf-8"):
if not line.startswith("//"):
continue
line = line[2:].strip()
if line == "Supports:":
insupports = True
continue
if insupports:
match = BRAND_MODEL.match(line)
if match:
supports.append((match.group("brand"), match.group("model")))
else:
insupports = False
continue
# search and inform about any legacy formated supports data
elif any(x in line for x in [ \
"seems compatible with",
"be compatible with",
"it working with here"]):
print(f"\t{path.name} Legacy supports format found\n\t\t{line}")
return supports
def makeurl(txt, path):
"""Make a Markup URL from given filename"""
return f"[{txt}]({CODE_URL + path})"
def outputprotocols(fout, protocols):
"""For a given protocol set, sort and output the markdown"""
protocols = list(protocols)
protocols.sort()
for protocol in protocols:
fout.write(f"- {protocol}\n")
def generate(fout):
"""Generate data to fout
return True on any issues (when alert is active)"""
decodedprotocols = getdecodedprotocols()
sendonly = getallprotocols() - decodedprotocols
allacs = getallacs()
sets = getalldevices()
allcodes = sets.allcodes
allbrands = list(allcodes.keys())
allbrands.sort()
fout.write("\n# IR Protocols supported by this library\n\n")
fout.write(
"| Protocol | Brand | Model | A/C Model | Detailed A/C Support |\n")
fout.write("| --- | --- | --- | --- | --- |\n")
for protocolbrand in allbrands:
protocol, brand = protocolbrand
codes = allcodes[protocolbrand]
codes.sort()
acmodels = []
acsupport = "-"
if protocol in allacs:
acmodels = list(allacs[protocol])
acmodels.sort()
brand = makeurl(brand, protocol + ".h")
if protocol not in EXCLUDED_ACS:
acsupport = "Yes"
# pylint: disable=C0209
fout.write("| {} | **{}** | {} | {} | {} |\n".format(
makeurl(protocol, protocol + ".cpp"),
brand,
"<BR>".join(codes).replace("|", "\\|"),
"<BR>".join(acmodels),
acsupport,
))
# pylint: enable=C0209
fout.write("\n\n## Send only protocols:\n\n")
outputprotocols(fout, sendonly)
fout.write("\n\n## Send & decodable protocols:\n\n")
outputprotocols(fout, decodedprotocols)
return ARGS.alert and sets.printwarnings()
def generatenone():
"""No out write
return True on any issues"""
return generate(StringIO())
def generatestdout():
"""Standard out write
return True on any issues"""
fout = sys.stdout
fout.write(getmarkdownheader())
return generate(fout)
def generatefile():
"""File write, extra detection of changes in existing file
return True on any issues, but only if there is changes"""
# get file path
foutpath = getmdfile()
if ARGS.verbose:
print(f"Output path: {foutpath!s}")
# write data to temp memorystream
ftemp = StringIO()
ret = generate(ftemp)
# get old filedata, skipping header
with getmdfile().open("r", encoding="utf-8") as forg:
olddata = forg.readlines()[3:]
# get new data, skip first empty line
ftemp.seek(0)
newdata = ftemp.readlines()[1:]
# if new data is same as old we don't need to write anything
if newdata == olddata:
print("No changes, exit without write")
return False
# write output
with foutpath.open("w", encoding="utf-8") as fout:
fout.write(getmarkdownheader())
fout.write(ftemp.getvalue())
return ret
def main():
"""Default main function
return True on any issues"""
initargs()
if ARGS.verbose:
print(f"Looking for files in: {ARGS.directory.resolve()!s}")
if ARGS.noout:
return generatenone()
if ARGS.stdout:
return generatestdout()
# default file
return generatefile()
if __name__ == "__main__":
sys.exit(1 if main() else 0)