line_length_checker.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import re
  2. import sys
  3. def getValue(line: str, key: str, default = None):
  4. """Convenience function that finds the value in a line of g-code.
  5. When requesting key = x from line "G1 X100" the value 100 is returned.
  6. """
  7. if not key in line or (';' in line and line.find(key) > line.find(';')):
  8. return default
  9. sub_part = line[line.find(key) + 1:]
  10. m = re.search('^-?[0-9]+\.?[0-9]*', sub_part)
  11. if m is None:
  12. return default
  13. try:
  14. return int(m.group(0))
  15. except ValueError: #Not an integer.
  16. try:
  17. return float(m.group(0))
  18. except ValueError: #Not a number at all.
  19. return default
  20. def analyse(gcode, distance_to_report, print_layers = False):
  21. lines_found = 0
  22. previous_x = 0
  23. previous_y = 0
  24. dist_squared = distance_to_report * distance_to_report
  25. current_layer = 0
  26. for line in gcode.split("\n"):
  27. if not line.startswith("G1"):
  28. if line.startswith(";LAYER:"):
  29. previous_x = 0
  30. previous_y = 0
  31. current_layer += 1
  32. continue
  33. current_x = getValue(line, "X")
  34. current_y = getValue(line, "Y")
  35. if current_x is None or current_y is None:
  36. continue
  37. diff_x = current_x - previous_x
  38. diff_y = current_y - previous_y
  39. if diff_x * diff_x + diff_y * diff_y < dist_squared:
  40. lines_found += 1
  41. if print_layers:
  42. print("[!] ", distance_to_report, " layer ", current_layer, " ", previous_x, previous_y)
  43. previous_y = current_y
  44. previous_x = current_x
  45. return lines_found
  46. def loadAndPrettyPrint(file_name):
  47. print(file_name.replace(".gcode",""))
  48. with open(file_name) as f:
  49. data = f.read()
  50. print("| Line length | Num segments |")
  51. print("| ------------- | ------------- |")
  52. print("| 1 |", analyse(data, 1), "|")
  53. print("| 0.5 |", analyse(data, 0.5), "|")
  54. print("| 0.1 |", analyse(data, 0.1), "|")
  55. print("| 0.05 |", analyse(data, 0.05), "|")
  56. print("| 0.01 |", analyse(data, 0.01), "|")
  57. print("| 0.005 |", analyse(data, 0.005), "|")
  58. print("| 0.001 |", analyse(data, 0.001), "|")
  59. if __name__ == "__main__":
  60. if len(sys.argv) != 2 :
  61. print("Usage: <input g-code>")
  62. sys.exit(1)
  63. in_filename = sys.argv[1]
  64. loadAndPrettyPrint(sys.argv[1])