Writing 0 value to DB

Here is the set up I have. I have a tag for currentShift, which changes between 1, 2 3 and back to 1. Starting at 7:00 AM, Below script run on the tag value change. When 1 becomes 2, I write the data to DB and reset the shift counts values to 0. The behavior I am seeing is, the OEE data written to DB is 0. Possibly the values were reset to 0 before the DB write is complete. is there a better way to handle this. Can a small delay be added to ensure the data is written to DB before resetting the values?


	if initialChange or currentValue.value == previousValue.value:
		return  # Skip on initial load or no actual change
		
	try:
		# Cache new shift start time first
		newStart = system.date.now()
		
		shiftNumber = previousValue.value  # Save the shift we are finishing

		tagPaths = [
			"[.]../../Performance/OEE/OEE",
			"[.]../../Performance/OEE/Availability",
			"[.]../../Performance/OEE/Performance",
			"[.]../../Performance/OEE/Quality",
		]

		# Read all values at once
		tagValues = system.tag.readBlocking(tagPaths)
		#params = [tv.value for tv in tagValues]
		params = [shiftNumber ] + [tv.value for tv in tagValues]
		# Build MS-SQL insert
		query = """
		INSERT INTO OEE_Data (
			shiftNumber, OEE, Availability, Performance, Quality
		) VALUES (?, ?, ?, ?, ?)
		"""

		# Execute insert
		system.db.runPrepUpdate(query, params, "OEE_Data")
		
		# Reset tags to "0" at the start of a new shift
		system.tag.writeBlocking([
		"[.]../../Current/ProductionData/ShiftCounts/shift1Count",
		"[.]../../Current/ProductionData/ShiftCounts/shift2Count",
		"[.]../../Current/ProductionData/ShiftCounts/shift3Count",
		"[.]../../Current/ProductionData/ShiftCounts/shiftCount",
		], [0]*4)
	except Exception as e:
		system.util.getLogger("OEE_Data").error("Failed to write shift data: " + str(e))

You aren't passing shiftNumber into that first query as a parameter, only params which contain the four values read from tags.

thats my bad, I updated the code, I had the shiftnumber, in the stripped down version I forgot to keep that.

This isn't happening with the script you've posted. The tag values you're reading are immutable; they're not live references back to the actual tag value. A QualifiedValue containing 1 from a tag read will continue to contain 1, even if you write to the tag again.

Log the values right before the query, to make sure they are what you think they are.
Once you confirm that the values inserted in the table are not the values you pass as parameters, we can start trying to figure out why.

3 Likes