awlsim-linuxcnc-hal 14.1 KB
Newer Older
1 2 3 4 5
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# AWL simulator - LinuxCNC HAL module
#
Michael Büsch's avatar
Michael Büsch committed
6
# Copyright 2013-2016 Michael Buesch <m@bues.ch>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

23
from __future__ import division, absolute_import, print_function, unicode_literals
24 25 26

import sys
import os
27
import time
28 29
import getopt

30 31 32
from awlsim_loader.common import *
from awlsim_loader.coreserver import *
from awlsim_loader.coreclient import *
33

34

35 36
class LinuxCNC_NotRunning(Exception):
	pass
37

38 39 40
# Check presence of LinuxCNC.
# Returns normally, if LinuxCNC is detected.
# Raises LinuxCNC_NotRunning, if LinuxCNC is not detected.
41 42
def watchdogHook(_unused = None):
	# Check whether LinuxCNC is running.
43
	for lockname in ("/tmp/linuxcnc.lock", "/tmp/emc.lock"):
44
		if fileExists(lockname):
45
			return True
46
	if not opt_watchdog:
Michael Büsch's avatar
Michael Büsch committed
47 48
		# The check is disabled. Return success.
		return True
49 50 51
	printError("LinuxCNC doesn't seem to be running. "\
		   "(Use '--watchdog off' to disable this check.)")
	raise LinuxCNC_NotRunning()
52 53 54 55 56 57 58 59 60 61 62 63

# Create the LinuxCNC HAL pins
def createHalPins(hal,
		  inputBase, inputSize,
		  outputBase, outputSize):
	HAL_BIT, HAL_U32, HAL_S32, HAL_FLOAT = \
		LinuxCNC_HAL.HAL_BIT, LinuxCNC_HAL.HAL_U32, \
		LinuxCNC_HAL.HAL_S32, LinuxCNC_HAL.HAL_FLOAT
	HAL_IN, HAL_OUT, HAL_RO, HAL_RW = \
		LinuxCNC_HAL.HAL_IN, LinuxCNC_HAL.HAL_OUT, \
		LinuxCNC_HAL.HAL_RO, LinuxCNC_HAL.HAL_RW

64 65 66 67 68
	printInfo("Mapped AWL/STL input area:  P#E %d.0 BYTE %d" %\
		  (inputBase, inputSize))
	printInfo("Mapped AWL/STL output area:  P#A %d.0 BYTE %d" %\
		  (outputBase, outputSize))

69 70
	# Create the input pins
	for i in range(inputBase, inputBase + inputSize):
71
		offset = i - inputBase
72 73 74
		for bit in range(8):
			hal.newpin("input.bit.%d.%d" % (i, bit), HAL_BIT, HAL_IN)
			hal.newparam("input.bit.%d.%d.active" % (i, bit), HAL_BIT, HAL_RW)
75 76 77
		hal.newpin("input.u8.%d" % i, HAL_U32, HAL_IN)
		hal.newparam("input.u8.%d.active" % i, HAL_BIT, HAL_RW)
		if i % 2:
78
			continue
79 80 81 82 83 84 85 86 87 88
		if inputSize - offset < 2:
			continue
		hal.newpin("input.u16.%d" % i, HAL_U32, HAL_IN)
		hal.newparam("input.u16.%d.active" % i, HAL_BIT, HAL_RW)
		hal.newpin("input.s16.%d" % i, HAL_S32, HAL_IN)
		hal.newparam("input.s16.%d.active" % i, HAL_BIT, HAL_RW)
		if inputSize - offset < 4:
			continue
		hal.newpin("input.u31.%d" % i, HAL_U32, HAL_IN)
		hal.newparam("input.u31.%d.active" % i, HAL_BIT, HAL_RW)
89 90 91 92 93 94 95
		hal.newpin("input.s32.%d" % i, HAL_S32, HAL_IN)
		hal.newparam("input.s32.%d.active" % i, HAL_BIT, HAL_RW)
		hal.newpin("input.float.%d" % i, HAL_FLOAT, HAL_IN)
		hal.newparam("input.float.%d.active" % i, HAL_BIT, HAL_RW)

	# Create the output pins
	for i in range(outputBase, outputBase + outputSize):
96
		offset = i - outputBase
97 98
		for bit in range(8):
			hal.newpin("output.bit.%d.%d" % (i, bit), HAL_BIT, HAL_OUT)
99 100 101 102 103 104
			hal.newparam("output.bit.%d.%d.active" % (i, bit), HAL_BIT, HAL_RW)
		hal.newpin("output.u8.%d" % i, HAL_U32, HAL_OUT)
		hal.newparam("output.u8.%d.active" % i, HAL_BIT, HAL_RW)
		if i % 2:
			continue
		if outputSize - offset < 2:
