awlsim-symtab 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #
  4. # AWL simulator - Symbol table parser
  5. #
  6. # Copyright 2014-2016 Michael Buesch <m@bues.ch>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. #
  22. from __future__ import division, absolute_import, print_function, unicode_literals
  23. import sys
  24. import getopt
  25. from awlsim_loader.common import *
  26. from awlsim_loader.core import *
  27. def usage():
  28. print("awlsim-symtab symbol table parser, version %s" %\
  29. VERSION_STRING)
  30. print("")
  31. print("Usage: awlsim-symtab [OPTIONS] [inputfile] [outputfile]")
  32. print("")
  33. print("If inputfile is - or omitted, stdin is used.")
  34. print("If outputfile is - or omitted, stdout is used.")
  35. print("")
  36. print("Options:")
  37. print(" -I|--input-format FMT Input file format.")
  38. print(" FMT may be one of: auto, csv, asc")
  39. print(" Default: auto")
  40. print(" -O|--output-format FMT Input file format.")
  41. print(" FMT may be one of: csv, readable-csv, asc")
  42. print(" Default: readable-csv")
  43. print("")
  44. print("Example usage for converting .ASC to readable .CSV:")
  45. print(" awlsim-symtab -I asc -O readable-csv symbols.asc symbols.csv")
  46. def main():
  47. opt_inputParser = None
  48. opt_outputFormat = "readable-csv"
  49. opt_infile = "-"
  50. opt_outfile = "-"
  51. try:
  52. (opts, args) = getopt.getopt(sys.argv[1:],
  53. "hI:O:",
  54. [ "help", "input-format=", "output-format=", ])
  55. except getopt.GetoptError as e:
  56. printError(str(e))
  57. usage()
  58. return ExitCodes.EXIT_ERR_CMDLINE
  59. for (o, v) in opts:
  60. if o in ("-h", "--help"):
  61. usage()
  62. return ExitCodes.EXIT_OK
  63. if o in ("-I", "--input-format"):
  64. if v.lower() == "auto":
  65. opt_inputParser = None
  66. elif v.lower() in ("csv", "readable-csv"):
  67. opt_inputParser = SymTabParser_CSV
  68. elif v.lower() == "asc":
  69. opt_inputParser = SymTabParser_ASC
  70. else:
  71. printError("Invalid --input-format")
  72. return ExitCodes.EXIT_ERR_CMDLINE
  73. if o in ("-O", "--output-format"):
  74. opt_outputFormat = v.lower()
  75. if opt_outputFormat not in ("csv", "readable-csv", "asc"):
  76. printError("Invalid --output-format")
  77. return ExitCodes.EXIT_ERR_CMDLINE
  78. if len(args) == 1:
  79. opt_infile = args[0]
  80. elif len(args) == 2:
  81. opt_infile = args[0]
  82. opt_outfile = args[1]
  83. elif len(args) > 2:
  84. usage()
  85. return ExitCodes.EXIT_ERR_CMDLINE
  86. try:
  87. if opt_infile == "-":
  88. if isMicroPython:
  89. inDataBytes = sys.stdin.read().encode(SymTabSource.COMPAT_ENCODING)
  90. elif isPy2Compat:
  91. inDataBytes = sys.stdin.read()
  92. else:
  93. inDataBytes = sys.stdin.buffer.read()
  94. else:
  95. inDataBytes = safeFileRead(opt_infile)
  96. # Decode the symbol table using S7 compatible encoding.
  97. encoding = SymTabSource.COMPAT_ENCODING
  98. try:
  99. inDataText = inDataBytes.decode(encoding)
  100. except UnicodeError as e:
  101. raise AwlSimError("Failed to %s decode symbol table text: "
  102. "%s" % (encoding, str(e)))
  103. if opt_inputParser:
  104. tab = opt_inputParser.parseText(inDataText,
  105. autodetectFormat=False)
  106. else:
  107. tab = SymTabParser.parseText(inDataText,
  108. autodetectFormat=True)
  109. if opt_outputFormat == "csv":
  110. outDataText = tab.toCSV()
  111. elif opt_outputFormat == "readable-csv":
  112. outDataText = tab.toReadableCSV()
  113. elif opt_outputFormat == "asc":
  114. outDataText = tab.toASC(stripWhitespace=False)
  115. else:
  116. assert(0)
  117. # Encode the symbol table using S7 compatible encoding.
  118. encoding = SymTabSource.COMPAT_ENCODING
  119. try:
  120. outDataBytes = outDataText.encode(encoding)
  121. except UnicodeError as e:
  122. raise AwlSimError("Failed to %s encode symbol table text: "
  123. "%s" % (encoding, str(e)))
  124. if opt_outfile == "-":
  125. if isMicroPython:
  126. sys.stdout.write(outDataBytes.decode(SymTabSource.COMPAT_ENCODING))
  127. elif isPy2Compat:
  128. sys.stdout.write(outDataBytes)
  129. sys.stdout.flush()
  130. else:
  131. sys.stdout.buffer.write(outDataBytes)
  132. sys.stdout.buffer.flush()
  133. else:
  134. try:
  135. fd = open(opt_outfile, "wb")
  136. fd.write(outDataBytes)
  137. fd.close()
  138. except IOError as e:
  139. printError("Failed to write output file '%s': %s" %\
  140. (opt_outfile, str(e)))
  141. return ExitCodes.EXIT_ERR_IO
  142. except AwlSimError as e:
  143. printError(e.getReport())
  144. return ExitCodes.EXIT_ERR_SIM
  145. return ExitCodes.EXIT_OK
  146. if __name__ == "__main__":
  147. sys.exit(main())