awlsim-symtab 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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 isPy2Compat:
  89. inDataBytes = sys.stdin.read()
  90. else:
  91. inDataBytes = sys.stdin.buffer.read()
  92. else:
  93. inDataBytes = safeFileRead(opt_infile)
  94. # Decode the symbol table using S7 compatible encoding.
  95. encoding = SymTabSource.COMPAT_ENCODING
  96. try:
  97. inDataText = inDataBytes.decode(encoding)
  98. except UnicodeError as e:
  99. raise AwlSimError("Failed to %s decode symbol table text: "
  100. "%s" % (encoding, str(e)))
  101. if opt_inputParser:
  102. tab = opt_inputParser.parseText(inDataText,
  103. autodetectFormat=False)
  104. else:
  105. tab = SymTabParser.parseText(inDataText,
  106. autodetectFormat=True)
  107. if opt_outputFormat == "csv":
  108. outDataText = tab.toCSV()
  109. elif opt_outputFormat == "readable-csv":
  110. outDataText = tab.toReadableCSV()
  111. elif opt_outputFormat == "asc":
  112. outDataText = tab.toASC(stripWhitespace=False)
  113. else:
  114. assert(0)
  115. # Encode the symbol table using S7 compatible encoding.
  116. encoding = SymTabSource.COMPAT_ENCODING
  117. try:
  118. outDataBytes = outDataText.encode(encoding)
  119. except UnicodeError as e:
  120. raise AwlSimError("Failed to %s encode symbol table text: "
  121. "%s" % (encoding, str(e)))
  122. if opt_outfile == "-":
  123. if isPy2Compat:
  124. sys.stdout.write(outDataBytes)
  125. sys.stdout.flush()
  126. else:
  127. sys.stdout.buffer.write(outDataBytes)
  128. sys.stdout.buffer.flush()
  129. else:
  130. try:
  131. fd = open(opt_outfile, "wb")
  132. fd.write(outDataBytes)
  133. fd.close()
  134. except IOError as e:
  135. printError("Failed to write output file '%s': %s" %\
  136. (opt_outfile, str(e)))
  137. return ExitCodes.EXIT_ERR_IO
  138. except AwlSimError as e:
  139. printError(e.getReport())
  140. return ExitCodes.EXIT_ERR_SIM
  141. return ExitCodes.EXIT_OK
  142. if __name__ == "__main__":
  143. sys.exit(main())