105
			continue
106 107 108 109 110 111 112 113
		hal.newpin("output.u16.%d" % i, HAL_U32, HAL_OUT)
		hal.newparam("output.u16.%d.active" % i, HAL_BIT, HAL_RW)
		hal.newpin("output.s16.%d" % i, HAL_S32, HAL_OUT)
		hal.newparam("output.s16.%d.active" % i, HAL_BIT, HAL_RW)
		if outputSize - offset < 4:
			continue
		hal.newpin("output.u31.%d" % i, HAL_U32, HAL_OUT)
		hal.newparam("output.u31.%d.active" % i, HAL_BIT, HAL_RW)
114
		hal.newpin("output.s32.%d" % i, HAL_S32, HAL_OUT)
115
		hal.newparam("output.s32.%d.active" % i, HAL_BIT, HAL_RW)
116
		hal.newpin("output.float.%d" % i, HAL_FLOAT, HAL_OUT)
117 118 119
		hal.newparam("output.float.%d.active" % i, HAL_BIT, HAL_RW)

	hal.newparam("config.ready", HAL_BIT, HAL_RW)
120 121

def usage():
122 123
	print("awlsim-linuxcnc-hal version %s" % VERSION_STRING)
	print("")
124
	print("Usage: awlsim-linuxcnc-hal [OPTIONS] PROJECT.awlpro")
125 126
	print("")
	print("Options:")
127
	print(" -i|--input-size SIZE    The input area size, in bytes.")
128
	print("                         Overrides input-size from project file.")
129
	print(" -I|--input-base BASE    The AWL/STL input address base.")
130
	print("                         Overrides input-base from project file.")
131
	print(" -o|--output-size SIZE   The output area size, in bytes.")
132
	print("                         Overrides output-size from project file.")
133
	print(" -O|--output-base BASE   The AWL/STL output address base.")
134
	print("                         Overrides output-base from project file.")
135 136 137 138 139
	print("")
	print(" -l|--listen HOST:PORT   Set the address and port where the")
	print("                         awlsim core server should listen on.")
	print("                         Defaults to %s:%d" %\
		  (AwlSimServer.DEFAULT_HOST, AwlSimServer.DEFAULT_PORT))
140
	print("")
141 142 143 144 145 146 147 148
	print(" -L|--loglevel LVL       Set the log level:")
	print("                         0: Log nothing")
	print("                         1: Log errors")
	print("                         2: Log errors and warnings")
	print("                         3: Log errors, warnings and info messages (default)")
	print("                         4: Verbose logging")
	print("                         5: Extremely verbose logging")
	print(" -N|--nice NICE          Renice the process. -20 <= NICE <= 19.")
149 150 151 152 153 154 155 156
	print("                         Default: Do not renice")
	print("")
	print("Debugging options:")
	print(" -W|--watchdog 1/0       Enable/disable LinuxCNC runtime watchdog.")
	print("                         Default: on")
	print(" -M|--max-runtime SEC    Module will be stopped after SEC seconds.")
	print("                         Default: No timeout")
	print(" -x|--extended-insns     Force-enable extended instructions")
157 158
	print("")
	print("For an example LinuxCNC HAL configuration see:")
159
	print("  examples/linuxcnc-demo/linuxcnc-demo.hal")
160 161

def main():
162 163 164 165 166 167 168 169 170
	global LinuxCNC_HAL

	global opt_inputSize
	global opt_inputBase
	global opt_outputSize
	global opt_outputBase
	global opt_listen
	global opt_loglevel
	global opt_nice
171
	global opt_watchdog
172 173
	global opt_maxRuntime
	global opt_extInsns
Michael Büsch's avatar
Michael Büsch committed
174

175 176 177 178
	opt_inputSize = None
	opt_inputBase = None
	opt_outputSize = None
	opt_outputBase = None
179 180 181
	opt_listen = (AwlSimServer.DEFAULT_HOST, AwlSimServer.DEFAULT_PORT)
	opt_loglevel = Logging.LOG_INFO
	opt_nice = None
182 183 184
	opt_watchdog = True
	opt_maxRuntime = -1.0
	opt_extInsns = None
