Posted to tcl by Napier at Sun Jan 04 22:40:31 GMT 2015view pretty

	proc onData {sockID ip} {
	    if {[chan gets $sockID line] >= 0} {
			LOG "Received Data from $ip ($sockID)"
			LOG "$line"
			switch -regexp -- $line {
				"CONFIRMED" {
					# Logged In and Authorized
					if {[dict exists $::miDoor::Sockets $sockID]} {
						dict set ::miDoor::Devices $ip connecting 0
						UCL 1 "miDoor at $ip is Logged in and Ready for Commands"
					}
				}
				"STATUS 0:" {
					set r [string trim [string map {"STATUS 0:" ""} $line]]
					switch -regexp -- $r {
						"ERROR" {
							if {[lindex $r 1] == 1003} {
								# No More Log Entries are Available
								UCL 1 "Done Retrieving miDoor Event Logs"
							} else {
								UCL 1 "ERROR Detected: [lrange $r 2 end]"
							}	
						}
						"ACCEPTED" {
							UCL 1 "miDoor has Accepted the Command"
						}
					}
				}
				"STATE 0:" {
					# Response to a Query
					set r [string trim [string map {"STATE 0:" ""} $line]]
					set tempDict \
						[dict create \
							state [lindex $r 0] \
							lastChanged [lindex $r 2] \
							text [lindex $r 3] \
							temp [lindex $r 4] \
							alarm [lindex $r 5] \
							switch [lindex $r 7] \
							admin [lindex $r 8] \
							lastResponse [clock milliseconds] \
						]
					set currentState [dict get $tempDict state]
					if {[dict exists $::miDoor::Devices $ip status state]} {
						set oldState [dict get $::miDoor::Devices $ip status state]
					} else {
						set oldState -1
					}
					dict set ::miDoor::Devices "$ip" status $tempDict
					if {[dict exists $::miDoor::Names $ip]} {
						set name [dict get $::miDoor::Names $ip]
					} else {
						LOG "Name of Device Not Found, Registration Error?"
						return
					}
					if {$oldState == -1} {
						LOG "STATE CHANGE STATUS CURRENTLY UNKNOWN"
						::Access::Devices::Update -name "$name" -status [dict get $tempDict state]
						return
					}
					set deviceNumber [::Access::getDeviceNumberbyName $name]
					if {[dict exists $::Access::Devices::Listing $deviceNumber status]} {
						set shownState [dict get $::Access::Devices::Listing $deviceNumber status]
						if {$shownState != $currentState} {
							::Access::Devices::Update -name "$name" -status "$currentState"
							::DeviceEvents::Evaluate 1 -name "$name" -status "$currentState"
						}
					}

					# Evaluate Last Changed Device Event
					::DeviceEvents::Evaluate 3 -name "$name" -status "$currentState" -lastChanged "[dict get $tempDict lastChanged]" 

					# Shouldn't Need This:
					#if {$currentState != $oldState} {
					#	LOG "miDoor State Has Changed!"
					#	LOG "Sending Received miDoor State Response to URC Interfaces"
					#	LOG "$tempDict"
					#	::Access::Devices::Update -name "$name" -status [dict get $tempDict state]
					#}
				}
			}
	    }
	    if {[eof $sockID]} {
	        LOG "WARNING: miDoor Closed the Socket Connection"
			catch {chan close $sockID}
	    }
	}