awlsim-test 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #
  4. # AWL simulator - Commandline testing interface
  5. #
  6. # Copyright 2012-2018 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 os
  25. import getopt
  26. import traceback
  27. import signal
  28. from awlsim_loader.common import *
  29. from awlsim_loader.core import *
  30. from awlsim_loader.coreclient import *
  31. from awlsim_loader.awlcompiler import *
  32. from awlsim_loader.fupcompiler import *
  33. import awlsim_loader.cython_helper as cython_helper
  34. class TestAwlSimClient(AwlSimClient):
  35. def handle_CPUDUMP(self, dumpText):
  36. emitCpuDump(dumpText)
  37. class ConsoleSSHTunnel(SSHTunnel):
  38. def sshMessage(self, message, isDebug):
  39. if opt_loglevel > Logging.LOG_INFO:
  40. isDebug = False
  41. super(ConsoleSSHTunnel, self).sshMessage(message, isDebug)
  42. def usage():
  43. print("awlsim version %s" % VERSION_STRING)
  44. print("")
  45. print("Usage: awlsim-test [OPTIONS] <AWL-source or awlsim-project file>")
  46. print("")
  47. print("Options:")
  48. print(" -Y|--cycle-limit SEC Cycle time limit, in seconds (default 1.0)")
  49. print(" -M|--max-runtime SEC CPU will be stopped after SEC seconds (default: off)")
  50. print(" -2|--twoaccu Force 2-accu mode")
  51. print(" -4|--fouraccu Force 4-accu mode")
  52. print(" -D|--no-cpu-dump Do not show CPU status while running")
  53. print(" -x|--extended-insns Enable extended instructions")
  54. print(" -t|--obtemp 1/0 Enable/disable writing of OB-temp variables (Default: off)")
  55. print(" -T|--clock-mem ADDR Force clock memory address (Default: off)")
  56. print(" -m|--mnemonics auto Force mnemonics type: en, de, auto")
  57. print(" -O|--optimizers OPT Sets the optimization mode.")
  58. print(" OPT may be one of:")
  59. print(" default: Keep project settings (default)")
  60. print(" all: Enable all optimizers")
  61. print(" off: Disable all optimizers")
  62. print(" -L|--loglevel LVL Set the log level:")
  63. print(" 0: Log nothing")
  64. print(" 1: Log errors")
  65. print(" 2: Log errors and warnings")
  66. print(" 3: Log errors, warnings and info messages (default)")
  67. print(" 4: Verbose logging")
  68. print(" 5: Extremely verbose logging")
  69. print("")
  70. print("Server backend related options:")
  71. print(" -c|--connect Connect to server backend")
  72. print(" -C|--connect-to IP:PORT Connect to server backend")
  73. print(" -b|--spawn-backend Spawn a new backend server and connect to it")
  74. if not isWinStandalone:
  75. print(" -i|--interpreter EXE Set the backend interpreter executable")
  76. print("")
  77. print("Loading hardware modules:")
  78. print(" -H|--hardware NAME:PARAM=VAL:PARAM=VAL...")
  79. print("Print module information:")
  80. print(" -I|--hardware-info NAME")
  81. print("")
  82. print(" Where NAME is the name of the hardware module.")
  83. print(" PARAM=VAL are optional hardware specific parameters.")
  84. print("")
  85. print("Other options:")
  86. print(" --list-sfc Print a list of all supported SFCs")
  87. print(" --list-sfc-verbose Verbose SFC list")
  88. print(" --list-sfb Print a list of all supported SFBs")
  89. print(" --list-sfb-verbose Verbose SFB list")
  90. print("")
  91. print("Environment variables:")
  92. print(" AWLSIM_PROFILE =0 Disable profiling (default)")
  93. print(" =1 Enable core cycle profiling")
  94. print(" =2 Enable full core profiling (including startup)")
  95. print("")
  96. print(" AWLSIM_CYTHON =0 Do not attempt to use Cython core (default)")
  97. print(" =1 Attempt to use Cython core, but fall back to Python")
  98. print(" =2 Enforce Cython core")
  99. print("")
  100. print(" AWLSIM_AFFINITY =0,2,... Comma separated list of host CPU cores")
  101. print(" to run on. Default: all cores.")
  102. def printSysblockInfo(blockTable, prefix, withExtended, withInterface):
  103. for block in sorted(dictValues(blockTable),
  104. key = lambda b: b.name[0]):
  105. if block.broken:
  106. continue
  107. number, name, desc = block.name
  108. if number < 0 and not withExtended:
  109. continue
  110. if desc:
  111. desc = " (%s)" % desc
  112. else:
  113. desc = ""
  114. print(" %s %d \"%s\"%s" % (prefix, number, name, desc))
  115. if withInterface:
  116. for ftype in (BlockInterfaceField.FTYPE_IN,
  117. BlockInterfaceField.FTYPE_OUT,
  118. BlockInterfaceField.FTYPE_INOUT):
  119. try:
  120. fields = block.interfaceFields[ftype]
  121. except KeyError:
  122. continue
  123. for field in fields:
  124. field.fieldType = ftype
  125. print(" %s" % str(field))
  126. def writeStdout(message):
  127. if Logging.loglevel >= Logging.LOG_INFO:
  128. sys.stdout.write(message)
  129. sys.stdout.flush()
  130. nextScreenUpdate = 0.0
  131. lastDump = ""
  132. lastDumpNrLines = 0
  133. emptyLine = " " * 79
  134. def clearConsole():
  135. # Make cursor visible, clear console and
  136. # move cursor to homeposition.
  137. if osIsPosix:
  138. writeStdout("\x1B[?25h\x1B[2J\x1B[H")
  139. elif osIsWindows:
  140. os.system("cls")
  141. def emitCpuDump(dump):
  142. global lastDump
  143. global lastDumpNrLines
  144. # Pad lines
  145. dumpLines = list(line + (78 - len(line)) * ' ' + '|'
  146. for line in dump.splitlines())
  147. dumpNrLines = len(dumpLines)
  148. # Clear lines from previous dump.
  149. if dumpNrLines < lastDumpNrLines:
  150. dumpLines.extend([ emptyLine, ] * (lastDumpNrLines - dumpNrLines))
  151. dump = "\n".join(dumpLines)
  152. lastDumpNrLines = dumpNrLines
  153. lastDump = dump
  154. if osIsPosix:
  155. # Clear console, move home and print dump.
  156. writeStdout("\x1B[2J\x1B[H" + dump)
  157. else:
  158. # Clear console, move home and print dump.
  159. clearConsole()
  160. writeStdout(dump)
  161. def emitSpeedDump(cpu):
  162. dump = "S7 CPU speed: %s stmt/s" % cpu.insnPerSecondHR
  163. dump += " " * (79 - len(dump))
  164. writeStdout("\x1B[2J\x1B[H" + dump + "\n")
  165. def cpuDumpCallback(cpu):
  166. global nextScreenUpdate
  167. if cpu.now >= nextScreenUpdate:
  168. nextScreenUpdate = cpu.now + 0.3
  169. emitCpuDump(str(cpu))
  170. def cpuStatsCallback(cpu):
  171. global nextScreenUpdate
  172. if cpu.now >= nextScreenUpdate:
  173. nextScreenUpdate = cpu.now + 1.0
  174. emitSpeedDump(cpu)
  175. def assignCpuSpecs(cpuSpecs, projectCpuSpecs):
  176. cpuSpecs.assignFrom(projectCpuSpecs)
  177. if opt_nrAccus is not None:
  178. cpuSpecs.setNrAccus(opt_nrAccus)
  179. def assignCpuConf(cpuConf, projectCpuConf):
  180. cpuConf.assignFrom(projectCpuConf)
  181. if opt_mnemonics is not None:
  182. cpuConf.setConfiguredMnemonics(opt_mnemonics)
  183. if opt_clockMem is not None:
  184. cpuConf.setClockMemByte(opt_clockMem)
  185. if opt_cycletime is not None:
  186. cpuConf.setCycleTimeLimitUs(int(round(opt_cycletime * 1000000.0)))
  187. if opt_maxRuntime is not None:
  188. cpuConf.setRunTimeLimitUs(int(round(opt_maxRuntime * 1000000.0)))
  189. if opt_obtemp is not None:
  190. cpuConf.setOBStartinfoEn(opt_obtemp)
  191. if opt_extInsns is not None:
  192. cpuConf.setExtInsnsEn(opt_extInsns)
  193. def run(inputFile):
  194. s = None
  195. try:
  196. if cython_helper.shouldUseCython():
  197. printInfo("*** Using accelerated CYTHON core "
  198. "(AWLSIM_CYTHON environment variable is set)")
  199. project = Project.fromProjectOrRawAwlFile(inputFile)
  200. printInfo("Parsing code...")
  201. generatedAwlSrcs = []
  202. # Get mnemonics type
  203. mnemonics = project.getCpuConf().getConfiguredMnemonics()
  204. if opt_mnemonics is not None:
  205. mnemonics = opt_mnemonics
  206. # Parse FUP sources
  207. optSettCont = None
  208. if opt_optimizers == "off":
  209. optSettCont = AwlOptimizerSettingsContainer(globalEnable=False)
  210. elif opt_optimizers == "all":
  211. optSettCont = AwlOptimizerSettingsContainer(globalEnable=True,
  212. allEnable=True)
  213. for fupSrc in project.getFupSources():
  214. if not fupSrc.enabled:
  215. continue
  216. generatedAwlSrcs.append(FupCompiler().compile(
  217. fupSource=fupSrc,
  218. symTabSources=project.getSymTabSources(),
  219. mnemonics=mnemonics,
  220. optimizerSettingsContainer=optSettCont))
  221. # Parse KOP sources
  222. for kopSrc in project.getKopSources():
  223. if not kopSrc.enabled:
  224. continue
  225. pass#TODO
  226. # Parse AWL sources
  227. parseTrees = []
  228. for awlSrc in itertools.chain(project.getAwlSources(),
  229. generatedAwlSrcs):
  230. if not awlSrc.enabled:
  231. continue
  232. p = AwlParser()
  233. p.parseSource(awlSrc)
  234. parseTrees.append(p.getParseTree())
  235. # Parse symbol tables
  236. symTables = []
  237. for symTabSrc in project.getSymTabSources():
  238. if not symTabSrc.enabled:
  239. continue
  240. tab = SymTabParser.parseSource(symTabSrc,
  241. autodetectFormat = True,
  242. mnemonics = mnemonics)
  243. symTables.append(tab)
  244. printInfo("Initializing core...")
  245. s = AwlSim()
  246. s.reset()
  247. # Load hardware modules
  248. def loadMod(name, parameters):
  249. printInfo("Loading hardware module '%s'..." % name)
  250. hwClass = s.loadHardwareModule(name)
  251. s.registerHardwareClass(hwClass = hwClass,
  252. parameters = parameters)
  253. for modDesc in project.getHwmodSettings().getLoadedModules():
  254. loadMod(modDesc.getModuleName(),
  255. modDesc.getParameters())
  256. for name, parameters in opt_hwmods:
  257. loadMod(name, parameters)
  258. # Configure the CPU
  259. cpu = s.getCPU()
  260. assignCpuSpecs(cpu.getSpecs(), project.getCpuSpecs())
  261. assignCpuConf(cpu.getConf(), project.getCpuConf())
  262. if not opt_noCpuDump:
  263. if opt_speedStats:
  264. cpu.setBlockExitCallback(cpuStatsCallback, cpu)
  265. elif opt_loglevel >= Logging.LOG_INFO:
  266. cpu.setBlockExitCallback(cpuDumpCallback, cpu)
  267. # Download the program
  268. printInfo("Initializing CPU...")
  269. for symTable in symTables:
  270. s.loadSymbolTable(symTable)
  271. for libSel in project.getLibSelections():
  272. s.loadLibraryBlock(libSel)
  273. for parseTree in parseTrees:
  274. s.load(parseTree)
  275. # Run the program
  276. s.startup()
  277. printInfo("[Initialization finished - CPU is executing user code]")
  278. try:
  279. if not opt_noCpuDump:
  280. clearConsole()
  281. while 1:
  282. s.runCycle()
  283. finally:
  284. if not opt_noCpuDump and opt_loglevel >= Logging.LOG_INFO:
  285. clearConsole()
  286. writeStdout(lastDump + '\n')
  287. except (AwlParserError, AwlSimError) as e:
  288. printError(e.getReport())
  289. return ExitCodes.EXIT_ERR_SIM
  290. except KeyboardInterrupt as e:
  291. pass
  292. except MaintenanceRequest as e:
  293. if e.requestType in (MaintenanceRequest.TYPE_SHUTDOWN,
  294. MaintenanceRequest.TYPE_STOP,
  295. MaintenanceRequest.TYPE_RTTIMEOUT):
  296. printInfo("Shutting down, as requested (%s)..." % str(e))
  297. else:
  298. printError("Received unknown maintenance request "
  299. "(%d: %s)..." % (e.requestType, str(e)))
  300. finally:
  301. if s:
  302. s.shutdown()
  303. return ExitCodes.EXIT_OK
  304. def runWithServerBackend(inputFile):
  305. client = None
  306. tunnel = None
  307. try:
  308. project = Project.fromProjectOrRawAwlFile(inputFile)
  309. linkSettings = project.getCoreLinkSettings()
  310. if opt_spawnBackend:
  311. host = AwlSimServer.DEFAULT_HOST
  312. port = range(AwlSimServer.DEFAULT_PORT,
  313. AwlSimServer.DEFAULT_PORT + 4096)
  314. else:
  315. host = linkSettings.getConnectHost()
  316. port = linkSettings.getConnectPort()
  317. if opt_connectTo:
  318. host, port = opt_connectTo
  319. # Establish SSH tunnel, if requested.
  320. if linkSettings.getTunnel() == linkSettings.TUNNEL_SSH and\
  321. not opt_spawnBackend:
  322. printInfo("Establishing SSH tunnel...")
  323. localPort = linkSettings.getTunnelLocalPort()
  324. if localPort == linkSettings.TUNNEL_LOCPORT_AUTO:
  325. localPort = None
  326. tunnel = ConsoleSSHTunnel(
  327. remoteHost = host,
  328. remotePort = port,
  329. localPort = localPort,
  330. sshUser = linkSettings.getSSHUser(),
  331. sshPort = linkSettings.getSSHPort(),
  332. sshExecutable = linkSettings.getSSHExecutable(),
  333. )
  334. host, port = tunnel.connect()
  335. # Connect to the server
  336. client = TestAwlSimClient()
  337. if opt_spawnBackend:
  338. client.spawnServer(interpreter = opt_interpreter,
  339. listenHost = host,
  340. listenPort = port)
  341. port = client.serverProcessPort
  342. printInfo("Connecting to core server...")
  343. client.connectToServer(host=host, port=port, timeout=20.0)
  344. printInfo("Initializing core...")
  345. client.setLoglevel(opt_loglevel)
  346. client.setRunState(False)
  347. client.reset()
  348. # Load hardware modules
  349. client.loadHardwareModules(project.getHwmodSettings().getLoadedModules())
  350. for name, parameters in opt_hwmods:
  351. client.loadHardwareModule(HwmodDescriptor(name, parameters))
  352. # Configure the core
  353. if opt_noCpuDump:
  354. client.setPeriodicDumpInterval(0)
  355. else:
  356. client.setPeriodicDumpInterval(300)
  357. specs = client.getCpuSpecs()
  358. assignCpuSpecs(specs, project.getCpuSpecs())
  359. client.setCpuSpecs(specs)
  360. conf = client.getCpuConf()
  361. assignCpuConf(conf, project.getCpuConf())
  362. client.setCpuConf(conf)
  363. #TODO configure optimizers
  364. # Fire up the core
  365. printInfo("Initializing CPU...")
  366. client.loadProject(project, loadCpuSpecs=False,
  367. loadCpuConf=False,
  368. loadHwMods=False)
  369. client.setRunState(True)
  370. # Run the client-side event loop
  371. printInfo("[Initialization finished - Remote-CPU is executing user code]")
  372. try:
  373. if not opt_noCpuDump:
  374. clearConsole()
  375. while True:
  376. client.processMessages(None)
  377. finally:
  378. if not opt_noCpuDump and opt_loglevel >= Logging.LOG_INFO:
  379. clearConsole()
  380. writeStdout(lastDump + '\n')
  381. except AwlSimError as e:
  382. printError(e.getReport())
  383. return ExitCodes.EXIT_ERR_SIM
  384. except MaintenanceRequest as e:
  385. if e.requestType in (MaintenanceRequest.TYPE_SHUTDOWN,
  386. MaintenanceRequest.TYPE_STOP,
  387. MaintenanceRequest.TYPE_RTTIMEOUT):
  388. printInfo("Shutting down, as requested (%s)..." % str(e))
  389. else:
  390. printError("Received unknown maintenance request "
  391. "(%d: %s)..." % (e.requestType, str(e)))
  392. except KeyboardInterrupt as e:
  393. pass
  394. finally:
  395. if tunnel:
  396. tunnel.shutdown()
  397. if client:
  398. client.shutdown()
  399. return ExitCodes.EXIT_OK
  400. def __signalHandler(sig, frame):
  401. printInfo("Received signal %d" % sig)
  402. if sig == signal.SIGTERM:
  403. # Raise SIGINT. It will shut down everything.
  404. os.kill(os.getpid(), signal.SIGINT)
  405. def main():
  406. global opt_cycletime
  407. global opt_maxRuntime
  408. global opt_noCpuDump
  409. global opt_speedStats
  410. global opt_nrAccus
  411. global opt_extInsns
  412. global opt_obtemp
  413. global opt_clockMem
  414. global opt_mnemonics
  415. global opt_optimizers
  416. global opt_hwmods
  417. global opt_hwinfos
  418. global opt_loglevel
  419. global opt_connect
  420. global opt_connectTo
  421. global opt_spawnBackend
  422. global opt_interpreter
  423. opt_cycletime = None
  424. opt_maxRuntime = None
  425. opt_noCpuDump = False
  426. opt_speedStats = False
  427. opt_nrAccus = None
  428. opt_extInsns = None
  429. opt_obtemp = None
  430. opt_clockMem = None
  431. opt_mnemonics = None
  432. opt_optimizers = "default"
  433. opt_hwmods = []
  434. opt_hwinfos = []
  435. opt_loglevel = Logging.LOG_INFO
  436. opt_connect = None
  437. opt_connectTo = False
  438. opt_spawnBackend = False
  439. opt_interpreter = None
  440. try:
  441. (opts, args) = getopt.getopt(sys.argv[1:],
  442. "hY:M:24qDSxt:T:m:O:H:I:P:L:cC:bi:",
  443. [ "help", "cycle-limit=", "max-runtime=", "twoaccu", "fouraccu",
  444. "quiet", "no-cpu-dump", "speed-stats", "extended-insns",
  445. "obtemp=", "clock-mem=", "mnemonics=", "optimizers=",
  446. "hardware=", "hardware-info=", "profile=",
  447. "loglevel=",
  448. "connect", "connect-to=", "spawn-backend", "interpreter=",
  449. "list-sfc", "list-sfc-verbose",
  450. "list-sfb", "list-sfb-verbose", ])
  451. except getopt.GetoptError as e:
  452. printError(str(e))
  453. usage()
  454. return ExitCodes.EXIT_ERR_CMDLINE
  455. for (o, v) in opts:
  456. if o in ("-h", "--help"):
  457. usage()
  458. return ExitCodes.EXIT_OK
  459. if o in ("-Y", "--cycle-limit"):
  460. try:
  461. opt_cycletime = float(v)
  462. except ValueError:
  463. printError("-Y|--cycle-limit: Invalid time format")
  464. sys.exit(1)
  465. if o in ("-M", "--max-runtime"):
  466. try:
  467. opt_maxRuntime = float(v)
  468. except ValueError:
  469. printError("-M|--max-runtime: Invalid time format")
  470. sys.exit(1)
  471. if o in ("-2", "--twoaccu"):
  472. opt_nrAccus = 2
  473. if o in ("-4", "--fouraccu"):
  474. opt_nrAccus = 4
  475. if o in ("-D", "--no-cpu-dump"):
  476. opt_noCpuDump = True
  477. if o in ("-S", "--speed-stats"):
  478. opt_speedStats = True
  479. if o in ("-x", "--extended-insns"):
  480. opt_extInsns = True
  481. if o in ("-t", "--obtemp"):
  482. opt_obtemp = str2bool(v)
  483. if o in ("-T", "--clock-mem"):
  484. try:
  485. opt_clockMem = int(v)
  486. if opt_clockMem < -1 or opt_clockMem > 0xFFFF:
  487. raise ValueError
  488. except ValueError:
  489. printError("-T|--clock-mem: Invalid byte address")
  490. sys.exit(1)
  491. if o in ("-m", "--mnemonics"):
  492. opt_mnemonics = v.lower()
  493. if opt_mnemonics not in ("en", "de", "auto"):
  494. printError("-m|--mnemonics: Invalid mnemonics type")
  495. sys.exit(1)
  496. if o in ("-O", "--optimizers"):
  497. try:
  498. modes = v.split(",")
  499. for mode in modes:
  500. mode = mode.lower()
  501. if mode in ("off", "all", "default"):
  502. opt_optimizers = mode
  503. else:
  504. printError("-O|--optimizers: Unknown optimizer: %s" % mode)
  505. sys.exit(1)
  506. except (ValueError, IndexError) as e:
  507. printError("-O|--optimizers: Invalid optimization mode")
  508. sys.exit(1)
  509. if o in ("-H", "--hardware"):
  510. try:
  511. v = v.split(':')
  512. if not v:
  513. raise ValueError
  514. name = v[0]
  515. params = {}
  516. for pstr in v[1:]:
  517. if not pstr:
  518. continue
  519. i = pstr.find('=')
  520. if i < 0:
  521. raise ValueError
  522. pname = pstr[:i]
  523. pval = pstr[i+1:]
  524. if not pname or not pval:
  525. raise ValueError
  526. params[pname] = pval
  527. opt_hwmods.append( (name, params) )
  528. except (ValueError, IndexError) as e:
  529. printError("-H|--hardware: Invalid module name or parameters")
  530. sys.exit(1)
  531. if o in ("-I", "--hardware-info"):
  532. opt_hwinfos.append(v.split(':')[0])
  533. if o in ("-L", "--loglevel"):
  534. try:
  535. opt_loglevel = int(v)
  536. except ValueError:
  537. printError("-L|--loglevel: Invalid log level")
  538. sys.exit(1)
  539. if o in ("-c", "--connect"):
  540. opt_connect = True
  541. if o in ("-C", "--connect-to"):
  542. try:
  543. idx = v.rfind(":")
  544. if idx <= 0:
  545. raise ValueError
  546. opt_connectTo = (v[:idx], int(v[idx+1:]))
  547. except ValueError:
  548. printError("-c|--connect: Invalid host/port")
  549. sys.exit(1)
  550. if o in ("-b", "--spawn-backend"):
  551. opt_spawnBackend = True
  552. if o in ("-i", "--interpreter"):
  553. if isWinStandalone:
  554. printError("-i|--interpreter not supported on win-standalone")
  555. sys.exit(1)
  556. opt_interpreter = v
  557. if o in ("--list-sfc", "--list-sfc-verbose"):
  558. print("The supported system functions (SFCs) are:")
  559. from awlsim.core.systemblocks.tables import SFC_table
  560. printSysblockInfo(SFC_table, "SFC", bool(opt_extInsns),
  561. o.endswith("verbose"))
  562. return ExitCodes.EXIT_OK
  563. if o in ("--list-sfb", "--list-sfb-verbose"):
  564. print("The supported system function blocks (SFBs) are:")
  565. from awlsim.core.systemblocks.tables import SFB_table
  566. printSysblockInfo(SFB_table, "SFB", bool(opt_extInsns),
  567. o.endswith("verbose"))
  568. return ExitCodes.EXIT_OK
  569. if len(args) != 1 and not opt_hwinfos:
  570. usage()
  571. return ExitCodes.EXIT_ERR_CMDLINE
  572. if args:
  573. inputFile = args[0]
  574. Logging.setLoglevel(opt_loglevel)
  575. opt_mnemonics = {
  576. None : None,
  577. "en" : S7CPUConfig.MNEMONICS_EN,
  578. "de" : S7CPUConfig.MNEMONICS_DE,
  579. "auto" : S7CPUConfig.MNEMONICS_AUTO,
  580. }[opt_mnemonics]
  581. try:
  582. if opt_hwinfos:
  583. # Just print the hardware-infos and exit.
  584. for name in opt_hwinfos:
  585. cls = AwlSim.loadHardwareModule(name)
  586. print(cls.getModuleInfo())
  587. return ExitCodes.EXIT_OK
  588. except (AwlParserError, AwlSimError) as e:
  589. printError(e.getReport())
  590. return ExitCodes.EXIT_ERR_SIM
  591. signal.signal(signal.SIGTERM, __signalHandler)
  592. if opt_interpreter and not opt_spawnBackend:
  593. printError("Selected an --interpreter, but no "
  594. "--spawn-backend was requested.")
  595. return ExitCodes.EXIT_ERR_CMDLINE
  596. if opt_spawnBackend or opt_connect or opt_connectTo:
  597. return runWithServerBackend(inputFile)
  598. return run(inputFile)
  599. if __name__ == "__main__":
  600. sys.exit(main())