185 186 187

	try:
		(opts, args) = getopt.getopt(sys.argv[1:],
188
			"hi:I:o:O:l:L:N:W:M:x",
189
			[ "help", "input-size=", "input-base=",
190 191
			  "output-size=", "output-base=",
			  "listen=",
192 193
			  "loglevel=", "nice=",
			  "watchdog=", "max-runtime=", "extended-insns", ])
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
	except getopt.GetoptError as e:
		printError(str(e))
		usage()
		return 1
	for (o, v) in opts:
		if o in ("-h", "--help"):
			usage()
			return 0
		if o in ("-i", "--input-size"):
			try:
				opt_inputSize = int(v)
			except ValueError:
				printError("-i|--input-size: Invalid argument")
				return 1
		if o in ("-I", "--input-base"):
			try:
				opt_inputBase = int(v)
			except ValueError:
				printError("-I|--input-base: Invalid argument")
				return 1
		if o in ("-o", "--output-size"):
			try:
				opt_outputSize = int(v)
			except ValueError:
				printError("-o|--output-size: Invalid argument")
				return 1
		if o in ("-O", "--output-base"):
			try:
				opt_outputBase = int(v)
			except ValueError:
				printError("-O|--output-base: Invalid argument")
				return 1
226 227
		if o in ("-l", "--listen"):
			try:
228 229 230 231 232 233 234 235
				host, port = parseNetAddress(v)
				if not host.strip() or\
				   host in {"any", "all"}:
					host = ""
				if port is None:
					port = AwlSimServer.DEFAULT_PORT
				opt_listen = (host, port)
			except AwlSimError as e:
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
				printError("-l|--listen: Invalid host/port")
				return 1
		if o in ("-L", "--loglevel"):
			try:
				opt_loglevel = int(v)
			except ValueError:
				printError("-L|--loglevel: Invalid log level")
				return 1
		if o in ("-N", "--nice"):
			try:
				opt_nice = int(v)
				if opt_nice < -20 or opt_nice > 19:
					raise ValueError
			except ValueError:
				printError("-N|--nice: Invalid niceness level")
				return 1
252 253 254 255 256 257 258 259 260 261
		if o in ("-W", "--watchdog"):
			opt_watchdog = str2bool(v)
		if o in ("-M", "--max-runtime"):
			try:
				opt_maxRuntime = float(v)
			except ValueError:
				printError("-M|--max-runtime: Invalid time format")
				return 1
		if o in ("-x", "--extended-insns"):
			opt_extInsns = True
262 263 264
	if len(args) != 1:
		usage()
		return 1
265
	projectFile = args[0]
266

Michael Büsch's avatar
Michael Büsch committed
267
	result = ExitCodes.EXIT_OK
268
	try:
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
		Logging.setPrefix("awlsim-linuxcnc: ")
		Logging.setLoglevel(opt_loglevel)

		# Adjust process priority
		if opt_nice is not None:
			try:
				os.nice(opt_nice)
			except OSError as e:
				printError("Failed to renice process to "
					   "%d: %s" % (opt_nice, str(e)))
				return 1

		# Try to import the LinuxCNC HAL module
		try:
			import hal as LinuxCNC_HAL
		except ImportError as e:
			printError("Failed to import LinuxCNC HAL "
				   "module: %s" % str(e))
			return 1

		# Create the LinuxCNC HAL component.
290 291
		hal = LinuxCNC_HAL.component("awlsim")

292
		# Read the project.
293
		project = Project.fromProjectOrRawAwlFile(projectFile)
294 295 296 297 298 299 300 301 302 303 304
		hwmodSettings = project.getHwmodSettings()
		# Get the 'linuxcnc' hardware module descriptor.
		linuxcncHwmodDesc = None
		for modDesc in hwmodSettings.getLoadedModules():
			if modDesc.getModuleName() == "linuxcnc":
				if linuxcncHwmodDesc:
					printError("ERROR: More than one 'linuxcnc' hardware "
						   "module found in the project file. Only "
						   "one 'linuxcnc' module is supported.")
				linuxcncHwmodDesc = modDesc
		if not linuxcncHwmodDesc:
305 306 307 308 309 310 311
			if opt_inputBase is None and\
			   opt_outputBase is None and\
			   opt_inputSize is None and\
			   opt_outputSize is None:
				printWarning("Warning: Hardware module 'linuxcnc' not "
					     "included in project file. "
					     "Loading module nevertheless.")
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
			modDesc = HwmodDescriptor(moduleName = "linuxcnc",
						  parameters = {
				"hal"			: None,
				"removeOnReset"		: "0",
				"inputAddressBase"	: "0",
				"outputAddressBase"	: "0",
				"inputSize"		: "32",
				"outputSize"		: "32",
			})
			hwmodSettings.addLoadedModule(modDesc)
			linuxcncHwmodDesc = modDesc
		# Override hardware module parameters, if required.
		linuxcncHwmodDesc.setParameterValue("hal", hal)
		linuxcncHwmodDesc.setParameterValue("removeOnReset", "0")
		if opt_inputBase is not None:
			linuxcncHwmodDesc.setParameterValue("inputAddressBase",
							    str(opt_inputBase))
		if opt_inputSize is not None:
			linuxcncHwmodDesc.setParameterValue("inputSize",
							    str(opt_inputSize))
		if opt_outputBase is not None:
			linuxcncHwmodDesc.setParameterValue("outputAddressBase",
							    str(opt_outputBase))
		if opt_outputSize is not None:
			linuxcncHwmodDesc.setParameterValue("outputSize",
							    str(opt_outputSize))

		# Create the HAL pins, as requested.
		try:
			modDesc = linuxcncHwmodDesc
			inputBase = int(modDesc.getParameter("inputAddressBase"))
			inputSize = int(modDesc.getParameter("inputSize"))
			outputBase = int(modDesc.getParameter("outputAddressBase"))
			outputSize = int(modDesc.getParameter("outputSize"))
		except ValueError:
			printError("ERROR: 'linuxcnc' module hardware parameter "
				   "value error.")
			return 1
		createHalPins(hal = hal,
			      inputBase = inputBase,
			      inputSize = inputSize,
			      outputBase = outputBase,
			      outputSize = outputSize)
355

356 357
		# Configure the core and the core server.
		server = AwlSimServer()
358
		for modDesc in hwmodSettings.getLoadedModules():
359
			server.loadHardwareModule(modDesc)
360 361 362 363 364 365
		server.cpuEnableObTempPresets(project.getObTempPresetsEn())
		server.cpuEnableExtendedInsns(project.getExtInsnsEn() or\
					      opt_extInsns)
		#TODO set cycle time limit
		server.cpuSetRunTimeLimit(opt_maxRuntime)
		server.cpuSetSpecs(project.getCpuSpecs())
366

367
		# Load the program
368 369 370 371 372 373
		for symSrc in project.getSymTabSources():
			server.loadSymTabSource(symSrc)
		for libSel in project.getLibSelections():
			server.loadLibraryBlock(libSel)
		for awlSrc in project.getAwlSources():
			server.loadAwlSource(awlSrc)
374 375 376 377
		for fupSrc in project.getFupSources():
			server.loadFupSource(fupSrc)
		for kopSrc in project.getKopSources():
			server.loadKopSource(kopSrc)
378 379

		# Set the Linux-CNC watchdog as cycle exit hook.
380
		server.setCycleExitHook(watchdogHook)
381

382 383 384 385
		# Run the server
		printInfo("Starting interpreter core...")
		server.startup(host = opt_listen[0],
			       port = opt_listen[1],
386
			       handleExceptionServerside = True,
387 388
			       handleMaintenanceServerside = True)
		server.setRunState(server.STATE_RUN)
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
		lastExceptionTime = None
		while True:
			try:
				server.run()
			except (AwlParserError, AwlSimError) as e:
				now = time.time()
				if lastExceptionTime is not None and\
				   now - lastExceptionTime < 1.0:
					# The last fault is less than one second
					# in the past. Raise a fatal exception.
					printError("Fatal fault detected")
					raise e
				else:
					lastExceptionTime = now
					# Non-fatal fault.
					# Ensure the CPU is stopped and enter
					# the run loop again.
					printError(e.getReport())
					printError("CPU stopped due to fault")
					server.setRunState(server.STATE_STOP)
					continue
			# Run loop exited normally. Bail out.
			break
412
	except LinuxCNC_NotRunning as e:
Michael Büsch's avatar
Michael Büsch committed
413
		result = ExitCodes.EXIT_ERR_OTHER
414
	except KeyboardInterrupt as e:
Michael Büsch's avatar
Michael Büsch committed
415
		result = ExitCodes.EXIT_ERR_OTHER
416 417
	except (AwlParserError, AwlSimError) as e:
		printError(e.getReport())
Michael Büsch's avatar
Michael Büsch committed
418
		result = ExitCodes.EXIT_ERR_SIM
419 420
	except MaintenanceRequest as e:
		if e.requestType in (MaintenanceRequest.TYPE_SHUTDOWN,
421 422
				     MaintenanceRequest.TYPE_STOP,
				     MaintenanceRequest.TYPE_RTTIMEOUT):
Michael Büsch's avatar
Michael Büsch committed
423
			result = ExitCodes.EXIT_OK
424 425 426
		else:
			printError("Received invalid maintenance request %d" %\
				   e.requestType)
Michael Büsch's avatar
Michael Büsch committed
427
			result = ExitCodes.EXIT_ERR_SIM
428 429 430
	printInfo("LinuxCNC HAL module shutdown.")

	return result
431 432 433

if __name__ == "__main__":
	sys.exit(main())