diff --git a/aliasMapEnquiry.py b/aliasMapEnquiry.py index b286236..a254f8a 100755 --- a/aliasMapEnquiry.py +++ b/aliasMapEnquiry.py @@ -67,45 +67,40 @@ def main(): if options.veryverbose : connection.network.verbose = True - ''' - @todo identifynode option not currently implemented - ''' - #if options.identifynode : - # import getUnderTestAlias - # options.dest, otherNodeId = getUnderTestAlias.get(options.alias, - # None, - # options.verbose) - # if options.nodeid == None : - # options.nodeid = otherNodeId + if options.identifynode : + import getUnderTestAlias + options.dest, options.nodeid = getUnderTestAlias.get(options.alias, None, options.verbose or options.veryverbose) retval = test(options.alias, options.dest, options.nodeid, connection, options.verbose) connection.network.close() exit(retval) - + def test(alias, dest, nodeID, connection, verbose) : + retval = 0 + # check with node id in frame connection.network.send(makeframe(alias, nodeID)) expect = canolcbutils.makeframestring(0x10701000 + dest, nodeID) - if (connection.network.expect(exact=expect) == None) : - print "Expected reply when node ID matches not received" - return 2 + if (connection.network.expect(startswith=expect) == None) : + print ("Expected reply "+expect+" when node ID matches not received") + retval = retval | 1 - # check without node id in frame + # check without node id in frame connection.network.send(canolcbutils.makeframestring(0x10702000+alias,None)) expect = canolcbutils.makeframestring(0x10701000 + dest, nodeID) - if (connection.network.expect(exact=expect) == None) : - print "Expected reply when node ID matches not received" - return 2 + if (connection.network.expect(startswith=expect) == None) : + print ("Expected reply when node ID matches not received") + retval = retval | 2 # test non-matching NodeID using a reserved one connection.network.send(makeframe(alias, [0,0,0,0,0,1])) reply = connection.network.receive() - if (connection.network.expect(exact=expect) != None) : - print "Unexpected reply received when node ID didnt match ", reply - return 2 - - return 0 + if (connection.network.expect(startswith=expect) != None) : + print ("Unexpected reply received when node ID didnt match ", reply) + retval = retval | 4 + + return retval if __name__ == '__main__': main() diff --git a/allTest.py b/allTest.py index fc834dd..92806ea 100755 --- a/allTest.py +++ b/allTest.py @@ -8,24 +8,24 @@ import connection as connection import canolcbutils import defaults - + def usage() : - print "" - print "Called standalone, will sequence through a set of tests" - print "" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 123)" - print "-d --dest dest alias (default 123)" - print "-b number of datagram buffers to test (sends b+1 requests) default 1" - print "-c continue after error; (attempts to) run to completion even if error encountered" - print "-e --event eventID as 1.2.3.4.5.6.7.8 form" - print "-n --node dest nodeID (-t option sets automatically, format is 01.02.03.04.05.06)" - print "-r run until error; repeats until failure" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print ("") + print ("Called standalone, will sequence through a set of tests") + print ("") + print ("") + print ("Default connection detail taken from connection.py") + print ("") + print ("-a --alias source alias (default 123)") + print ("-d --dest dest alias (default 123)") + print ("-b number of datagram buffers to test (sends b+1 requests) default 1") + print ("-c continue after error; (attempts to) run to completion even if error encountered") + print ("-e --event eventID as 1.2.3.4.5.6.7.8 form") + print ("-n --node dest nodeID (-t option sets automatically, format is 01.02.03.04.05.06)") + print ("-r run until error; repeats until failure") + print ("-t find destination alias automatically") + print ("-v verbose") + print ("-V Very verbose") import getopt, sys @@ -40,12 +40,12 @@ def main(): complete = False repeat = False bufnum = 1 - + try: opts, remainder = getopt.getopt(sys.argv[1:], "e:n:b:a:d:vVtcr", ["event=", "alias=", "node=", "dest="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print (str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -75,16 +75,25 @@ def main(): # now execute retval = test(alias, dest, nodeID, event, connection, verbose, complete, repeat, identifynode, bufnum) - done(retval) + done(retval) def done(retval) : connection.network.close() exit(retval) - + +def purge() : + # wait two seconds, dropping all traffic + # used after errors to clear up any remnant traffic + import time + time.sleep(2) + while connection.network.receive() != None : + continue + return + def test(alias, dest, nodeID, event, connection, verbose, complete, repeat, identifynode, bufnum): result = 0; - + while True : if identifynode : @@ -92,177 +101,196 @@ def test(alias, dest, nodeID, event, connection, verbose, complete, repeat, iden dest, nodeID = getUnderTestAlias.get(alias, None, verbose) import aliasMapEnquiry - if verbose : print "aliasMapEnquiry" + if verbose : print ("aliasMapEnquiry") retval = aliasMapEnquiry.test(alias, dest, nodeID, connection, verbose) if retval != 0 : - print "Error in aliasMapEnquiry" + print ("Error in aliasMapEnquiry") if not complete : done(retval) + purge() result |= retval - + import verifyNodeGlobal - #if verbose : print "verifyNodeGlobal w no NodeID" + #if verbose : print ("verifyNodeGlobal w no NodeID") #retval = verifyNodeGlobal.test(alias, None, connection) #if retval != 0 : - # print "Error in verifyNodeGlobal w no NodeID" + # print ("Error in verifyNodeGlobal w no NodeID") # if not complete : done(retval) # result |= retval - if verbose : print "verifyNodeGlobal" + if verbose : print ("verifyNodeGlobal") retval = verifyNodeGlobal.test(alias, nodeID, connection) if retval != 0 : - print "Error in verifyNodeGlobal" + print ("Error in verifyNodeGlobal") if not complete : done(retval) + purge() result |= retval - + import verifyNodeAddressed - if verbose : print "verifyNodeAddressed" + if verbose : print ("verifyNodeAddressed") retval = verifyNodeAddressed.test(alias, dest, nodeID, connection, verbose) if retval != 0 : - print "Error in verifyNodeAddressed" + print ("Error in verifyNodeAddressed") if not complete : done(retval) + purge() result |= retval - + import protocolIdentProtocol - if verbose : print "protocolIdentProtocol" + if verbose : print ("protocolIdentProtocol") retval = protocolIdentProtocol.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in protocolIdentProtocol" + print ("Error in protocolIdentProtocol") if not complete : done(retval) + purge() result |= retval - + import identifyEventsGlobal - if verbose : print "identifyEventsGlobal" + if verbose : print ("identifyEventsGlobal") retval = identifyEventsGlobal.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in identifyEventsGlobal" + print ("Error in identifyEventsGlobal") if not complete : done(retval) + purge() result |= retval - + import identifyEventsAddressed - if verbose : print "identifyEventsAddressed" + if verbose : print ("identifyEventsAddressed") retval = identifyEventsAddressed.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in identifyEventsAddressed" + print ("Error in identifyEventsAddressed") if not complete : done(retval) + purge() result |= retval - + import identifyConsumers - if verbose : print "identifyConsumers" + if verbose : print ("identifyConsumers") retval = identifyConsumers.test(alias, event, connection, verbose) if retval != 0 : - print "Error in identifyConsumers" + print ("Error in identifyConsumers") if not complete : done(retval) + purge() result |= retval - + import identifyProducers - if verbose : print "identifyProducers" + if verbose : print ("identifyProducers") retval = identifyProducers.test(alias, event, connection, verbose) if retval != 0 : - print "Error in identifyProducers" + print ("Error in identifyProducers") if not complete : done(retval) + purge() result |= retval - + import testProducerConsumerNotification - if verbose : print "testProducerConsumerNotification" + if verbose : print ("testProducerConsumerNotification") retval = testProducerConsumerNotification.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in testProducerConsumerNotification" + print ("Error in testProducerConsumerNotification") if not complete : done(retval) + purge() result |= retval - + import testConfigurationProtocol - if verbose : print "testConfigurationProtocol" + if verbose : print ("testConfigurationProtocol") retval = testConfigurationProtocol.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in testConfigurationProtocol", retval + print ("Error in testConfigurationProtocol") if not complete : done(retval) + purge() result |= retval - + import testDatagram - if verbose : print "testDatagram" + if verbose : print ("testDatagram") retval = testDatagram.test(alias, dest, connection, bufnum, verbose) if retval != 0 : - print "Error in testDatagram", retval + print ("Error in testDatagram") if not complete : done(retval) + purge() result |= retval - + import testOverlappingDatagrams - if verbose : print "testOverlappingDatagrams" + if verbose : print ("testOverlappingDatagrams") retval = testOverlappingDatagrams.test(alias, dest, bufnum, connection, verbose) if retval != 0 : - print "Error in testOverlappingDatagrams", retval + print ("Error in testOverlappingDatagrams") if not complete : done(retval) + purge() result |= retval import simpleNodeIdentificationInformation - if verbose : print "simpleNodeIdentificationInformation" + if verbose : print ("simpleNodeIdentificationInformation") retval = simpleNodeIdentificationInformation.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in simpleNodeIdentificationInformation" + print ("Error in simpleNodeIdentificationInformation") if not complete : done(retval) + purge() result |= retval - + import testCDI - if verbose : print "testCDI" + if verbose : print ("testCDI") retval = testCDI.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in testCDI" + print ("Error in testCDI") if not complete : done(retval) + purge() result |= retval - + import testReservedBits - if verbose : print "testReservedBits" + if verbose : print ("testReservedBits") retval = testReservedBits.test(alias, nodeID, dest, connection, verbose) if retval != 0 : - print "Error in testReservedBits" + print ("Error in testReservedBits") if not complete : done(retval) - result |= retval - + purge() + result |= retval + import unknownDatagramType - if verbose : print "unknownDatagramType" + if verbose : print ("unknownDatagramType") retval = unknownDatagramType.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in unknownDatagramType" + print ("Error in unknownDatagramType") if not complete : done(retval) + purge() result |= retval - + import unknownMtiAddressed - if verbose : print "unknownMtiAddressed" + if verbose : print ("unknownMtiAddressed") retval = unknownMtiAddressed.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in unknownMtiAddressed" + print ("Error in unknownMtiAddressed") if not complete : done(retval) + purge() result |= retval - + import testStandardFrame import time - if verbose : print "testStandardFrame" + if verbose : print ("testStandardFrame") retval = testStandardFrame.test(connection, verbose) if retval != 0 : - print "Error in testStandardFrame" + print ("Error in testStandardFrame") if not complete : done(retval) + purge() result |= retval time.sleep(3) - + # done last, as changes alias in use import testAliasConflict - if verbose : print "testAliasConflict" + if verbose : print ("testAliasConflict") retval = testAliasConflict.test(alias, dest, connection, verbose) if retval != 0 : - print "Error in testAliasConflict" + print ("Error in testAliasConflict") if not complete : done(retval) + purge() result |= retval if not repeat : break - if verbose : print "End of pass, repeat" - if verbose : print "" - - if verbose : print "Note: Did not perform testStartup, which is manual" - if verbose : print "Note: Did not perform testForZeroAlias.py, which is slow" + if verbose : print ("End of pass, repeat") + if verbose : print ("") + + if verbose : print ("Note: Did not perform testStartup, which is manual") + if verbose : print ("Note: Did not perform testForZeroOrRepeatedAlias.py, which is slow") if verbose : - if result != 0 : print "Encountered errors" - else : print "Normal end" + if result != 0 : print ("Encountered errors") + else : print ("Normal end") - return + return result if __name__ == '__main__': main() diff --git a/canloader.py b/canloader.py index 1ad330f..65ad8e3 100644 --- a/canloader.py +++ b/canloader.py @@ -21,29 +21,29 @@ BOOTLOADER_VERSION = 0xA5 def selectNode(CRIS, NNB, connection, verbose) : - print "In selectNode" + print("In selectNode") frame = makeframestring(CRIS, CAN_SELECT_NODE, [NNB]) response = False resp_frame = '' counter = 100 while (not response) and counter: - print "sending CAN_SELECT_NODE" + print("sending CAN_SELECT_NODE") connection.network.send(frame) resp_frame = connection.network.receive() if (resp_frame != None) and isFrameType(resp_frame, CAN_SELECT_NODE, CRIS): - print "node selected!" + print("node selected!") response = True else: counter -= 1 if(counter == 0): return False #now examine the response more carefully data = bodyArray(resp_frame) - print "data contains ", - print data + print("data contains ", end=' ') + print(data) if(data[0] >= BOOTLOADER_VERSION) and (data[1] == 1): - print "selectNode success! Done" + print("selectNode success! Done") return True - print "selectNode fail!" + print("selectNode fail!") return False def expect(good, bad, connection, verbose) : @@ -83,10 +83,10 @@ def selectMemoryPage(page, CRIS, connection, verbose): return expect(expected_response, error_response, connection, verbose) def eraseMemory(CRIS, connection, verbose) : - print "eraseMemory" + print("eraseMemory") frame = makeframestring(CRIS, CAN_PROG_START, [0x80, 0xFF, 0xFF]) expected_response = makeframestring(CRIS, CAN_PROG_START, [0x00]) - print expected_response + print(expected_response) error_response = makeframestring(CRIS, CAN_ERROR, [0x00]) connection.network.send(frame) return expect(expected_response, error_response, connection, verbose) @@ -99,7 +99,7 @@ def startWrite(start, end, CRIS, connection, verbose) : return expect(expected_response, error_response, connection, verbose) def writeMemory(ih, zero_index, start, end, CRIS, connection, verbose) : - if verbose: print "WRITE" + if verbose: print("WRITE") if not startWrite(start, end, CRIS, connection, verbose) : return False address = start @@ -117,7 +117,7 @@ def writeMemory(ih, zero_index, start, end, CRIS, connection, verbose) : if(response != None) and isFrameType(response, CAN_PROG_DATA, CRIS): payload = bodyArray(response) if payload[0] != 0x00 and payload[0] != 0x02: - print "ERROR WRITING" + print("ERROR WRITING") return False else: done = True @@ -127,7 +127,7 @@ def writeMemory(ih, zero_index, start, end, CRIS, connection, verbose) : return True def verifyMemory(ih, CRIS, connection, verbose) : - if verbose: print "VERIFY" + if verbose: print("VERIFY") address = ih.minaddr() while(address < ih.maxaddr()): incr = min(8, (ih.maxaddr()+1) - address) @@ -140,7 +140,7 @@ def verifyMemory(ih, CRIS, connection, verbose) : payload = bodyArray(response) for i in range(len(payload)): if payload[i] != ih[address + i]: - print "ERROR IN VERIFY!" + print("ERROR IN VERIFY!") exit address += len(payload) done = True @@ -151,20 +151,20 @@ def startApplication(CRIS, connection, verbose) : connection.network.send(frame) def usage() : - print "" - print "TODO Called standalone, will send one CAN datagram message" - print " and display response." - print "" - print "Expect a single datagram reply in return" - print "e.g. [1Esssddd] 4C" - print "from destination alias to source alias" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-t find destination alias semi-automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("TODO Called standalone, will send one CAN datagram message") + print(" and display response.") + print("") + print("Expect a single datagram reply in return") + print("e.g. [1Esssddd] 4C") + print("from destination alias to source alias") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-t find destination alias semi-automatically") + print("-v verbose") + print("-V Very verbose") if __name__ == '__main__': @@ -177,9 +177,9 @@ def usage() : identifynode = False try: opts, remainder = getopt.getopt(sys.argv[1:], "f:d:vVt", ["dest=", "alias=", "content="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: diff --git a/canolcbutils.py b/canolcbutils.py index 31e7b53..8505f58 100755 --- a/canolcbutils.py +++ b/canolcbutils.py @@ -27,10 +27,10 @@ def makeframestring(header, body) : def splitSequence(seq) : strings = seq.split('.') result = [] - for a in strings : + for a in strings : result = result+[int(a, 16)] return result - + ''' Pull body bytes from frame as array ''' @@ -41,7 +41,7 @@ def bodyArray(frame) : result = result+[int(string[:2],16)] string = string[2:] return result - + ''' Return (header, body) of a P/C Event Report frame alias: the source alias of this node @@ -53,11 +53,10 @@ def eventframe(alias, event) : def main(): (header, body) = eventframe(0x123, [11,255,240,4,5,6,7,8]); - print makeframestring(header, body) - print splitSequence("1.2.3.a.0a.10.4") - print bodyArray(":X1E000000F010203040506;") - + print (makeframestring(header, body)) + print (splitSequence("1.2.3.a.0a.10.4")) + print (bodyArray(":X1E000000F010203040506;")) + if __name__ == '__main__': main() - \ No newline at end of file diff --git a/connection.py b/connection.py index 61b26bd..4bcbfed 100755 --- a/connection.py +++ b/connection.py @@ -12,35 +12,35 @@ network = defaults.network -thisNodeID = defaults.thisNodeID +thisNodeID = defaults.thisNodeID thisNodeAlias = defaults.thisNodeAlias -testNodeID = defaults.testNodeID +testNodeID = defaults.testNodeID testNodeAlias = defaults.testNodeAlias def main(): usage() - + return # done with example - + def list() : - print "network.host = "+network.host - print "network.port = "+str(network.port) - print "thisNodeID = ",thisNodeID - print "thisNodeAlias = "+hex(thisNodeAlias) - print "testNodeID = ",testNodeID - print "testNodeAlias = "+hex(testNodeAlias) + print ("network.host = "+network.host) + print ("network.port = "+str(network.port)) + print ("thisNodeID = ",thisNodeID) + print ("thisNodeAlias = "+hex(thisNodeAlias)) + print ("testNodeID = ",testNodeID) + print ("testNodeAlias = "+hex(testNodeAlias)) return def usage() : - print "" - print "Python module for defining the layout connection." - print "" - print "Invoked by other routines to know how to send, " - print "not intended to be invoked standalone" - print "" + print ("") + print ("Python module for defining the layout connection.") + print ("") + print ("Invoked by other routines to know how to send, ") + print ("not intended to be invoked standalone") + print ("") list() return - + if __name__ == '__main__': main() diff --git a/datagram.py b/datagram.py index 9b420bf..3fd28ba 100755 --- a/datagram.py +++ b/datagram.py @@ -50,16 +50,16 @@ def sendOneDatagram(alias, dest, content, connection, verbose) : frame = connection.network.receive() if frame == None : - print "Did not receive reply" + print("Did not receive reply") return 1 if not isOkReply(frame) : - print "Unexpected message received instead of Datagram Received OK" + print("Unexpected message received instead of Datagram Received OK") return 2 if not int(frame[12:15],16) == alias: - print "Improper dest alias in reply", frame + print("Improper dest alias in reply", frame) return 3 if not int(frame[7:10],16) == dest: - print "Improper source alias in reply", frame + print("Improper source alias in reply", frame) return 3 return 0 @@ -68,7 +68,7 @@ def receiveOneDatagram(alias, dest, conection, verbose) : while True : reply = connection.network.receive() if (reply == None ) : - print "No datagram segment received" + print("No datagram segment received") return 4 elif reply.startswith(":X1B") or reply.startswith(":X1C") : retval = retval + canolcbutils.bodyArray(reply) @@ -78,7 +78,7 @@ def receiveOneDatagram(alias, dest, conection, verbose) : connection.network.send(makereply(alias, dest)) return retval else : - print "Unexpected message instead of datagram segment", reply + print("Unexpected message instead of datagram segment", reply) return 3 def sendOneDatagramNoWait(alias, dest, content, connection, verbose) : @@ -108,7 +108,7 @@ def receiveDatagramReplyAndOneDatagram(alias, dest, conection, verbose) : while True : reply = connection.network.receive() if (reply == None ) : - print "Missing response" + print("Missing response") return 4 elif isOkReply(reply) : haveReply = True @@ -124,29 +124,29 @@ def receiveDatagramReplyAndOneDatagram(alias, dest, conection, verbose) : if haveReply : return retval else : - print "Unexpected message", reply + print("Unexpected message", reply) return 3 def usage() : - print "" - print "Called standalone, will send one CAN datagram message" - print " and display response." - print "" - print "Expect a single datagram reply in return" - print "e.g. [1Esssddd] 4C" - print "from destination alias to source alias" - print "" - print "Default connection detail taken from connection.py" - print "" - print "See also testDatagram.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-c --content message content (default 1.2.3.4)" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Called standalone, will send one CAN datagram message") + print(" and display response.") + print("") + print("Expect a single datagram reply in return") + print("e.g. [1Esssddd] 4C") + print("from destination alias to source alias") + print("") + print("Default connection detail taken from connection.py") + print("") + print("See also testDatagram.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-c --content message content (default 1.2.3.4)") + print("-t find destination alias automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -160,9 +160,9 @@ def main(): try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:c:vVt", ["dest=", "alias=", "content="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: diff --git a/defaults.py b/defaults.py index 7055573..5f0aa9d 100755 --- a/defaults.py +++ b/defaults.py @@ -1,51 +1,57 @@ -serial = False -tcp = True -ethernet = False +# select the connection type (only one) +serial = True windows = False +serialPort = "/dev/cu.usbmodemCC570001B1" + +tcp = False +ethernet = False +networkHost = "192.168.16.212" + local = False +# thisNode is the node doing the testing +thisNodeID = [1,2,3,4,5,6] +thisNodeAlias = 0xAAA -if tcp and not local: +# testNode is the node under test +# usually the -t option is used to gather this info from the single attached node +testNodeID = [2,3,4,5,6,1] +testNodeAlias = 0xDDD +# an event produced and consumed by the device under test or None +testEventID = [0x05, 0x02, 0x01, 0x02, 0x02, 0x00, 0x00, 0x00] + + +if tcp : import tcpolcblink network = tcpolcblink.TcpToOlcbLink() - network.host = "174.18.137.234" - network.host = "localhost" - #network.host = "propername.local." + network.host = networkHost network.port = 12021 -elif ethernet and not local: +elif ethernet : import ethernetolcblink network = ethernetolcblink.EthernetToOlcbLink() - network.host = "174.18.137.234" - #network.host = "propername.local." + network.host = networkHost network.port = 12021 -elif windows and not local : +elif windows : import serialolcblink network = serialolcblink.SerialOlcbLink() - network.port = "COM9" + network.port = serialPort network.speed = 500000 network.startdelay = 0 -elif serial and not local : +elif serial : import serialolcblink network = serialolcblink.SerialOlcbLink() - #network.port = "/dev/cu.usbserial-A900fLVC" - #network.port = "/dev/cu.usbmodem401331" - #network.port = "/dev/cu.usbserial-AE015IZE" # Ioduino - network.port = "/dev/cu.usbserial-A5VRG6OF" # TCH parallel - network.speed = 230400 - network.parallel = True - network.startdelay = 2 + network.port = serialPort + network.speed = 57600 #115200 #230400 + network.parallel = False + network.startdelay = 1 # time to wait at start for adapter to come up, in seconds elif local : import pipeolcblink network = pipeolcblink.PipeOlcbLink() network.name = "pyOlcbBasicNode" else : - print "Please set one of the options to True" + print ("Please set one of the options to True") -thisNodeID = [1,2,3,4,5,6] -thisNodeAlias = 0xAAA testNodeID = [2,3,4,5,6,1] testNodeAlias = 0xDDD - - testEventID = [0x05, 0x02, 0x01, 0x02, 0x02, 0x00, 0x00, 0x00] diff --git a/ethernetolcblink.py b/ethernetolcblink.py index a14c482..cdd2759 100755 --- a/ethernetolcblink.py +++ b/ethernetolcblink.py @@ -15,7 +15,7 @@ def __init__(self) : # prepare, but don't open self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #self.socket.timeout(10) - + # defaults (generally overridden by system-wide defaults elsewhere) self.host = "10.00.01.98" # Arduino adapter default self.port = 23 @@ -25,51 +25,100 @@ def __init__(self) : self.socket = None self.rcvData = "" return - + def connect(self) : # if verbose, print - if (self.verbose) : print " connect to ",self.host,":",self.port - + if (self.verbose) : print (" connect to ",self.host,":",self.port) + self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.host, self.port)) - + # wait for link startup # after (possible) reset due to serial startup if self.startdelay > 0 : - if self.verbose : print " waiting", self.startdelay, "seconds for adapter restart" + if self.verbose : print (" waiting", self.startdelay, "seconds for adapter restart") time.sleep(self.startdelay) return - + def send(self, frame) : if (self.socket == None) : self.connect() - + # if verbose, print - if (self.verbose) : print " send ",frame - + if (self.verbose) : print (" send ",frame) + # send - self.socket.send(frame+'\n') - + self.socket.send((frame+'\n').encode()) + return - + def receive(self) : # returns frame if (self.socket == None) : self.connect() - - # if verbose, print - if (self.verbose) : print " receive ", - + self.socket.settimeout(self.timeout) while (self.rcvData.find('\n') < 0) : try: - self.rcvData = self.rcvData+self.socket.recv(1024) - except socket.timeout, err: - if (self.verbose) : print "" # blank line to show delay? + self.rcvData = self.rcvData+self.socket.recv(1024).decode('UTF8') + except socket.timeout as err: + if (self.verbose) : print (" receive ") # blank line to show delay? return None r = self.rcvData[0:self.rcvData.find('\n')] self.rcvData = self.rcvData[self.rcvData.find('\n')+1:] - if (self.verbose) : print r + if (self.verbose) : print (" receive "+r) return r + ''' + Continue receiving data until the we get the expected result or timeout. + @param exact if != None, look for result with exact string + @param startswith if != None, look for result starting with string + @param data if != None, tuple of data bytes to match + @param timeout timeout in seconds, if timeout != 0, return None on timeout + @return resulting message on success, None on timeout + ''' + def expect(self, exact=None, startswith=None, data=None, timeout=1) : + start = time.time() + while (True) : # loop to find, timeout or fali + result = self.receive() + + if (result == None) : + if (timeout != 0) : + if (time.time() > (start + timeout)) : + if (self.verbose) : + print ("Timeout") + return None + else : + continue + else : return None + + # here, result was not None - do sequential checks + if (exact == None and startswith == None and data == None) : + return result # no test, just get the data + + if (data != None) : + if (len(data) == ((len(result) - 12) / 2)) : + i = 0 + j = 11 + while (data[i] == int('0x' + result[j] + result[j + 1], 16)) : + i = i + 1 + j = j + 2 + if (i != len(data)) : + return None + + if (exact != None) : + print ("exact may not be working right?") + print (result) + print (exact) + print (result == exact) + if (result != exact) : + return None + + if (startswith != None) : + if (not result.startswith(startswith)) : + return None + + # here, we passed all the available tests! + return result + def close(self) : return @@ -78,54 +127,60 @@ def close(self) : def main(): global frame - + # create connection object network = EthernetToOlcbLink() # get defaults - host = network.host + host = network.host port = network.port verbose = network.verbose - - frame = ':X182DF123N0203040506080001;' + + frame = ':X19490001N;' # process arguments (host, port, frame, verbose) = args(host, port, frame, verbose) - + # load new defaults network.host = host network.port = port network.verbose = verbose - + # send the frame network.send(frame) - - return # done with example + + # then wait for and display responses until interrupted or nothing received + while True : + reply = network.receive() + if reply == None : break + print (reply) + return + def usage() : - print "" - print "Python module for connecting to an OpenLCB via an Ethernet connection." - print "Called standalone, will send one CAN frame." - print "" - print "valid options:" - print " -v for verbose; also displays any responses" - print " -h, --host for host name or IP address" - print " -p, --port for port number" - print "" - print "valid usages (default values):" - print " ./ethernetolcblink.py --host=10.00.01.98" - print " ./ethernetolcblink.py --host=10.00.01.98 --port=23" - print " ./ethernetolcblink.py --host=10.00.01.98 --port=23 :X182DF123N0203040506080001\;" - print "" - print "Note: Most shells require escaping the semicolon at the end of the frame." - + print ("") + print ("Python module for connecting to an OpenLCB via an Ethernet connection.") + print ("Called standalone, will send one CAN frame.") + print ("") + print ("valid options:") + print (" -v for verbose; also displays any responses") + print (" -h, --host for host name or IP address") + print (" -p, --port for port number") + print ("") + print ("valid usages (default values):") + print (" ./ethernetolcblink.py --host=10.00.01.98") + print (" ./ethernetolcblink.py --host=10.00.01.98 --port=12021") + print (" ./ethernetolcblink.py --host=10.00.01.98 --port=12021 :X19490001N\;") + print ("") + print ("Note: Most shells require escaping the semicolon at the end of the frame.") + def args(host, port, frame, verbose) : # argument processing try: opts, remainder = getopt.getopt(sys.argv[1:], "h:p:v", ["host=", "port="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print (str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -137,10 +192,9 @@ def args(host, port, frame, verbose) : port = int(arg) else: assert False, "unhandled option" - if (len(remainder) > 0) : + if (len(remainder) > 0) : frame = remainder[0] return (host, port, frame, verbose) - + if __name__ == '__main__': main() - \ No newline at end of file diff --git a/getUnderTestAlias.py b/getUnderTestAlias.py index af259db..0a54825 100755 --- a/getUnderTestAlias.py +++ b/getUnderTestAlias.py @@ -17,26 +17,31 @@ ''' def get(alias, nodeID, verbose) : + if verbose : print (" get alias of node under test") connection.network.send(verifyNodeGlobal.makeframe(alias, nodeID)) - while (True) : + loop = 1 + while (loop < 20) : + loop = loop+1 reply = connection.network.receive() - if (reply == None ) : return None,None + if (reply == None ) : continue if (reply.startswith(":X19170")) : alias,nodeID = int(reply[7:10],16),canolcbutils.bodyArray(reply) - if verbose : print "Found alias "+str(alias)+" ("+hex(alias)+") for node ID ",nodeID + if verbose : print (" Found alias "+str(alias)+" ("+hex(alias)+") for node ID "+str(nodeID)) return alias,nodeID - + print ("Could not obtain alias, no reply from unit under test") + exit(1) + def usage() : - print "" - print " Assumoing one under-test node present, uses " - print " one CAN VerifyNode (Global) message" - print " to get that node's alias " - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 123)" - print "-n --node dest nodeID (default None)" - print "-v verbose" + print ("") + print (" Assumoing one under-test node present, uses ") + print (" one CAN VerifyNode (Global) message") + print (" to get that node's alias ") + print ("") + print ("Default connection detail taken from connection.py") + print ("") + print ("-a --alias source alias (default 123)") + print ("-n --node dest nodeID (default None)") + print ("-v verbose") import getopt, sys @@ -47,9 +52,9 @@ def main(): verbose = False try: opts, remainder = getopt.getopt(sys.argv[1:], "h:p:n:a:vV", ["alias=", "node=", "host=", "port="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print (str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: diff --git a/identifyConsumers.py b/identifyConsumers.py index b261bc5..243acfb 100755 --- a/identifyConsumers.py +++ b/identifyConsumers.py @@ -13,20 +13,20 @@ def makeframe(alias, eventID) : return canolcbutils.makeframestring(0x198F4000+alias,eventID) def usage() : - print "" - print "Called standalone, will send one CAN IdentifyConsumers message" - print " and display response" - print "" - print "Expect zero or more ConsumerIdentified reply in return" - print "e.g. [194C4sss] nn nn nn nn nn nn" - print "containing dest alias and EventID" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-e --event eventID as 1.2.3.4.5.6.7.8 form" - print "-v verbose" - print "-V Very verbose" + print("") + print("Called standalone, will send one CAN IdentifyConsumers message") + print(" and display response") + print("") + print("Expect zero or more ConsumerIdentified reply in return") + print("e.g. [194C4sss] nn nn nn nn nn nn") + print("containing dest alias and EventID") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-e --event eventID as 1.2.3.4.5.6.7.8 form") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -38,9 +38,9 @@ def main(): # argument processing try: opts, remainder = getopt.getopt(sys.argv[1:], "e:a:vV", ["alias=", "event="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -67,7 +67,7 @@ def test(alias,event,connection,verbose) : while (True) : if (connection.network.receive() == None ) : break count = count + 1 - if verbose : print " Found",count,"nodes" + if verbose : print(" Found",count,"nodes") return 0 if __name__ == '__main__': diff --git a/identifyEventsAddressed.py b/identifyEventsAddressed.py index abf7f9d..b7ba28e 100755 --- a/identifyEventsAddressed.py +++ b/identifyEventsAddressed.py @@ -12,23 +12,23 @@ def makeframe(alias, dest) : body = [(dest>>8)&0xFF, dest&0xFF] return canolcbutils.makeframestring(0x19968000+alias,body) - + def usage() : - print "" - print "Called standalone, will send one CAN IdentifyEvents message" - print " and display response" - print "" - print "Expect zero or more ConsumerIdentified reply in return" - print "e.g. [1926Bsss] nn nn nn nn nn nn" - print "containing dest alias and EventID" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-t find destination alias automatically" - print "-v verbose" - print "-V very verbose" + print("") + print("Called standalone, will send one CAN IdentifyEvents message") + print(" and display response") + print("") + print("Expect zero or more ConsumerIdentified reply in return") + print("e.g. [1926Bsss] nn nn nn nn nn nn") + print("containing dest alias and EventID") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-t find destination alias automatically") + print("-v verbose") + print("-V very verbose") from optparse import OptionParser @@ -85,8 +85,8 @@ def main(): retval = test(options.alias, options.dest, connection, options.verbose) connection.network.close() exit(retval) - -def test(alias, dest, connection, verbose) : + +def test(alias, dest, connection, verbose) : connection.network.send(makeframe(alias,dest)) producerCount = 0 consumerCount = 0 @@ -109,8 +109,8 @@ def test(alias, dest, connection, verbose) : if (reply.startswith(':X19524')) : producerRange.append(int(reply[11:27],16)) if (verbose) : - print " Found", consumerCount,"consumer events" - print " Found", producerCount,"producer events" + print(" Found", consumerCount,"consumer events") + print(" Found", producerCount,"producer events") for a in consumerRange : i = 4 if ((a % 2) == 0) : @@ -120,14 +120,14 @@ def test(alias, dest, connection, verbose) : i = i * 2 else : while (True) : - if ((a % i) == 0) : + if ((a % i) != i-1) : break; i = i * 2 - mask = (i / 2) - 1 + mask = int(i / 2) - 1 base = a & ~mask - print " Found consumer range", \ + print(" Found consumer range", \ '{0:8x}'.format(base), "-", \ - '{0:8x}'.format(base + mask) + '{0:8x}'.format(base + mask)) for a in producerRange : i = 4 if ((a % 2) == 0) : @@ -137,14 +137,14 @@ def test(alias, dest, connection, verbose) : i = i * 2 else : while (True) : - if ((a % i) == 0) : + if ((a % i) != i-1) : break; i = i * 2 - mask = (i / 2) - 1 + mask = int(i / 2) - 1 base = a & ~mask - print " Found producer range", \ + print(" Found producer range", \ '{0:8x}'.format(base), "-", \ - '{0:8x}'.format(base + mask) + '{0:8x}'.format(base + mask)) return 0 diff --git a/identifyEventsGlobal.py b/identifyEventsGlobal.py index d641e35..6961da1 100755 --- a/identifyEventsGlobal.py +++ b/identifyEventsGlobal.py @@ -11,7 +11,7 @@ def makeframe(alias) : return canolcbutils.makeframestring(0x19970000+alias, None) - + from optparse import OptionParser ''' @@ -58,7 +58,7 @@ def main(): connection.network.close() exit(retval) -def test(alias, dest, connection, verbose) : +def test(alias, dest, connection, verbose) : # now execute connection.network.send(makeframe(alias)) producerCount = 0 @@ -82,8 +82,8 @@ def test(alias, dest, connection, verbose) : if (reply.startswith(':X19524')) : producerRange.append(int(reply[11:27],16)) if (verbose) : - print " Found", consumerCount,"consumer events" - print " Found", producerCount,"producer events" + print(" Found", consumerCount,"consumer events") + print(" Found", producerCount,"producer events") for a in consumerRange : i = 4 if ((a % 2) == 0) : @@ -93,14 +93,14 @@ def test(alias, dest, connection, verbose) : i = i * 2 else : while (True) : - if ((a % i) == 0) : + if ((a % i) != i-1) : break; i = i * 2 - mask = (i / 2) - 1 + mask = int(i / 2) - 1 base = a & ~mask - print " Found consumer range", \ + print(" Found consumer range", \ '{0:8x}'.format(base), "-", \ - '{0:8x}'.format(base + mask) + '{0:8x}'.format(base + mask)) for a in producerRange : i = 4 if ((a % 2) == 0) : @@ -110,14 +110,14 @@ def test(alias, dest, connection, verbose) : i = i * 2 else : while (True) : - if ((a % i) == 0) : + if ((a % i) != i-1) : break; i = i * 2 - mask = (i / 2) - 1 + mask = int(i / 2) - 1 base = a & ~mask - print " Found producer range", \ + print(" Found producer range", \ '{0:8x}'.format(base), "-", \ - '{0:8x}'.format(base + mask) + '{0:8x}'.format(base + mask)) return 0 diff --git a/identifyProducers.py b/identifyProducers.py index a4786c0..fae7f10 100755 --- a/identifyProducers.py +++ b/identifyProducers.py @@ -13,20 +13,20 @@ def makeframe(alias, eventID) : return canolcbutils.makeframestring(0x19914000+alias,eventID) def usage() : - print "" - print "Called standalone, will send one CAN IdentifyProducer message" - print " and display response" - print "" - print "Expect zero or more ProducerIdentified reply in return" - print "e.g. [19544sss] nn nn nn nn nn nn" - print "containing dest alias and EventID" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-e --event eventID as 1.2.3.4.5.6.7.8 form" - print "-v verbose" - print "-V Very verbose" + print("") + print("Called standalone, will send one CAN IdentifyProducer message") + print(" and display response") + print("") + print("Expect zero or more ProducerIdentified reply in return") + print("e.g. [19544sss] nn nn nn nn nn nn") + print("containing dest alias and EventID") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-e --event eventID as 1.2.3.4.5.6.7.8 form") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -38,9 +38,9 @@ def main(): # argument processing try: opts, remainder = getopt.getopt(sys.argv[1:], "e:a:vVt", ["alias=", "event="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -67,7 +67,7 @@ def test(alias,event,connection,verbose) : while (True) : if (connection.network.receive() == None ) : break count = count + 1 - if verbose : print " Found",count,"nodes" + if verbose : print(" Found",count,"nodes") return 0 if __name__ == '__main__': diff --git a/index.html b/index.html index a15258f..58171db 100644 --- a/index.html +++ b/index.html @@ -15,25 +15,25 @@ -

OpenLCB +

OpenLCB Python Prototype

This is the index page of the OpenLCBâ„¢ Python prototypes directory.

Most of the Python modules in this package are meant to be run -from the command line, or invoked programmatically. +from the command line, or invoked programmatically.

To run one from the Mac OS X or Linux command line, first edit the defaults.py file with your connection -information, then do e.g.: +information, then do e.g.:

./verifyNodeGlobal.py -v

To run the full set of tests from the Mac OS X or Linux command line, -do : +do :

./allTest.py -t -v && echo OK

-followed by testing the start-up sequencing with : +followed by testing the start-up sequencing with :

-
./testStartup.py -t -v && echo OK

+

./testStartup.py && echo OK

(Reset the node when prompted to force the start-up sequence to run)

When running from the command line, internal help is available via the -h option, as in:

@@ -53,99 +53,101 @@

There are text files containing typical -output from running +output from running

./allTest.py -t -V

-and +and

./testStartup.py -t -V

test scripts that you can consult to see what normal operation looks like. Note that they contain node IDs, aliases, and event IDs that -are specific to the particular node being tested, so your mileage -

-
    -

    will

    -
-

vary. +are specific to the particular node being tested, so your mileage +will vary.

The type of access (Ethernet or USB) and parameters such as IP address, default node IDs, etc are defined in the default.py file. When using the command line, edit that file for your specific needs. If you're using a serial connection, you -need to have PySerial installed, which is +need to have PySerial installed, which is described here.

Utilities and Modules

The basic Ethernet connection is accessed via the -"ethernetolcblink" module. +"ethernetolcblink" module.

    import ethernetolcblink

The basic USB-Serial connection is accessed via the "serialolcblink" -module. +module.

    import serialolcblink

Other cross-connection utilities can found in the "canolcbutils" -module. +module.

Frame and Message Tools

verifyNodeGlobal
Send a "Verify Node Global" message, getting a reply from - each connected node. + each connected node.
verifyNodeAddressed
Send a "Verify Node Addressed" message, getting a reply - from the addressed node. + from the addressed node.
identifyConsumers
Send an "Identify Consumers" message, which will generate - a reply from any node using consuming the Event ID + a reply from any node using consuming the Event ID
identifyProducers
Send a "Identify Producers" message, which will generate a - reply from any node using consuming the Event ID. + reply from any node using consuming the Event ID.
identifyEventsGlobal
Send a "Identify Events Global" message, getting a reply - from each connected node. + from each connected node.
identifyEventsAddressed
- Send a "Verify Node Global" message. + Send a "Verify Node Global" message.
datagram
- Send a "datagram" message. + Send a "datagram" message.

Tests

+ +You can learn about use of these will the -h option, which is generally available. +
allTest
- Runs the complete set of tests in sequence + Runs the complete set of tests in sequence. The -t + option will acquire the alias and node ID from the device under test. + The -c option will continue running after a failure so that you + get the results of the entire series of tests.
testProducerConsumerNotification
Uses IdentifyEvents to learn which events a node produces and consumes, then checks that IdentifyConsumers and IdentifyProducers - will find them. + will find them.
testConfigurationProtocol
- Does a sequence of tests of the configuration protocol + Does a sequence of tests of the configuration protocol
- testConfigurationProtocol
- Does a sequence of tests of the configuration protocol -

Tools

monitor
- Monitors received frames until cancelled + Monitors received frames until cancelled
readConfiguration
- Reads from a node via the configuration protocol + Reads from a node via the configuration protocol +
+ serialolcblink
+ Allows you to send specific CAN frames via a serial USB adapter
ethernetolcblink
- Allows you to send specific CAN frames via an Ethernet adapter + Allows you to send specific CAN frames via an Ethernet link
getUnderTestAlias
Assumes there is only one node attached, and finds the alias for - addressing it. + addressing it.



@@ -156,4 +158,4 @@

page.

This is SVN $Revision$ of 08/16/09.

- \ No newline at end of file + diff --git a/monitor.py b/monitor.py index d698f3d..ebe23f4 100755 --- a/monitor.py +++ b/monitor.py @@ -11,7 +11,7 @@ def main(): while (True) : frame = connection.network.receive() - if (frame != None ) : print frame, + if (frame != None ) : print (frame), return if __name__ == '__main__': diff --git a/pipeolcblink.py b/pipeolcblink.py index e80085b..6b7a4db 100755 --- a/pipeolcblink.py +++ b/pipeolcblink.py @@ -2,20 +2,14 @@ ''' Drive an OpenLCB via pipes to an executable -argparse is new in Jython 2.7, so dont use here - @author: Bob Jacobsen ''' import subprocess -# stdout,stderr = p.communicate("send stuff input\n more studd") -# print "O",stdout -# print "E",stderr - class PipeOlcbLink : def __init__(self) : - + # Defaults (generally overridden by system-wide defaults elsewhere) # To use these: # cd ../C (e.g. to prototypes/C) @@ -27,13 +21,13 @@ def __init__(self) : self.verbose = False self.process = None return - + def connect(self) : # if verbose, print - if (self.verbose) : print " starting ",self.name," from ",self.location - + if (self.verbose) : print(" starting ",self.name," from ",self.location) + executable = self.location+self.name - self.process = subprocess.Popen(executable,1,None,subprocess.PIPE,subprocess.PIPE, + self.process = subprocess.Popen(executable,1,None,subprocess.PIPE,subprocess.PIPE, sys.stderr, None, False, True) self.seenEnd = False @@ -51,15 +45,15 @@ def connect(self) : self.process.stdin.write('T\n') self.flush() return - + def send(self, frame) : - if self.process == None : + if self.process == None : self.connect() elif not self.seenEnd : self.flush() - + # if verbose, print - if self.verbose : print " send ",frame + if self.verbose : print(" send ",frame) # send self.seenEnd = False @@ -67,13 +61,10 @@ def send(self, frame) : self.process.stdin.flush() return - + def receive(self) : # returns frame if (self.process == None) : self.connect() - - # if verbose, print - if (self.verbose) : print " receive ", - + r = self.process.stdout.readline() # timeout returns empty line @@ -84,16 +75,16 @@ def receive(self) : # returns frame self.process.stdin.write('T\n') self.process.stdin.flush() r = self.process.stdout.readline() - + if not r.startswith(":") : - if (self.verbose) : print "" # blank line to show delay? + if (self.verbose) : print(" receive ") # blank line to show delay? self.seenEnd = True return None - # if verbose, display what's received - if (self.verbose) : print r, - - return r + # if verbose, display what's received + if (self.verbose) : print(" receive "+str(r)) + + return r def close(self) : self.process.kill() @@ -106,7 +97,7 @@ def flush(self) : # reads past any pending input if not r.startswith(":") : self.seenEnd = True break - if self.verbose : print " drop ",r, + if self.verbose : print(" drop ",r, end=' ') return def more(self) : # checks whether any more input in response to most recent stimulus @@ -116,54 +107,54 @@ def more(self) : # checks whether any more input in response to most recent stim def main(): global frame - + # create connection object network = PipeOlcbLink() # get defaults - location = network.location + location = network.location name = network.name verbose = network.verbose - + frame = ':X180A7000N;' # process arguments (location, name, frame, verbose) = args(location, name, frame, verbose) - + # load new defaults network.location = location network.name = name network.verbose = verbose - + # send the frame network.send(frame) while True : network.receive() - + return # done with example def usage(location, name) : - print "" - print "Python module for connecting to an OpenLCB via an Ethernet connection." - print "Called standalone, will send one CAN frame." - print "" - print "valid options:" - print " -v for verbose; also displays any responses" - print " -n, --name executable name, e.g. "+location - print " -l, --location directory to look for file, e.g. "+name - print "" - print "example:" - print " python pipeolcblink.py :X180A7000N;\;" - print "" - print "Note: Most shells require escaping the semicolon at the end of the frame." - + print("") + print("Python module for connecting to an OpenLCB via an Ethernet connection.") + print("Called standalone, will send one CAN frame.") + print("") + print("valid options:") + print(" -v for verbose; also displays any responses") + print(" -n, --name executable name, e.g. "+location) + print(" -l, --location directory to look for file, e.g. "+name) + print("") + print("example:") + print(" python pipeolcblink.py :X180A7000N;\;") + print("") + print("Note: Most shells require escaping the semicolon at the end of the frame.") + def args(location, name, frame, verbose) : # argument processing try: opts, remainder = getopt.getopt(sys.argv[1:], "n:l:vV", ["name=", "location="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage(location, name) sys.exit(2) for opt, arg in opts: @@ -177,11 +168,11 @@ def args(location, name, frame, verbose) : name = arg else: assert False, "unhandled option" - - if (len(remainder) > 0) : + + if (len(remainder) > 0) : frame = remainder[0] return (location, name, frame, verbose) - + if __name__ == '__main__': main() - + diff --git a/protocolIdentProtocol.py b/protocolIdentProtocol.py index 3f58000..d8798c3 100755 --- a/protocolIdentProtocol.py +++ b/protocolIdentProtocol.py @@ -12,10 +12,12 @@ def makeframe(alias, dest) : body = [(dest>>8)&0xFF, dest&0xFF] return canolcbutils.makeframestring(0x19828000+alias,body) - + from optparse import OptionParser def main(): + nodeID = connection.testNodeID + # argument processing usage = "usage: %prog [options]\n\n" + \ "Called standalone, will send one CAN " + \ @@ -46,23 +48,20 @@ def main(): action="store_true", dest="veryverbose", default=False, help="print very verbose debug information") - + (options, args) = parser.parse_args() if options.veryverbose : connection.network.verbose = True - ''' - @todo identifynode option not currently implemented - ''' - #if identifynode : - # import getUnderTestAlias - # dest, otherNodeId = getUnderTestAlias.get(alias, None, verbose) + if options.identifynode : + import getUnderTestAlias + options.dest, nodeID = getUnderTestAlias.get(options.alias, None, options.verbose or options.veryverbose) retval = test(options.alias, options.dest, connection, options.verbose) connection.network.close() exit(retval) - + def test(alias, dest, connection, verbose) : connection.network.send(makeframe(alias, dest)) body = [(alias>>8)&0xFF, alias&0xFF] @@ -70,41 +69,41 @@ def test(alias, dest, connection, verbose) : expect = expect[:-1] reply = connection.network.expect(startswith=expect) if (reply == None) : - print "Expected reply to good request not received" + print ("Expected reply to good request not received") return 2 - if (verbose) : - print " Node supports:" + if (verbose) : + print (" Node supports:") value = canolcbutils.bodyArray(reply) - if (value[2] & 0x80) != 0 : print " Protocol Identification" - if (value[2] & 0x40) != 0 : print " Datagram Protocol" - if (value[2] & 0x20) != 0 : print " Stream Protocol" - if (value[2] & 0x10) != 0 : print " Memory Configuration Protocol" - if (value[2] & 0x08) != 0 : print " Reservation Protocol" - if (value[2] & 0x04) != 0 : print " Event Exchange (P/C) Protocol" - if (value[2] & 0x02) != 0 : print " Identification Protocol" - if (value[2] & 0x01) != 0 : print " Teaching/Learning Protocol" - if (value[3] & 0x80) != 0 : print " Remote Button Protocol" - if (value[3] & 0x40) != 0 : print " Abbreviated Default CDI Protocol" - if (value[3] & 0x20) != 0 : print " Display Protocol" - if (value[3] & 0x10) != 0 : print " Simple Node Information Protocol" - if (value[3] & 0x08) != 0 : print " Configuration Description Information" - if (value[3] & 0x04) != 0 : print " Traction Control Protocol" - if (value[3] & 0x02) != 0 : print " Function Description Information" - if (value[3] & 0x01) != 0 : print " DCC Command Station Protocol" - if (value[4] & 0x80) != 0 : print " SimpleTrain Node Information" - if (value[4] & 0x40) != 0 : print " Function Configuration" - if (value[4] & 0x20) != 0 : print " Firmware Upgrade Protocol" - if (value[4] & 0x10) != 0 : print " Firmware Upgrade Active" + if (value[2] & 0x80) != 0 : print (" Protocol Identification") + if (value[2] & 0x40) != 0 : print (" Datagram Protocol") + if (value[2] & 0x20) != 0 : print (" Stream Protocol") + if (value[2] & 0x10) != 0 : print (" Memory Configuration Protocol") + if (value[2] & 0x08) != 0 : print (" Reservation Protocol") + if (value[2] & 0x04) != 0 : print (" Event Exchange (P/C) Protocol") + if (value[2] & 0x02) != 0 : print (" Identification Protocol") + if (value[2] & 0x01) != 0 : print (" Teaching/Learning Protocol") + if (value[3] & 0x80) != 0 : print (" Remote Button Protocol") + if (value[3] & 0x40) != 0 : print (" Abbreviated Default CDI Protocol") + if (value[3] & 0x20) != 0 : print (" Display Protocol") + if (value[3] & 0x10) != 0 : print (" Simple Node Information Protocol") + if (value[3] & 0x08) != 0 : print (" Configuration Description Information") + if (value[3] & 0x04) != 0 : print (" Traction Control Protocol") + if (value[3] & 0x02) != 0 : print (" Function Description Information") + if (value[3] & 0x01) != 0 : print (" DCC Command Station Protocol") + if (value[4] & 0x80) != 0 : print (" SimpleTrain Node Information") + if (value[4] & 0x40) != 0 : print (" Function Configuration") + if (value[4] & 0x20) != 0 : print (" Firmware Upgrade Protocol") + if (value[4] & 0x10) != 0 : print (" Firmware Upgrade Active") if (verbose) : - print " not addressed, expect no reply" + print (" not addressed, expect no reply") connection.network.send(makeframe(alias, (~dest)&0xFFF)) body = [(alias>>8)&0xFF, alias&0xFF] expect = canolcbutils.makeframestring(0x19668000 + dest, body) expect = expect[:-1] reply = connection.network.expect(startswith=expect) - if (reply != None ) : - print "Unexpected reply received to request to different node ", reply + if (reply != None ) : + print ("Unexpected reply received to request to different node ", reply) return 1 return 0 diff --git a/readConfiguration.py b/readConfiguration.py index 0bfb977..7b988bf 100755 --- a/readConfiguration.py +++ b/readConfiguration.py @@ -10,20 +10,20 @@ import datagram def usage() : - print "" - print "Called standalone, will do one-byte memory read" - print " and display response" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-c --count number of bytes to read (default 1)" - print "-s --space address space (default 254, configuration; CDI is 255, all-mem is 253)" - print "-A address, decimal, defaults to zero" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Called standalone, will do one-byte memory read") + print(" and display response") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-c --count number of bytes to read (default 1)") + print("-s --space address space (default 254, configuration; CDI is 255, all-mem is 253)") + print("-A address, decimal, defaults to zero") + print("-t find destination alias automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -39,9 +39,9 @@ def main(): try: opts, remainder = getopt.getopt(sys.argv[1:], "A:s:d:a:c:vVt", ["space=", "dest=", "count=", "alias="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -90,9 +90,9 @@ def test(alias, dest, connection, address, count, space, verbose) : # pass error code up return retval if retval[0:6] != [0x20,cmd|0x10,(address/256/256/256)&0xFF,(address/256/256)&0xFF,(address/256)&0xFF,address&0xFF] : - print "Unexpected message instead of read reply datagram ", retval + print("Unexpected message instead of read reply datagram ", retval) return 3 - if verbose : print "read value", retval[6:] + if verbose : print("read value", retval[6:]) if __name__ == '__main__': main() diff --git a/serialolcblink.py b/serialolcblink.py index 31b7042..cd0415f 100755 --- a/serialolcblink.py +++ b/serialolcblink.py @@ -11,9 +11,9 @@ class SerialOlcbLink : def __init__(self) : - + # defaults (generally overridden by system-wide defaults elsewhere) - self.port = "/dev/tty.usbserial-A7007AOK" + self.port = "/dev/cu.usbmodemCC570001B1" self.speed = 115200 self.timeout = 0.1 # try to keep operations fast self.verbose = False @@ -21,21 +21,22 @@ def __init__(self) : self.startdelay = 0 # set to 12 if your hardware resets on connection self.ser = None return - + def connect(self) : # if verbose, print - if (self.verbose) : print " connect to ",self.port," at ",self.speed - + if (self.verbose) : print (" connect to "+str(self.port)+" at "+str(self.speed)) + self.ser = serial.Serial(self.port, self.speed) self.ser.parity = serial.PARITY_NONE self.ser.bytesize = serial.EIGHTBITS self.ser.stopbits = serial.STOPBITS_TWO - self.ser.setXonXoff(True) + #self.ser.setXonXoff(True) self.ser.rtscts = False self.ser.dsrdtr = False self.ser.setDTR(True) self.ser.setRTS(True) - + + # from http://bytes.com/topic/python/answers/170478-uart-parity-setting-mark-space-using-pyserial if self.speed == 230400 and not self.parallel : self.ser.parity = serial.PARITY_EVEN @@ -44,23 +45,23 @@ def connect(self) : iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self.ser) cflag |= 0x40000000 # CMSPAR to select MARK parity termios.tcsetattr(self.ser, termios.TCSANOW, [iflag, oflag, cflag, lflag,ispeed, ospeed, cc]) - - + + # wait default time for Arduino startup # after (possible) reset due to serial startup if self.startdelay > 0 : - if self.verbose : print " waiting", self.startdelay, "seconds for adapter restart" + if self.verbose : print (" waiting", self.startdelay, "seconds for adapter restart") time.sleep(self.startdelay) # dump all messages while self.ser.inWaiting() > 0 : self.ser.readline() return - + def send(self, frame) : if self.ser == None : self.connect() - + # if verbose, print - if self.verbose : print " send ",frame + if self.verbose : print (" send "+str(frame)) # double-output format needed if operating at 230400 tframe = frame+'\n' @@ -70,29 +71,84 @@ def send(self, frame) : tframe = tframe+c+c tframe = tframe+";;" # send - self.ser.write(tframe) - + self.ser.write(tframe.encode()) + return - + def receive(self) : # returns frame if (self.ser == None) : self.connect() - - # if verbose, print - if (self.verbose) : print " receive ", - + self.ser.timeout = self.timeout line = ""; r = self.ser.readline() # remove Xoff/Xon characters if present - r = r.replace("\x11", "") + r = r.decode('utf8').replace("\x11", "") r = r.replace("\x13", "") + r = r.replace("\x0A", "") + r = r.replace("\x0D", "") # timeout returns "" - if r == "" : - if (self.verbose) : print "" # blank line to show delay? + if r == "" : + if (self.verbose) : print (" receive ") # blank line to show delay? return None - # if verbose, display what's received - if (self.verbose) : print r.replace("\x0A", "").replace("\x0D", "") - return r + # if verbose, display what's received + if (self.verbose) : print (" receive "+r.replace("\x0A", "").replace("\x0D", "")) + return r + + ''' + Continue receiving data until the we get the expected result or timeout. + @param exact if != None, look for result with exact string + @param startswith if != None, look for result starting with string + @param data if != None, tuple of data bytes to match + @param timeout timeout in seconds, if timeout != 0, return None on timeout + @return resulting message on success, None on timeout + ''' + def expect(self, exact=None, startswith=None, data=None, timeout=1) : + start = time.time() + while (True) : # loop to find, timeout or fali + result = self.receive() + + if (result == None) : + if (timeout != 0) : + if (time.time() > (start + timeout)) : + if (self.verbose) : + print ("Timeout") + return None + else : + continue + else : return None + + # here, result was not None - do sequential checks + if (exact == None and startswith == None and data == None) : + return result # no test, just get the data + + if (data != None) : + if (len(data) == ((len(result) - 12) / 2)) : + i = 0 + j = 11 + while i != len(data)-1 : + if (data[i] != int('0x' + result[j] + result[j + 1], 16)) : + # fail on non equal + return None + i = i + 1 + j = j + 2 + else : + # fail on length + return None + + if (exact != None) : + print ("exact may not be working right?") + print (result) + print (exact) + print (result == exact) + if (result != exact) : + return None + + if (startswith != None) : + if (not result.startswith(startswith)) : + return None + + # here, we passed all the available tests! + return result def close(self) : return @@ -101,56 +157,59 @@ def close(self) : def main(): global frame - + # create connection object network = SerialOlcbLink() # get defaults - port = network.port + port = network.port speed = network.speed verbose = network.verbose - - frame = ':X180A7000N;' + + frame = ':X19490001N;' # process arguments (port, speed, frame, verbose) = args(port, speed, frame, verbose) - + # load new defaults network.port = port network.speed = speed network.verbose = verbose - + # send the frame network.send(frame) + + # then wait for and display responses until interrupted or nothing received while True : - network.receive() - - return # done with example + reply = network.receive() + if reply == None : break + print (reply) + return def usage() : - print "" - print "Python module for connecting to an OpenLCB via an serial connection." - print "Called standalone, will send one CAN frame." - print "" - print "valid options:" - print " -v for verbose; also displays any responses" - print " -p, --port for serial port to USB connection" - print " -s, --speed for baud rate" - print "" - print "valid usages (default values):" - print " python serialolcblink.py --port=/dev/tty.usbserial-A7007AOK" - print " python serialolcblink.py --port=/dev/tty.usbserial-A7007AOK --speed=115200" - print " python serialolcblink.py --port=/dev/tty.usbserial-A7007AOK --speed=115200 :X180A7000N;\;" - print "" - print "Note: Most shells require escaping the semicolon at the end of the frame." - + print ("") + print ("Python module for connecting to an OpenLCB via an serial connection.") + print ("Called standalone, will send one CAN frame.") + print ("") + print ("valid options:") + print (" -v for verbose; also displays any responses") + print (" -p, --port for serial port to USB connection") + print (" -s, --speed for baud rate") + print ("") + print ("valid usages (default values):") + print (" python serialolcblink.py --port=/dev/tty.usbserial-A7007AOK") + print (" python serialolcblink.py --port=/dev/tty.usbserial-A7007AOK --speed=115200") + print (" python serialolcblink.py --port=/dev/tty.usbserial-A7007AOK --speed=115200 :X19490001N\;") + print ("") + print ("Note: Most shells require escaping the semicolon at the end of the frame.") + def args(port, speed, frame, verbose) : # argument processing try: opts, remainder = getopt.getopt(sys.argv[1:], "s:p:v", ["speed=", "port="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print (str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -162,10 +221,10 @@ def args(port, speed, frame, verbose) : speed = int(arg) else: assert False, "unhandled option" - if (len(remainder) > 0) : + if (len(remainder) > 0) : frame = remainder[0] return (port, speed, frame, verbose) - + if __name__ == '__main__': main() - + diff --git a/simpleNodeIdentificationInformation.py b/simpleNodeIdentificationInformation.py index 839a2b4..3b112ce 100755 --- a/simpleNodeIdentificationInformation.py +++ b/simpleNodeIdentificationInformation.py @@ -11,19 +11,19 @@ def makeframe(alias, dest) : body = [(dest>>8)&0xFF, dest&0xFF] return canolcbutils.makeframestring(0x19DE8000+alias,body) - + def usage() : - print "" - print "Called standalone, will send one CAN Simple Node Identificant Information (addressed) message" - print " and display response" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Called standalone, will send one CAN Simple Node Identificant Information (addressed) message") + print(" and display response") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-t find destination alias automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -33,12 +33,12 @@ def main(): dest = connection.testNodeAlias identifynode = False verbose = False - + try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:vVt", ["alias=", "dest="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -63,11 +63,11 @@ def main(): retval = test(alias, dest, connection, verbose) connection.network.close() exit(retval) - + def test(alias, dest, connection, verbose) : - if verbose : print " check valid request" + if verbose : print(" check valid request") connection.network.send(makeframe(alias, dest)) - + mfgName = "" mfgType = "" mfgHVers = "" @@ -75,16 +75,16 @@ def test(alias, dest, connection, verbose) : userName = "" userComment = "" fill = 0 # 0 is format byte, 1 is name, 2 is type, 3 is vers - + # assume always sends the same number of frames count = 0 - + while (True) : reply = connection.network.receive() if reply == None : break - if not (reply.startswith(":X19A08") and int(reply[7:10],16)==dest and int(reply[11:15],16)==alias) : - print "Unexpected reply received ", reply + if not (reply.startswith(":X19A08") and int(reply[7:10],16)==dest and int(reply[12:15],16)==alias) : + print("Unexpected reply received ", reply) return 1 # process content val = canolcbutils.bodyArray(reply) @@ -92,57 +92,55 @@ def test(alias, dest, connection, verbose) : for c in val[2:] : if fill == 0 : fill = 1 - if c != 1 : - print "First byte of first part should have been one, was ",c + if c != 1 and c != 4: + print("First byte of first part should have been one or four, was ",c) return 3 - elif fill == 1 : + elif fill == 1 : mfgName = mfgName+chr(c) elif fill == 2 : - mfgType = mfgType+chr(c) + mfgType = mfgType+chr(c) elif fill == 3 : - mfgHVers = mfgHVers+chr(c) + mfgHVers = mfgHVers+chr(c) elif fill == 4 : - mfgSVers = mfgSVers+chr(c) + mfgSVers = mfgSVers+chr(c) elif fill == 5 : fill = 6 - if c != 1 : - print "First byte of second part should have been one, was ",c + if c != 1 and c != 2 : + print("First byte of second part should have been one or two, was ",c) return 4 elif fill == 6 : - userName = userName+chr(c) + userName = userName+chr(c) elif fill == 7 : - userComment = userComment+chr(c) + userComment = userComment+chr(c) else : - print "Unexpected extra content", c + print("Unexpected extra content", c) return 15 if c == 0 : # end of string fill = fill + 1 if fill != 8 and fill != 5: - print "Didn't receive all strings", fill + print("Didn't receive all strings", fill) return fill+10 if verbose : - print " Manufacturer: ", mfgName - print " Type: ", mfgType - print " Hardware Version: ", mfgHVers - print " Software Version: ", mfgSVers + print(" Manufacturer: ", mfgName) + print(" Type: ", mfgType) + print(" Hardware Version: ", mfgHVers) + print(" Software Version: ", mfgSVers) if fill == 8 : - print " User Name: ", userName - print " User Comment: ", userComment + print(" User Name: ", userName) + print(" User Comment: ", userComment) - if verbose : print " address other node, expect no reply" + if verbose : print(" address other node, expect no reply") connection.network.send(makeframe(alias, (~dest)&0xFFF)) reply = connection.network.receive() - if reply != None : - print "Unexpected reply received ", reply - - if verbose : print " check three simultaneous requests" + if reply != None : + print("Unexpected reply received ", reply) + + if verbose : print(" check three simultaneous requests") alias2 = (alias+1)&0xFFF if alias2 == dest : alias2 = (alias2+1)&0xFFF - alias3 = (alias+10)&0xFFF + alias3 = (alias+3)&0xFFF if alias3 == dest : alias3 = (alias3+10)&0xFFF - - #frame = makeframe(alias, dest)+makeframe(alias2, dest)+makeframe(alias3, dest) - #connection.network.send(frame) + connection.network.send(makeframe(alias, dest)) connection.network.send(makeframe(alias2, dest)) connection.network.send(makeframe(alias3, dest)) @@ -154,29 +152,29 @@ def test(alias, dest, connection, verbose) : reply = connection.network.receive() if reply == None : break - if (reply.startswith(":X19A08") and int(reply[7:10],16)==dest and int(reply[11:15],16)==alias) : + if (reply.startswith(":X19A08") and int(reply[7:10],16)==dest and int(reply[12:15],16)==alias) : count1 = count1+1 - if (reply.startswith(":X19068") and int(reply[7:10],16)==dest and int(reply[11:15],16)==alias) : + if (reply.startswith(":X19068") and int(reply[7:10],16)==dest and int(reply[12:15],16)==alias) : count1 = count1-100 - if (reply.startswith(":X19A08") and int(reply[7:10],16)==dest and int(reply[11:15],16)==alias2) : + if (reply.startswith(":X19A08") and int(reply[7:10],16)==dest and int(reply[12:15],16)==alias2) : count2 = count2+1 - if (reply.startswith(":X19068") and int(reply[7:10],16)==dest and int(reply[11:15],16)==alias2) : + if (reply.startswith(":X19068") and int(reply[7:10],16)==dest and int(reply[12:15],16)==alias2) : count2 = count2-100 - if (reply.startswith(":X19A08") and int(reply[7:10],16)==dest and int(reply[11:15],16)==alias3) : + if (reply.startswith(":X19A08") and int(reply[7:10],16)==dest and int(reply[12:15],16)==alias3) : count3 = count3+1 - if (reply.startswith(":X19068") and int(reply[7:10],16)==dest and int(reply[11:15],16)==alias3) : + if (reply.startswith(":X19068") and int(reply[7:10],16)==dest and int(reply[12:15],16)==alias3) : count3 = count3-100 - if count != count1 and count1 != -100: - print "got ",count1," frames for request 1 instead of ",count + if count != count1 and count1 != -100: + print("got "+str(count1)+" frames for request 1 instead of "+str(count)+" in overlapping requests test") return 101 - if count != count2 and count2 != -100: - print "got ",count2," frames for request 2 instead of ",count + if count != count2 and count2 != -100: + print("got "+str(count2)+" frames for request 2 instead of "+str(count)+" in overlapping requests test") return 102 - if count != count3 and count3 != -100: - print "got ",count3," frames for request 3 instead of ",count + if count != count3 and count3 != -100: + print("got "+str(count3)+" frames for request 3 instead of "+str(count)+" in overlapping requests test") return 103 return 0 - + if __name__ == '__main__': main() diff --git a/tcpolcblink.py b/tcpolcblink.py index 21f7f7d..483894c 100755 --- a/tcpolcblink.py +++ b/tcpolcblink.py @@ -31,7 +31,7 @@ def __init__(self) : def connect(self) : # if verbose, print - if (self.verbose) : print " connect to ",self.host,":",self.port + if (self.verbose) : print(" connect to ",self.host,":",self.port) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.host, self.port)) @@ -39,7 +39,7 @@ def connect(self) : # wait for link startup # after (possible) reset due to serial startup if self.startdelay > 0 : - if self.verbose : print " waiting", self.startdelay, "seconds for adapter restart" + if self.verbose : print(" waiting", self.startdelay, "seconds for adapter restart") time.sleep(self.startdelay) return @@ -49,7 +49,7 @@ def send(self, string) : # if verbose, print if (self.verbose) : - print " send ",string + print(" send ",string) # send self.socket.send(string) @@ -76,9 +76,9 @@ def receive(self) : # returns frame try: self.rcvData = self.socket.recv(1024) self.rcvIndex = 0 - except socket.timeout, err: + except socket.timeout as err: if (self.verbose) : - print "" # blank line to show delay? + print("") # blank line to show delay? return None else : # parse our data @@ -91,7 +91,7 @@ def receive(self) : # returns frame self.rcvIndex = self.rcvIndex + 1 # if verbose, print if (self.verbose) : - print " receive",result + print(" receive",result) return result i = i + 1 self.rcvIndex = self.rcvIndex + 1 @@ -134,7 +134,7 @@ def expect(self, exact=None, startswith=None, data=None, timeout=1) : if (timeout != 0) : if (time.time() > (start + timeout)) : if (self.verbose) : - print "Timeout" + print("Timeout") return None def close(self) : diff --git a/tcpolcbutils.py b/tcpolcbutils.py index 355e04c..1a50998 100755 --- a/tcpolcbutils.py +++ b/tcpolcbutils.py @@ -72,9 +72,9 @@ def parseMessage(message) : ''' def main(): - print format(makemessagestring([0x12,0x34,0x56,0x78,0x9A,0xbc], None, [0x04,0x90,0x12,0x34,0x56,0x78,0x9A,0xbc])) - print parseMessage([0x04,0x90,0x12,0x34,0x56,0x78,0x9A,0xbc,1,2]) - print parseMessage([0x04,0x98,0x12,0x34,0x56,0x78,0x9A,0xbc, 0x12,0x34,0x56,0x78,0x9A,0xbc,1,2]) + print(format(makemessagestring([0x12,0x34,0x56,0x78,0x9A,0xbc], None, [0x04,0x90,0x12,0x34,0x56,0x78,0x9A,0xbc]))) + print(parseMessage([0x04,0x90,0x12,0x34,0x56,0x78,0x9A,0xbc,1,2])) + print(parseMessage([0x04,0x98,0x12,0x34,0x56,0x78,0x9A,0xbc, 0x12,0x34,0x56,0x78,0x9A,0xbc,1,2])) if __name__ == '__main__' : main() diff --git a/testAliasConflict.py b/testAliasConflict.py index 59143e5..0410cda 100755 --- a/testAliasConflict.py +++ b/testAliasConflict.py @@ -18,19 +18,19 @@ import verifyNodeGlobal import verifyNodeAddressed import time - + def usage() : - print "" - print "Called standalone, tests a node's response to" - print "seeing messages with its alias" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 123)" - print "-d --dest dest alias (default 123)" - print "-t find destination alias automatically" - print "-v verbose" - print "-V very verbose" + print("") + print("Called standalone, tests a node's response to") + print("seeing messages with its alias") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 123)") + print("-d --dest dest alias (default 123)") + print("-t find destination alias automatically") + print("-v verbose") + print("-V very verbose") import getopt, sys @@ -39,13 +39,13 @@ def main(): dest = connection.testNodeAlias; verbose = False identifynode = False - + # argument processing try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:vVt", ["alias=", "dest="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -70,37 +70,37 @@ def main(): retval = test(alias, dest, connection, verbose) connection.network.close() return retval - + def test(alias, dest, connection, verbose) : # Note: This test assumes that the response will be # to reacquire another alias after the conflicted one is # dropped. This isn't required behavior by standard, but - # is a necessary condition for the test to continue and + # is a necessary condition for the test to continue and # check another conflict condition. - # + # Sending a global message (that normally doesn't get a response) - # by sending verifyNodeGlobal with a nodeID that doesn't match any valid - if verbose : print " check no-response global message with alias conflict" + # by sending verifyNodeGlobal with a nodeID that doesn't match any valid ID + if verbose : print(" check no-response global message with alias conflict") connection.network.send(verifyNodeGlobal.makeframe(dest, [0,0,0,0,0,1])) reply = connection.network.receive() if reply == None : - print "no response received to conflict frame" + print("no response received to conflict frame") return 21 - if not reply.startswith(":X10703") : - print "Expected first AMR" + if not reply.startswith(":X10703") : # Expect AMR + print("Expected first AMR") return 22 - if int(reply[7:10],16) != dest : - print "incorrect alias in AMR" + if int(reply[7:10],16) != dest : # with expected (existing) alias + print("incorrect alias in AMR") return 23 reply = connection.network.receive() if reply == None : - print "no response received to conflict frame" + print("no response received to conflict frame") return 21 - if not reply.startswith(":X17") : - print "Expected first CID" + if not reply.startswith(":X17") : # Then first CID + print("Expected first CID") return 22 - if int(reply[7:10],16) == 0 : - print "received alias == 0" + if int(reply[7:10],16) == 0 : # With a new, non-zero alias + print("received alias == 0") return 23 dest = int(reply[7:10],16) # pull & drop rest of sequence @@ -108,35 +108,36 @@ def test(alias, dest, connection, verbose) : reply = connection.network.receive() # CID 3 reply = connection.network.receive() # CID 4 timeout = connection.network.timeout - connection.network.timeout = 1.0 + connection.network.timeout = 1.0 # (expect delay here) reply = connection.network.receive() # RID connection.network.timeout = timeout - # dump everything until nothing heard + # dump everything until nothing heard - can include lots of e.g. event identification while (reply != None) : reply = connection.network.receive() - + # Sending a global message (that normally does get a response) - if verbose : print " check response-inducing global message with alias conflict" + # check to make sure that response is sent with new alias + if verbose : print(" check response-inducing global message with alias conflict") connection.network.send(verifyNodeGlobal.makeframe(dest, None)) reply = connection.network.receive() if reply == None : - print "no response received to conflict frame" + print("no response received to conflict frame") return 21 - if not reply.startswith(":X10703") : - print "Expected second AMR" + if not reply.startswith(":X10703") : # Expect AMR + print("Expected second AMR") return 22 - if int(reply[7:10],16) != dest : - print "incorrect alias in AMR" + if int(reply[7:10],16) != dest : # with alias from previous collision recovery + print("incorrect alias in AMR") return 23 reply = connection.network.receive() if reply == None : - print "no response received to conflict frame" + print("no response received to conflict frame") return 31 - if not reply.startswith(":X17") : - print "Expected second CID" + if not reply.startswith(":X17") : # Expect 1st frame of 2nd CID sequence + print("Expected second CID") return 32 - if int(reply[7:10],16) == 0 : - print "received alias == 0" + if int(reply[7:10],16) == 0 : # with a new, non-zero alias + print("received alias == 0") return 33 dest = int(reply[7:10],16) # pull & drop rest of sequence @@ -147,32 +148,32 @@ def test(alias, dest, connection, verbose) : connection.network.timeout = 1.0 reply = connection.network.receive() # RID connection.network.timeout = timeout - # dump everything until nothing heard + # dump everything until nothing heard - not yet checking for reply to VerifyNode while (reply != None) : reply = connection.network.receive() - + # Sending an addressed message to some other alias (note arguments backwards, on purpose) - if verbose : print " check addressed message with alias conflict" + if verbose : print(" check addressed message with alias conflict") connection.network.send(verifyNodeAddressed.makeframe(dest, alias, None)) reply = connection.network.receive() if reply == None : - print "no response received to conflict frame" + print("no response received to conflict frame") return 21 if not reply.startswith(":X10703") : - print "Expected third AMR" + print("Expected third AMR") return 22 if int(reply[7:10],16) != dest : - print "incorrect alias in AMR" + print("incorrect alias in AMR") return 23 reply = connection.network.receive() if reply == None : - if verbose : print "no response received to conflict frame" + if verbose : print("no response received to conflict frame") return 41 if not reply.startswith(":X17") : - if verbose : print "Expected third CID" + if verbose : print("Expected third CID") return 42 if int(reply[7:10],16) == 0 : - print "received alias == 0" + print("received alias == 0") return 43 dest = int(reply[7:10],16) # pull & drop rest of sequence @@ -187,42 +188,42 @@ def test(alias, dest, connection, verbose) : while (reply != None) : reply = connection.network.receive() - # send a CheckID - if verbose : print " check CheckID with alias conflict" + # send a CheckID + if verbose : print(" check CheckID with alias conflict") connection.network.send(canolcbutils.makeframestring(0x17020000+dest, None)) reply = connection.network.receive() if reply == None : - if verbose : print "no response received to CID" + if verbose : print("no response received to CID") return 51 if int(reply[7:10],16) != dest : - if verbose : print "mismatched reply alias" + if verbose : print("mismatched reply alias") return 52 if not reply.startswith(":X10700") : - if verbose : print "CID reply not correct, RID expected" + if verbose : print("CID reply not correct, RID expected") return 53 - # send a ReserveID + # send a ReserveID + if verbose : print(" check ReserveID with alias conflict") connection.network.send(canolcbutils.makeframestring(0x10700000+dest, None)) - if verbose : print " check ReserveID with alias conflict" reply = connection.network.receive() if reply == None : - print "no response received to conflict frame" + print("no response received to conflict frame") return 21 - if not reply.startswith(":X10703") : - print "Expected fourth AMR" + if not reply.startswith(":X10703") : # Expect AMR + print("Expected fourth AMR") return 22 if int(reply[7:10],16) != dest : - print "incorrect alias in AMR" + print("incorrect alias in AMR") return 23 reply = connection.network.receive() if reply == None : - if verbose : print "no response received to conflict frame" + if verbose : print("no response received to conflict frame") return 61 if not reply.startswith(":X17") : - if verbose : print "Expected fourth CID" + if verbose : print("Expected fourth CID") return 62 if int(reply[7:10],16) == 0 : - print "received alias == 0" + print("received alias == 0") return 63 dest = int(reply[7:10],16) # pull & drop rest of sequence diff --git a/testCDI.py b/testCDI.py index a3c9a41..aa1645d 100755 --- a/testCDI.py +++ b/testCDI.py @@ -8,18 +8,18 @@ import connection as connection import canolcbutils import datagram - + def usage() : - print "" - print "Read and check the Configuration Definition Information" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Read and check the Configuration Definition Information") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-t find destination alias automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -29,12 +29,12 @@ def main(): dest = connection.testNodeAlias identifynode = False verbose = False - + try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:vVt", ["dest=", "alias="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -59,7 +59,7 @@ def main(): retval = test(alias, dest, connection, verbose) connection.network.close() exit(retval) - + def test(alias, dest, connection, verbose) : # instead of checking the length of the address space (not cleanly required anyway) @@ -69,19 +69,20 @@ def test(alias, dest, connection, verbose) : result = "" chunk = 16 done = False - - while True : + connection.network.timeout = 3 + + while True : # Read from CDI space retval = datagram.sendOneDatagram(alias, dest, [0x20,0x43,(address>>24)&0xFF,(address>>16)&0xFF,(address>>8)&0xFF,address&0xFF,chunk], connection, verbose) if retval != 0 : return retval # read data response retval = datagram.receiveOneDatagram(alias, dest, connection, verbose) - if (type(retval) is int) : + if (type(retval) is int) : # pass error code up return retval if retval[0:2] != [0x20,0x53] : - print "Unexpected message instead of read reply datagram ", retval + print("Unexpected message instead of read reply datagram ", retval) return 3 for c in retval[6:] : result = result+chr(c) @@ -90,21 +91,21 @@ def test(alias, dest, connection, verbose) : break; if done : break address = address + chunk - - if verbose : print " Read CDI result was ", len(result), " bytes" - if connection.network.verbose : print " Read CDI result ++++++++++\n", result,"\n++++++++++++++++" - - executable = "xmllint --noout --schema ../../specs/schema/cdi.xsd - " + + if verbose : print(" Read CDI result was ", len(result), " bytes") + if connection.network.verbose : print(" Read CDI result ++++++++++\n", result,"\n++++++++++++++++") + + executable = "xmllint --noout --schema http://openlcb.org/schema/cdi/1/1/cdi.xsd - " import subprocess - process = subprocess.Popen(executable,1,None,subprocess.PIPE,subprocess.PIPE, + process = subprocess.Popen(executable,-1,None,subprocess.PIPE,subprocess.PIPE, subprocess.STDOUT, None, False, True) - [stdout, stderr] = process.communicate(result) - + [stdout, stderr] = process.communicate(result.encode()) + if process.returncode != 0 : - print " CDI data did not validate: ", stdout + print(" CDI data did not validate: ", stdout) if process.returncode == 0 and verbose : - print " CDI result check: ", stdout + print(" CDI result check: ", stdout) return process.returncode diff --git a/testConfigurationProtocol.py b/testConfigurationProtocol.py index 95bac18..bd697fc 100755 --- a/testConfigurationProtocol.py +++ b/testConfigurationProtocol.py @@ -8,19 +8,19 @@ import connection as connection import canolcbutils import datagram - + def usage() : - print "" - print "Comprehensive test of the Memory Configuration " - print "Protocol implementation" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Comprehensive test of the Memory Configuration ") + print("Protocol implementation") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-t find destination alias automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -30,12 +30,12 @@ def main(): dest = connection.testNodeAlias identifynode = False verbose = False - + try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:vVt", ["dest=", "alias="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -60,92 +60,93 @@ def main(): retval = test(alias, dest, connection, verbose) connection.network.close() exit(retval) - + def test(alias, dest, connection, verbose) : # Get Configuration Options retval = datagram.sendOneDatagramNoWait(alias, dest, [0x20,0x80], connection, verbose) # read data response retval = datagram.receiveDatagramReplyAndOneDatagram(alias, dest, connection, verbose) - if (type(retval) is int) : + if (type(retval) is int) : # pass error code up return retval if retval[0:2] != [0x20,0x82] : - print "Unexpected message instead of read reply datagram ", retval + print("Unexpected message instead of read reply datagram ", retval) return 3 - if verbose : - print " Configuration Options:" + if verbose : + print(" Configuration Options:") cmd = retval[2]*256+retval[3] - print " Available commands (",hex(cmd),")" - print " Write under mask: ", "yes" if cmd&0x8000 else "no" - print " Unaligned reads: ", "yes" if cmd&0x4000 else "no" - print " Unaligned writes: ", "yes" if cmd&0x2000 else "no" - print " Mfg ACDI 0xFD read: ", "yes" if cmd&0x0800 else "no" - print " Usr ACDI 0xFC read: ", "yes" if cmd&0x0400 else "no" - print " Usr ACDI 0xFC write: ", "yes" if cmd&0x0200 else "no" - print " Write lengths (", hex(retval[4]),")" - print " 1 byte: ", "yes" if retval[4]&0x80 else "no" - print " 2 byte: ", "yes" if retval[4]&0x40 else "no" - print " 4 byte: ", "yes" if retval[4]&0x20 else "no" - print " 64 byte: ", "yes" if retval[4]&0x10 else "no" - print " arbitrary: ", "yes" if retval[4]&0x02 else "no" - print " stream: ", "yes" if retval[4]&0x01 else "no" - print " Highest space ", retval[5] - print " Lowest space ", retval[6] + print(" Available commands (",hex(cmd),")") + print(" Write under mask: ", "yes" if cmd&0x8000 else "no") + print(" Unaligned reads: ", "yes" if cmd&0x4000 else "no") + print(" Unaligned writes: ", "yes" if cmd&0x2000 else "no") + print(" Mfg ACDI 0xFD read: ", "yes" if cmd&0x0800 else "no") + print(" Usr ACDI 0xFC read: ", "yes" if cmd&0x0400 else "no") + print(" Usr ACDI 0xFC write: ", "yes" if cmd&0x0200 else "no") + print(" Write lengths (", hex(retval[4]),")") + print(" 1 byte: ", "yes" if retval[4]&0x80 else "no") + print(" 2 byte: ", "yes" if retval[4]&0x40 else "no") + print(" 4 byte: ", "yes" if retval[4]&0x20 else "no") + print(" 64 byte: ", "yes" if retval[4]&0x10 else "no") + print(" arbitrary: ", "yes" if retval[4]&0x02 else "no") + print(" stream: ", "yes" if retval[4]&0x01 else "no") + print(" Highest space ", retval[5]) + print(" Lowest space ", retval[6]) lowSpace = retval[6] highSpace = retval[5] - + # One byte read from config space retval = datagram.sendOneDatagramNoWait(alias, dest, [0x20,0x41,0,0,0,0,1], connection, verbose) # read data response retval = datagram.receiveDatagramReplyAndOneDatagram(alias, dest, connection, verbose) - if (type(retval) is int) : + if (type(retval) is int) : # pass error code up return retval if retval[0:6] != [0x20,0x51,0x00,0x00,0x00,0x00] : - print "Unexpected message instead of read reply datagram ", retval + print("Unexpected message instead of read reply datagram ", retval) return 3 - if verbose : print " Read one byte result", retval[6:7] - + if verbose : print(" Read one byte result", retval[6:7]) + # Eight byte read from config space retval = datagram.sendOneDatagramNoWait(alias, dest, [0x20,0x41,0,0,0,0,8], connection, verbose) # read data response retval = datagram.receiveDatagramReplyAndOneDatagram(alias, dest, connection, verbose) - if (type(retval) is int) : + if (type(retval) is int) : # pass error code up return retval if retval[0:6] != [0x20,0x51,0x00,0x00,0x00,0x00] : - print "Unexpected message instead of read reply datagram ", retval + print("Unexpected message instead of read reply datagram ", retval) return 3 - if verbose : print " Read eight bytes result", retval[6:] - + if verbose : print(" Read eight bytes result", retval[6:]) + n = highSpace while n >= lowSpace-1 : # Get Address Space Info from each space retval = datagram.sendOneDatagramNoWait(alias, dest, [0x20,0x84,n], connection, verbose) # read data response retval = datagram.receiveDatagramReplyAndOneDatagram(alias, dest, connection, verbose) - if (type(retval) is int) : + if (type(retval) is int) : # pass error code up return retval if retval[0] != 0x20 or retval[1]&0xFE != 0x86 or retval[2] != n : - print "Unexpected message instead of starting with [0x20,0x86,",n,"] read reply datagram: ", retval + print("Unexpected message instead of starting with [0x20,0x86,",n,"] read reply datagram: ", retval) return 3 - if verbose : - print " Address Space",n,"Options:" - print " Present? ", "yes" if retval[1]&0x01 else "no" - print " Highest address ", hex(((retval[3]*256+retval[4])*256+retval[5])*256+retval[6]) - print " Flags (", hex(retval[7]),")" - print " Read-only ", "yes" if retval[7]&0x01 else "no" - + if verbose : + retval.extend([0,0,0,0,0]) # in case trailing zeros not sent + print(" Address Space",n,"Options:") + print(" Present? ", "yes" if retval[1]&0x01 else "no") + print(" Highest address ", hex(((retval[3]*256+retval[4])*256+retval[5])*256+retval[6])) + print(" Flags (", hex(retval[7]),")") + print(" Read-only ", "yes" if retval[7]&0x01 else "no") + if len(retval) > 9: - print " Lowest address ", hex(((retval[9]*256+retval[10])*256+retval[11])*256+retval[12]) + print(" Lowest address ", hex(((retval[9]*256+retval[10])*256+retval[11])*256+retval[12])) else: - print " Lowest address implied at 0x0000" + print(" Lowest address implied at 0x0000") if len(retval) > 12: - print " Space name ", str(retval[12:]) + print(" Space name ", str(retval[12:])) n = n-1 - + return 0 if __name__ == '__main__': diff --git a/testDatagram.py b/testDatagram.py index bcbb810..0f7a3ba 100755 --- a/testDatagram.py +++ b/testDatagram.py @@ -16,7 +16,7 @@ def makefirstframe(alias, dest, content) : def makemiddleframe(alias, dest, content) : return canolcbutils.makeframestring(0x1C000000+alias+(dest<<12),content) - + def makefinalframe(alias, dest, content) : return canolcbutils.makeframestring(0x1D000000+alias+(dest<<12),content) @@ -47,13 +47,13 @@ def sendOneDatagram(alias, dest, content, connection, verbose) : frame = makefinalframe(alias, dest, content) connection.network.send(frame) - + frame = connection.network.receive() - if frame == None : - print "Did not receive reply" + if frame == None : + print("Did not receive reply") return 1 if not isAck(frame) : - print "Unexpected message received instead of reply" + print("Unexpected message received instead of reply") return 2 return 0 @@ -61,12 +61,14 @@ def receiveOneDatagram(alias, dest, conection, verbose) : retval = [] reply = connection.network.receive() + if reply == None : + return 10 if reply.startswith(":X1A"): - if not int(reply[4:7],16) == alias: - print "Improper dest alias in reply", reply + if (alias != None) and not int(reply[4:7],16) == alias: + print("Improper dest alias in reply", reply) return 3 if not int(reply[7:10],16) == dest: - print "Improper source alias in reply", reply + print("Improper source alias in reply", reply) return 3 retval = retval + canolcbutils.bodyArray(reply) connection.network.send(makereply(alias, dest)) @@ -74,19 +76,19 @@ def receiveOneDatagram(alias, dest, conection, verbose) : if reply.startswith(":X1B"): if not int(reply[4:7],16) == alias: - print "Improper dest alias in reply", reply + print("Improper dest alias in reply "+str(reply)) return 3 if not int(reply[7:10],16) == dest: - print "Improper source alias in reply", reply + print("Improper source alias in reply "+str(reply)) return 3 retval = retval + canolcbutils.bodyArray(reply) else: - print "Unexpected message instead of first datagram segment", reply + print("Unexpected message "+str(reply)+"instead of first datagram segment in reply to NAK") return 3 while True : reply = connection.network.receive() - if (reply == None ) : - print "No datagram segment received" + if (reply == None ) : + print("No datagram segment received") return 4 elif reply.startswith(":X1C") : retval = retval + canolcbutils.bodyArray(reply) @@ -96,23 +98,23 @@ def receiveOneDatagram(alias, dest, conection, verbose) : connection.network.send(makereply(alias, dest)) return retval else : - print "Unexpected message instead of datagram segment", reply + print("Unexpected message "+str(reply)+" instead of datagram segment") return 3 - + def usage() : - print "" - print "Extensive datagram testing using the Memory Config Protocol" - print "to generate return datagrams" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-b number of buffers to test (sends b+1 requests) default 1, -1 if node has variable number" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Extensive datagram testing using the Memory Config Protocol") + print("to generate return datagrams") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-b number of buffers to test (sends b+1 requests) default 1, -1 if node has variable number") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-t find destination alias automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -123,12 +125,12 @@ def main(): identifynode = False verbose = False num = 1 - + try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:b:vVt", ["dest=", "alias=", "content="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -155,50 +157,51 @@ def main(): retval = test(alias, dest, connection, num, verbose) connection.network.close() exit(retval) - + import datagram # Check for a reply datagram to a request, and check if it's basically OK def checkreply(alias, dest, connection, verbose) : frame = connection.network.receive() - if frame == None : - print "Did not receive reply" + if frame == None : + print("Did not receive reply") return 1 if not isAck(frame) : - print "Unexpected message received instead of reply" + print("Unexpected message received instead of reply") return 2 # read reply retval = receiveOneDatagram(alias, dest, connection, verbose) - if type(retval) is int : + if type(retval) is int : # pass error code up return retval if retval[0:3] != [0x20,0x51,0] : - print "Unexpected message instead of read reply datagram ", retval + print("Unexpected message instead of read reply datagram ", retval) return 3 # Check for a NAK datagram to a request, and check if it's basically OK def checkrejection(alias, dest, connection, verbose) : frame = connection.network.receive() if frame == None : - print "Did not receive reply" + print("Did not receive reply") return 1 if not isNAK(frame) : - print "Unexpected message received instead of NAK" + print("Unexpected message received instead of NAK") return 2 return 0 - -def test(alias, dest, connection, num, verbose) : + +def test(alias, dest, connection, num, verbose) : + # send a short read-request datagram in two segments - if verbose : print " test two segments" + if verbose : print(" test two segments") connection.network.send(makefirstframe(alias, dest, [0x20,0x41,0,0,0])) connection.network.send(makefinalframe(alias, dest, [0,8])) # check response to make sure it was received and interpreted OK retval = checkreply(alias, dest, connection, verbose) if type(retval) is int and retval != 0 : return retval+10 - + # send a short read-request datagram in two segments with another to somebody else in between - if verbose : print " test two segments with extraneous one interposed" + if verbose : print(" test two segments with extraneous one interposed") connection.network.send(makefirstframe(alias, dest, [0x20,0x41,0,0,0])) connection.network.send(makeonlyframe(alias, (~dest)&0xFFF, [0x20,0x41,0,0,0])) connection.network.send(makefinalframe(alias, dest, [0,8])) @@ -208,76 +211,55 @@ def test(alias, dest, connection, num, verbose) : return retval+20 # send a final segment without a start segment - if verbose : print " test final segment without a start segment" + if verbose : print(" test final segment without a start segment") connection.network.send(makefinalframe(alias, dest, [0x20,0x41,0,0,0,0,8])) # check response, expect error frame = connection.network.receive() if not isNAK(frame) : - print "Unexpected reply to final segment without a start segment", frame + print("Unexpected reply to final segment without a start segment", frame) return 101 # send a short read-request datagram in two segments with another from somebody else in between - # interposed one could get rejected or processed; here we assume rejected - if verbose : print " test two segments with another datagram interposed" + # interposed one could get rejected or processed; attempt to handle both cases + if verbose : print(" test two segments with another datagram interposed") connection.network.send(makefirstframe(alias, dest, [0x20,0x41,0,0,0])) newalias = (~alias)&0xFFF if newalias == dest: - newalias = (newalias - 1)&0xFFF; - connection.network.send(makeonlyframe(newalias, dest, [0x20,0x41,0,0,0,0,8])) + newalias = (newalias - 1)&0xFFF; + connection.network.send(makeonlyframe(newalias, dest, [0x20,0x41,0,0,0,0,1])) # check for reject of this one frame = connection.network.receive() if frame == None : - print "no reply to interposed datagram" + print("no reply to interposed datagram") return 81 - elif num == 1 and isAck(frame) : - print "interposed datagram was not rejected due to buffer full:", frame - return 82 elif num > 1 and isNAK(frame) : - print "Unexpected reject of interposed datagram:", frame + print("Unexpected reject of interposed datagram:", frame) return 83 - elif not (isNAK(frame) or isAck(frame)) : - print "Unexpected response to interposed datagram:", frame + elif not (isNAK(frame) or isAck(frame)) : + print("Unexpected response to interposed datagram:", frame) return 84 + elif num == 1 and isAck(frame) : + # this is the OK case of the intermediate datagram being accepted + if verbose: print(" interposed datagram was accepted:", frame) + retval = receiveOneDatagram(newalias, dest, connection, verbose) + if type(retval) is int : + # pass error code up + return retval + if retval[0:3] != [0x20,0x51,0] : + print("Unexpected message instead of read reply datagram ", retval) + return 3 # send final part of original datagram connection.network.send(makefinalframe(alias, dest, [0,8])) # check response retval = checkreply(alias, dest, connection, verbose) if type(retval) is int and retval != 0 : + print("failure on reply to final seqment") return retval+20 - # NAK the response datagram & check for retransmission - if verbose : print " send NAK to response" - connection.network.send(makeonlyframe(alias, dest, [0x20,0x41,0,0,0,0,1])) - frame = connection.network.receive() - if frame == None : - print "Did not receive reply" - return 31 - if not isAck(frame) : - print "Unexpected message received instead of reply" - return 32 - # read reply, should be a resend of same - reply = connection.network.receive() - if (reply == None ) : - print "No datagram segment received" - return 34 - elif not reply.startswith(":X1A") : - print "Unexpected message instead of datagram segment", reply - return 33 - # send NAK asking for retransmit retransmit and see if it's right this time - connection.network.send(canolcbutils.makeframestring(0x19A48000+alias,[(dest>>8)&0xFF, dest&0xFF,0x20,00])) - #retval = datagram.receiveOneDatagram(alias, dest, connection, verbose) - retval = receiveOneDatagram(alias, dest, connection, verbose) - if type(retval) is int : - # pass error code up - return retval - if retval[0:3] != [0x20,0x51,0] : - print "Unexpected message instead of read reply datagram ", retval - return 37 - - # Test recovery from failure during datagram send by sending a 1st segment, then AMR, + # Test recovery from failure during datagram send by sending a 1st segment, then AMR, # then a complete datagram. The reply will tell if the first part # was properly ignored. - if verbose : print " test recovery from AMR (node failure) after partial transmission of datagram" + if verbose : print(" test recovery from AMR (node failure) after partial transmission of datagram") # send 1st part (valid datagram part, garbage content) connection.network.send(makefirstframe(alias, dest, [0,0,0])) # send AMR for that node @@ -289,10 +271,10 @@ def test(alias, dest, connection, num, verbose) : if type(retval) is int and retval != 0 : return retval+20 - # Test recovery from failure during datagram send by sending a 1st segment, then AMD, + # Test recovery from failure during datagram send by sending a 1st segment, then AMD, # then a complete datagram. The reply will tell if the first part # was properly ignored. - if verbose : print " test recovery from AMD (node failure) after partial transmission of datagram" + if verbose : print(" test recovery from AMD (node failure) after partial transmission of datagram") # send 1st part (valid datagram part, garbage content) connection.network.send(makefirstframe(alias, dest, [0,0,0])) # send AMR for that node @@ -305,7 +287,7 @@ def test(alias, dest, connection, num, verbose) : return retval+20 # Test that AMR and AMD from other nodes don't confuse datagram transmission - if verbose : print " test that AMR, AMD from other nodes doesnt interfere" + if verbose : print(" test that AMR, AMD from other nodes doesnt interfere") # send 1st part (valid datagram part) connection.network.send(makefirstframe(alias, dest, [0x20])) # send AMR,AMD for another node @@ -318,6 +300,36 @@ def test(alias, dest, connection, num, verbose) : if type(retval) is int and retval != 0 : return retval+20 + # NAK the response datagram & check for retransmission + if verbose : print(" test NAK to response datagram") + connection.network.send(makeonlyframe(alias, dest, [0x20,0x41,0,0,0,0,1])) + frame = connection.network.receive() + if frame == None : + print("Did not receive reply to NAK") + return 31 + if not isAck(frame) : + print("Unexpected message received "+str(frame)+" instead of reply to NAK") + return 32 + # read reply, should be a resend of same + reply = connection.network.receive() + if (reply == None ) : + print("No datagram segment received") + return 34 + elif not reply.startswith(":X1A") : + print("Unexpected message "+str(reply)+" instead of datagram segment") + return 33 + # send NAK asking for retransmit retransmit and see if it's right this time + connection.network.send(canolcbutils.makeframestring(0x19A48000+alias,[(dest>>8)&0xFF, dest&0xFF,0x20,00])) + # expect that the datagram may be be retransmitted + retval = receiveOneDatagram(alias, dest, connection, verbose) + if type(retval) is int : + if retval != 10 : # 10 is no datagram received, which is OK + # pass error code up + return retval + elif retval[0:3] != [0x20,0x51,0] : + print("Unexpected message instead of read reply datagram ", retval) + return 37 + return 0 if __name__ == '__main__': diff --git a/testForZeroOrRepeatedAlias.py b/testForZeroOrRepeatedAlias.py index 28e0007..4697314 100755 --- a/testForZeroOrRepeatedAlias.py +++ b/testForZeroOrRepeatedAlias.py @@ -10,33 +10,33 @@ import verifyNodeGlobal import time - + def usage() : - print "" - print "Forces repeated reallocation of alias to check for zero or repetition." - print "" - print "Default connection detail taken from connection.py" - print "" - print "-d --dest destination (target node) starting alias" - print "-t find destination alias automatically" - print "-n --num number of cycles (default 40000, 0 means forever)" - print "-v verbose" - print "-V very verbose" + print("") + print("Forces repeated reallocation of alias to check for zero or repetition.") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-d --dest destination (target node) starting alias") + print("-t find destination alias automatically") + print("-n --num number of cycles (default 400, 0 means forever)") + print("-v verbose") + print("-V very verbose") import getopt, sys def main(): - n = 40000 + n = 400 dest = connection.testNodeAlias; verbose = False identifynode = False - + # argument processing try: opts, remainder = getopt.getopt(sys.argv[1:], "n:d:a:vVt", ["alias=", "dest=","num="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -57,14 +57,14 @@ def main(): retval = test(dest, connection, identifynode, n, verbose) connection.network.close() return retval - + def once(dest, connection, identifynode, verbose, marks) : alias = (dest-10)|1 # Note: This test assumes that the response will be # to reacquire another alias after the conflicted one is # dropped. This isn't required behavior by standard, but - # is a necessary condition for the test to continue and + # is a necessary condition for the test to continue and # check another conflict condition. # # Sending a global message (that normally doesn't get a response) @@ -72,23 +72,23 @@ def once(dest, connection, identifynode, verbose, marks) : connection.network.send(verifyNodeGlobal.makeframe(dest, [0,0,0,0,0,1])) reply = connection.network.receive() if reply == None : - print "no response received to conflict frame" + print("no response received to conflict frame") return -21 if not reply.startswith(":X10703") : - print "Expected first AMR" + print("Expected first AMR") return -22 reply = connection.network.receive() if reply == None : - print "no response received to conflict frame" + print("no response received to conflict frame") return -21 if not reply.startswith(":X17") : - print "Expected first CID" + print("Expected first CID") return -22 if int(reply[7:10],16) == 0 : - print "received alias == 0" + print("received alias == 0") return -24 if int(reply[7:10],16) == dest : - print "received alias == previous alias" + print("received alias == previous alias") # this is just noted, it doesnt end test dest = int(reply[7:10],16) marks.add(dest) @@ -102,7 +102,7 @@ def once(dest, connection, identifynode, verbose, marks) : reply = connection.network.receive() # VerifiedNID return dest - + def test(dest, connection, identifynode, n, verbose) : marks = set() if identifynode : @@ -110,15 +110,15 @@ def test(dest, connection, identifynode, n, verbose) : dest, otherNodeId = getUnderTestAlias.get(0x123, None, verbose) if n == 0 : - while dest >= 0 : + while dest >= 0 : dest = once(dest, connection, identifynode, verbose, marks) else : for i in range(n) : dest = once(dest, connection, identifynode, verbose, marks) if dest < 0 : return -dest - - if verbose : - print "covered", len(marks), "of 4095 in",n,"attempts" + + if verbose : + print("covered", len(marks), "of 4095 in",n,"attempts") return 0 if __name__ == '__main__': diff --git a/testOverlappingDatagrams.py b/testOverlappingDatagrams.py index 8d0e3fd..0687b5d 100755 --- a/testOverlappingDatagrams.py +++ b/testOverlappingDatagrams.py @@ -20,7 +20,7 @@ def makefirstframe(alias, dest, content) : def makemiddleframe(alias, dest, content) : return canolcbutils.makeframestring(0x1C000000+alias+(dest<<12),content) - + def makefinalframe(alias, dest, content) : return canolcbutils.makeframestring(0x1D000000+alias+(dest<<12),content) @@ -38,25 +38,25 @@ def isNAK(frame) : # frame = makeonlyframe(alias, dest, content) # connection.network.send(frame) # return -# +# # frame = makefirstframe(alias, dest, content[0:8]) # connection.network.send(frame) # content = content[8:] -# +# # while len(content) > 8 : # frame = makemiddleframe(alias, dest, content[0:8]) # connection.network.send(frame) # content = content[8:] -# +# # frame = makefinalframe(alias, dest, content) # connection.network.send(frame) -# +# # frame = connection.network.receive() # if frame == None : -# print "Did not receive reply" +# print ("Did not receive reply") # return 1 # if not isreply(frame) : -# print "Unexpected message received instead of reply" +# print ("Unexpected message received instead of reply") # return 2 # return 0 @@ -74,12 +74,12 @@ def receiveOneDatagram(alias, dest, conection, verbose) : if reply.startswith(":X1B"): retval = retval + canolcbutils.bodyArray(reply) else: - print "Unexpected message instead of first datagram segment", reply + print("Unexpected message instead of first datagram segment", reply) return 3 while True : reply = connection.network.receive() if (reply == None ) : - print "No datagram segment received" + print("No datagram segment received") return 4 elif reply.startswith(":X1C") : retval = retval + canolcbutils.bodyArray(reply) @@ -89,23 +89,23 @@ def receiveOneDatagram(alias, dest, conection, verbose) : connection.network.send(makereply(alias, dest)) return retval else : - print "Unexpected message instead of datagram segment", reply + print("Unexpected message instead of datagram segment", reply) return 3 def usage() : - print "" - print "Test of the specific case of overlapping datagrams," - print "created as part of the study of the missing start bit." - print "" - print "Sends enough datagrams to force a buffer-full reject message," - print "then checks processing of that." - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-b number of buffers to test (sends b+1 requests) default 1, -1 if node has variable number" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Test of the specific case of overlapping datagrams,") + print("created as part of the study of the missing start bit.") + print("") + print("Sends enough datagrams to force a buffer-full reject message,") + print("then checks processing of that.") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-b number of buffers to test (sends b+1 requests) default 1, -1 if node has variable number") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-t find destination alias automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -116,12 +116,12 @@ def main(): identifynode = False num = 1 verbose = False - + try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:b:vVt", ["dest=", "alias=", "content="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -148,73 +148,73 @@ def main(): retval = test(alias, dest, num, connection, verbose) connection.network.close() exit(retval) - + import datagram # Check for a reply datagram to a request, and check if it's basically OK def checkreply(alias, dest, connection, verbose) : frame = connection.network.receive() - if frame == None : - print "Did not receive reply" + if frame == None : + print("Did not receive reply") return 1 if not isACK(frame) : - print "Unexpected message received instead of reply" + print("Unexpected message received instead of reply") return 2 # read reply retval = receiveOneDatagram(alias, dest, connection, verbose) if retval == None : return 13 - if type(retval) is int : + if type(retval) is int : # pass error code up return retval if retval[0:3] != [0x20,0x51,0] : - print "Unexpected message instead of read reply datagram ", retval + print("Unexpected message instead of read reply datagram ", retval) return 3 # Check for a NAK datagram to a request, and check if it's basically OK def checkrejection(alias, dest, connection, verbose) : frame = connection.network.receive() if frame == None : - print "Did not receive reply" + print("Did not receive reply") return 1 if not isNAK(frame) : - print "Unexpected message received instead of NAK" + print("Unexpected message received instead of NAK") return 2 return 0 -def test(alias, dest, num, connection, verbose) : +def test(alias, dest, num, connection, verbose) : # num < 0 encodes "variable number of buffers, skip" - if num < 0 : - if verbose : print " skipping datagram parsing test" + if num < 0 : + if verbose : print(" skipping datagram parsing test") return # going to send a [0x20,0x41,0,0,0,0,8] read datagram in three parts: # [0x20] [0x41,0,0] [0,0,8] - if verbose : print " testing datagram parsing with ",num," buffer(s)" - - if connection.network.verbose : print " send initial frame from first source, plus",num,"more that should be ignored" + if verbose : print(" testing datagram parsing with ",num," buffer(s)") + + if connection.network.verbose : print(" send initial frame from first source, plus",num,"more that should be ignored") tempalias = alias for n in range(0,num+1) : connection.network.send(makefirstframe(tempalias, dest, [0x20])) tempalias = (tempalias + 1 ) & 0xFFF - if tempalias == dest : + if tempalias == dest : tempalias = (tempalias + 1 ) & 0xFFF - + # reply at this point should only be error to 2nd_or_later message, check for that frame = connection.network.receive() gotNAK = False # Assumes we only send one past the number of buffers if frame != None : if not (isNAK(frame) and (frame[15:17] == "20" or frame[15:17] == "60") ) : - print "expected NAK-buffer-unavailable reply to final frame of final datagram but received", frame + print("expected NAK-buffer-unavailable reply to final frame of final datagram but received", frame) return 81 # OK NAK, remember gotNAK = True - - - if connection.network.verbose : print " finish 1st datagram frames & check reply" + + + if connection.network.verbose : print(" finish 1st datagram frames & check reply") connection.network.send(makemiddleframe(alias, dest, [0x41,0,0])) connection.network.send(makefinalframe(alias, dest, [0,0,8])) # check response @@ -222,24 +222,24 @@ def test(alias, dest, num, connection, verbose) : if type(retval) is int and retval != 0 : return retval+20 - if connection.network.verbose : print " send intermediate frame of remaining",num,"datagram(s), expect no answers" + if connection.network.verbose : print(" send intermediate frame of remaining",num,"datagram(s), expect no answers") tempalias = alias for n in range(1,num+1) : tempalias = (tempalias + 1 ) & 0xFFF - if tempalias == dest : + if tempalias == dest : tempalias = (tempalias + 1 ) & 0xFFF connection.network.send(makemiddleframe(tempalias, dest, [0x41,0,0])) # do not expect reply at this point frame = connection.network.receive() if frame != None : - print "unexpected reply to middle segments", frame + print("unexpected reply to middle segments", frame) return 82 - - if connection.network.verbose : print " send final of other datagrams" + + if connection.network.verbose : print(" send final of other datagrams") tempalias = alias for n in range(1,num+1) : tempalias = (tempalias + 1 ) & 0xFFF - if tempalias == dest : + if tempalias == dest : tempalias = (tempalias + 1 ) & 0xFFF connection.network.send(makefinalframe(tempalias, dest, [0,0,8])) if n == num : @@ -247,15 +247,15 @@ def test(alias, dest, num, connection, verbose) : if gotNAK : continue frame = connection.network.receive() if frame == None : - print "missing reply to final segment" + print("missing reply to final segment") return 83 if not (isNAK(frame) and (frame[15:17] == "20" or frame[15:17] == "60") ) : - print "expected NAK-buffer-unavailable reply to final frame of final datagram but received", frame + print("expected NAK-buffer-unavailable reply to final frame of final datagram but received", frame) return 85 - else : - # expect it's OK before last - retval = checkreply(tempalias, dest, connection, verbose) - if type(retval) is int and retval != 0 : + else : + # expect it's OK before last + retval = checkreply(tempalias, dest, connection, verbose) + if type(retval) is int and retval != 0 : return retval+30 return 0 diff --git a/testProducerConsumerNotification.py b/testProducerConsumerNotification.py index e64ca19..74251c3 100755 --- a/testProducerConsumerNotification.py +++ b/testProducerConsumerNotification.py @@ -19,23 +19,23 @@ import identifyConsumers import identifyProducers - + def usage() : - print "" - print "Called standalone, will send one CAN IdentifyConsumers message" - print " and display response" - print "" - print "Expect zero or more ConsumerIdentified reply in return" - print "e.g. [1926Bsss] nn nn nn nn nn nn" - print "containing dest alias and EventID" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 123)" - print "-d --dest dest alias (default 123)" - print "-t find destination alias automatically" - print "-v verbose" - print "-V very verbose" + print ("") + print ("Called standalone, will send one CAN IdentifyConsumers message") + print (" and display response") + print ("") + print ("Expect zero or more ConsumerIdentified reply in return") + print ("e.g. [1926Bsss] nn nn nn nn nn nn") + print ("containing dest alias and EventID") + print ("") + print ("Default connection detail taken from connection.py") + print ("") + print ("-a --alias source alias (default 123)") + print ("-d --dest dest alias (default 123)") + print ("-t find destination alias automatically") + print ("-v verbose") + print ("-V very verbose") import getopt, sys @@ -44,13 +44,13 @@ def main(): dest = connection.testNodeAlias; verbose = False identifynode = False - + # argument processing try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:vVt", ["alias=", "dest="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print((str(err))) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -75,61 +75,76 @@ def main(): retval = test(alias, dest, connection, verbose) connection.network.close() return retval - + def test(alias, dest, connection, verbose) : # now execute connection.network.send(identifyEventsAddressed.makeframe(alias, dest)) consumed = [] produced = [] + retval = 0 + while (True) : reply = connection.network.receive() if (reply == None ) : break if ( reply.startswith(":X194C7") or reply.startswith(":X194C4") or reply.startswith(":X194C5") ): event = canolcbutils.bodyArray(reply) - if verbose : print " consumes ", event + if verbose : print((" consumes "+str(event))) consumed = consumed+[event] elif ( reply.startswith(":X19547") or reply.startswith(":X19544") or reply.startswith(":X19545") ): event = canolcbutils.bodyArray(reply) - if verbose : print " produces ", event + if verbose : print((" produces "+str(event))) produced = produced+[event] + # now check consumers and producers individually timeout = connection.network.timeout connection.network.timeout = 0.25 - if connection.network.verbose : print "Start individual checks" + if connection.network.verbose : print("Start individual checks") for c in consumed : + if verbose : print(("Check consumes "+str(c))) connection.network.send(identifyConsumers.makeframe(alias, c)) reply = connection.network.receive() - if (reply == None ) : - print "no reply for consumer ", c - return 20 - elif not ( reply.startswith(":X194C7") or reply.startswith(":X194C4") or reply.startswith(":X194C5") ): - print "Unexpected reply "+reply - return 21 + if (reply == None ) : + print(("no reply for consumer "+str(c))) + retval = retval +1 + continue + # accept all three states plus range reply + elif not ( reply.startswith(":X194C7") or reply.startswith(":X194C4") or reply.startswith(":X194C5") or reply.startswith(":X194A4") ): + print(("Unexpected reply "+reply)) + retval = retval +1 + continue # here is OK, go around to next while True : reply = connection.network.receive() if (reply == None ) : break elif ( not reply.startswith(":X194C7") ) : - print "Unexpected reply "+reply - return 22 + print(("Unexpected reply "+reply)) + retval = retval +1 + continue for p in produced : + if verbose : print(("Check produces "+str(p))) connection.network.send(identifyProducers.makeframe(alias, p)) reply = connection.network.receive() if (reply == None ) : - print "no reply for producer ", p - return 30 - elif not ( reply.startswith(":X19547") or reply.startswith(":X19544") or reply.startswith(":X19545") ): - print "Unexpected reply "+reply - return 31 + print(("no reply for producer "+str(p))) + retval = retval +1 + continue + # accept all three states plus range reply + elif not ( reply.startswith(":X19547") or reply.startswith(":X19544") or reply.startswith(":X19545") or reply.startswith(":X19524") ): + print(("Unexpected reply "+reply)) + retval = retval +1 + continue # here is OK, go around to next while True : reply = connection.network.receive() if (reply == None ) : break elif ( not reply.startswith(":X19547") ) : - print "Unexpected reply "+reply - return 32 + print(("Unexpected reply "+reply)) + retval = retval +1 + continue + connection.network.timeout = timeout - return 0 + + return retval if __name__ == '__main__': main() diff --git a/testReservedBits.py b/testReservedBits.py index c87c17c..c9cc0ac 100755 --- a/testReservedBits.py +++ b/testReservedBits.py @@ -12,18 +12,18 @@ def usage() : - print "" - print "Test that various reserved bits are not being (incorrectly) checked." - print "" - print "Relies on the node properly handling verifyNodeAddressed and verifyNodeGlobal" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 123)" - print "-n --node dest nodeID (default None, format 01.02.03.04.05.06)" - print "-t find NodeID automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Test that various reserved bits are not being (incorrectly) checked.") + print("") + print("Relies on the node properly handling verifyNodeAddressed and verifyNodeGlobal") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 123)") + print("-n --node dest nodeID (default None, format 01.02.03.04.05.06)") + print("-t find NodeID automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -37,9 +37,9 @@ def main(): try: opts, remainder = getopt.getopt(sys.argv[1:], "tn:a:vVd:", ["alias=", "node=", "dest="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -75,49 +75,49 @@ def makeAddressedFrame(alias, dest, nodeID) : return canolcbutils.makeframestring(0x09488000+alias,body) def test(alias, nodeID, dest, connection, verbose): - if verbose : print " test against verifyNodeGlobal" + if verbose : print(" test against verifyNodeGlobal") # first, send to this node connection.network.send(canolcbutils.makeframestring(0x09490000+alias,nodeID)) reply = connection.network.receive() if reply == None : - print "Global verify with matching node ID did not receive expected reply" + print("Global verify with matching node ID did not receive expected reply") return 2 elif not reply.startswith(":X19170") : - print "Global verify with matching node ID received wrong reply message", reply + print("Global verify with matching node ID received wrong reply message", reply) return 4 # send without node ID connection.network.send(canolcbutils.makeframestring(0x09490000+alias, None)) reply = connection.network.receive() if reply == None : - print "Global verify without node ID did not receive expected reply" + print("Global verify without node ID did not receive expected reply") return 12 elif not reply.startswith(":X19170") : - print "Global verify without node ID received wrong reply message ", reply + print("Global verify without node ID received wrong reply message ", reply) return 14 # send with wrong node ID connection.network.send(canolcbutils.makeframestring(0x09490000+alias, [0,0,0,0,0,1])) reply = connection.network.receive() if reply != None : - print "Global verify with wrong node ID should not receive reply but did: ", reply + print("Global verify with wrong node ID should not receive reply but did: ", reply) return 24 - if verbose : print " test against verifyNodeAddressed" + if verbose : print(" test against verifyNodeAddressed") connection.network.send(makeAddressedFrame(alias, dest, nodeID)) reply = connection.network.receive() if reply == None : - print "Expected reply not received" + print("Expected reply not received") return 2 elif not reply.startswith(":X19170") : - print "Unexpected reply received ", reply + print("Unexpected reply received ", reply) return 1 # try with invalid alias connection.network.send(makeAddressedFrame(alias, ~dest, nodeID)) reply = connection.network.receive() if reply != None : - print "Unexpected reply received ", reply + print("Unexpected reply received ", reply) return 1 return 0 diff --git a/testResponseTime.py b/testResponseTime.py index 4a9f134..81b59ee 100755 --- a/testResponseTime.py +++ b/testResponseTime.py @@ -22,18 +22,18 @@ def get(alias, nodeID) : return int(reply[7:10],16),canolcbutils.bodyArray(reply) def usage() : - print "" - print " Assumoing one under-test node present, uses " - print " one CAN VerifyNode (Global) message" - print " to get that node's alias " - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 123)" - print "-n --num number of cycles (default 100, 0 means forever)" - print "-p number of requests to send in parallel (default 1)" - print "-v verbose" - print "-V Very verbose" + print("") + print(" Assumoing one under-test node present, uses ") + print(" one CAN VerifyNode (Global) message") + print(" to get that node's alias ") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 123)") + print("-n --num number of cycles (default 100, 0 means forever)") + print("-p number of requests to send in parallel (default 1)") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -46,9 +46,9 @@ def main(): try: opts, remainder = getopt.getopt(sys.argv[1:], "h:p:n:a:vVp", ["alias=", "num=", "host=", "port="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -80,10 +80,10 @@ def once(alias, n, connection, verbose, parallel) : # skip reply = connection.network.receive() if reply == None : - print "No reply received" + print("No reply received") return 1 if not reply.startswith(":X180B7") : - print "Incorrect reply received" + print("Incorrect reply received") return 2 return 0 @@ -97,7 +97,7 @@ def test(alias, n, connection, verbose, parallel) : if retval != 0 : return retval end = time.time() if verbose : - print end-start + print(end-start) return 0 diff --git a/testStandardFrame.py b/testStandardFrame.py index 4632618..58a8b34 100755 --- a/testStandardFrame.py +++ b/testStandardFrame.py @@ -16,13 +16,13 @@ def makeframe(header) : return retval def usage() : - print "" - print "Sends standard-form CAN frames, checking for no reply" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-v verbose" - print "-V Very verbose" + print("") + print("Sends standard-form CAN frames, checking for no reply") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -32,9 +32,9 @@ def main(): try: opts, remainder = getopt.getopt(sys.argv[1:], "vV", []) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -59,7 +59,7 @@ def test(connection, verbose) : if reply == None : return 0 while reply != None : - print "Unexpected reply recieved to standard frame", hex(header), " was ", reply + print("Unexpected reply recieved to standard frame", hex(header), " was ", reply) reply = connection.network.receive() return 4 diff --git a/testStartup.py b/testStartup.py index 0720f83..b9b2f5b 100755 --- a/testStartup.py +++ b/testStartup.py @@ -26,18 +26,19 @@ import canolcbutils import time - +import sys + def usage() : - print "" - print "Called standalone, tests a nodes startup processing." - print "Reset the node (or force startup) after the script starts" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias" - print "-d --dest destination (target node) starting alias" - print "-v verbose" - print "-V very verbose" + print ("") + print ("Called standalone, tests a nodes startup processing.") + print ("Reset the node (or force startup) when prompted") + print ("") + print ("Default connection detail taken from connection.py") + print ("") + print ("-a --alias source alias") + print ("-d --dest destination (target node) starting alias") + print ("-v verbose") + print ("-V very verbose") import getopt, sys @@ -45,13 +46,13 @@ def main(): alias = connection.thisNodeAlias; dest = connection.testNodeAlias; verbose = False - + # argument processing try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:vV", ["alias=", "dest="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print (str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -69,152 +70,179 @@ def main(): retval = test(alias, dest, connection, verbose) connection.network.close() - return retval - + sys.exit(retval) + +# skip (return False) frames that are not from our desired under-test source alias +# and return ones that are +def getDutMessage(dest) : + reply = connection.network.receive() + while (reply != None and (int(reply[7:10],16))!= dest) : + print (" skipping "+reply); + reply = connection.network.receive() + return reply + def test(alias, dest, connection, verbose) : # wait for reset - - # expect RIF sequence (check timing) + + # expect RIF sequence after reset, check timing timeout = connection.network.timeout connection.network.timeout = 25 connection.network.connect() - if verbose : print "Restart node now" + + print ("Restart node now") + reply = connection.network.receive() - if verbose : print "Start checking node output" + if verbose : print ("Start checking node output") while (True) : if reply == None : - print "1st CIM reply not received, did you reset node?" + print ("1st CIM reply not received, did you reset node?") return 1 elif reply.startswith(":X17") : break elif reply.startswith(":X") : - if verbose: print "ignoring unexpected frame", reply + if verbose: print ("ignoring unexpected frame", reply) else : - if verbose: print "ignoring misc characters not a frame: ", reply + if verbose: print ("ignoring misc characters not a frame: ", reply) reply = connection.network.receive() - + + # this overrides pre-configuration, is that OK? + dest = int(reply[7:10],16) + connection.network.timeout = timeout testAlias = reply[7:10] if testAlias == "000" : - print "node using alias == 0" + print ("node using alias == 0") return 331 - + id = reply[4:7] start = time.time() - - reply = connection.network.receive() + + reply = getDutMessage(dest) if reply == None : - print "2nd CIM reply not received" + print ("2nd CIM reply not received") return 2 if reply[7:10] != testAlias : - print "mismatched 2nd CIM source alias" + print ("mismatched 2nd CIM source alias") return 12 if not reply.startswith(":X16") : - print "2nd CIM reply not correct" + print ("2nd CIM reply not correct") return 32 id = id+reply[4:7] - reply = connection.network.receive() + reply = getDutMessage(dest) if reply == None : - print "3rd CIM reply not received" + print ("3rd CIM reply not received") return 3 if reply[7:10] != testAlias : - print "mismatched 3rd CIM source alias" + print ("mismatched 3rd CIM source alias") return 13 if not reply.startswith(":X15") : - print "3rd CIM reply not correct" + print ("3rd CIM reply not correct") return 33 id = id+reply[4:7] - reply = connection.network.receive() + reply = getDutMessage(dest) if reply == None : - print "4th CIM reply not received" - return 4 + print ("4th CIM reply not received") + return (4) if reply[7:10] != testAlias : - print "mismatched 4th CIM source alias" - return 14 + print ("mismatched 4th CIM source alias") + return (14) if not reply.startswith(":X14") : - print "4th CIM reply not correct" - return 34 + print ("4th CIM reply not correct") + return (34) id = id+reply[4:7] - - # expect CIF (check timing) - connection.network.timeout = 1 - reply = connection.network.receive() + + # expect RIM (check timing) + connection.network.timeout = 1 + reply = getDutMessage(dest) end = time.time() connection.network.timeout = timeout if reply == None : - print "RIM reply not received" - return 5 + print ("RIM reply not received") + return (5) if not reply.startswith(":X10700") : - print "RIM reply not correct" - return 35 + print ("RIM reply not correct") + return (35) if reply[7:10] != testAlias : - print "mismatched RIM source alias" - return 15 + print ("mismatched RIM source alias") + return (15) - if verbose : print "delay was ", end-start + if verbose : print (" delay was ", end-start) if end-start < 0.15 : # some tolerance on check... - print "did not wait long enough ", end-start - return 22 + print ("did not wait long enough ", end-start) + return (22) if end-start > .55 : # some tolerance on check... - print "waited too long ", end-start - return 22 + print ("waited too long ", end-start) + return (22) # expect AMD - reply = connection.network.receive() + reply = getDutMessage(dest) if reply == None : - print "AMD reply not received" - return 6 + print ("AMD reply not received") + return (6) if not reply.startswith(":X10701") : - print "AMD reply not correct" - return 35 + print ("AMD reply not correct") + return (35) if reply[7:10] != testAlias : - print "mismatched AMD source alias" - return 16 + print ("mismatched AMD source alias") + return (16) if id != reply[11:23] : - print "AMD node ID ",reply[11:23]," did not match one in CID frames ",id - return 21 - + print ("AMD node ID ",reply[11:23],") did not match one in CID frames ",id) + return (21) + # expect NodeInit - reply = connection.network.receive() + reply = getDutMessage(dest) if reply == None : - print "NodeInit reply not received" + print ("NodeInit reply not received") return 7 if not reply.startswith(":X19100") : - print "NodeInit reply not correct" + print ("NodeInit reply not correct") return 37 if reply[7:10] != testAlias : - print "mismatched NodeInit source alias" + print ("mismatched NodeInit source alias") return 17 if id != reply[11:23] : - print "NodeInit node ID did not match",id, reply[11:23] - return 27 - - # expect one or more Produced/Consumed messages + print ("NodeInit node ID did not match",id, reply[11:23]) + return (27) + + # expect zero or more Produced/Consumed messages consumed = [] produced = [] - while (True) : - reply = connection.network.receive() + start = time.time() + while (time.time() - start < 5.0) : + reply = getDutMessage(dest) if (reply == None ) : break if (reply.startswith(":X194C")) : event = canolcbutils.bodyArray(reply) - if verbose : print "consumes ", event + if verbose : print ("consumes ", event) consumed = consumed+[event] + elif (reply.startswith(":X19524")) : + if verbose : print ("Producer Range Identified") + # we don't post-process these + elif (reply.startswith(":X194A4")) : + if verbose : print ("Consumer Range Identified") + # we don't post-process these elif (reply.startswith(":X1954")) : event = canolcbutils.bodyArray(reply) - if verbose : print "produces ", event + if verbose : print ("produces ", event) produced = produced+[event] elif (reply.startswith(":X195B4")) : event = canolcbutils.bodyArray(reply) - if verbose : print "event produced", event + if verbose : print ("event produced", event) + elif (reply.startswith(":X198F4")) : + event = canolcbutils.bodyArray(reply) + if verbose : print ("Identify Consumer request ", event) + elif (reply.startswith(":X19914")) : + event = canolcbutils.bodyArray(reply) + if verbose : print ("Identify Producer request ", event) else : - print "Unexpected message" - return 50 + print ("Unexpected message ", reply) + return (50) return 0 if __name__ == '__main__': diff --git a/unknownDatagramType.py b/unknownDatagramType.py index 46df61e..2be6aa6 100755 --- a/unknownDatagramType.py +++ b/unknownDatagramType.py @@ -9,19 +9,19 @@ import connection as connection import canolcbutils - + def usage() : - print "" - print "Called standalone, will scan unknown Datagram types" - print " and display response" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Called standalone, will scan unknown Datagram types") + print(" and display response") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-t find destination alias automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -33,12 +33,12 @@ def main(): dest = connection.testNodeAlias identifynode = False verbose = False - + try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:vVt", ["alias=", "dest="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -63,18 +63,18 @@ def main(): retval = test(alias, dest, connection, verbose) connection.network.close() exit(retval) - + def test(alias, dest, connection, verbose) : import datagram for type in range(0,256) : if type in knownType : continue connection.network.send(datagram.makeonlyframe(alias, dest, [type])) reply = connection.network.receive() - if reply == None : - print "Expected reply not received for", type + if reply == None : + print("Expected reply not received for "+str(type)) return 2 - if (not reply.startswith(":X19A48")) or reply[15:19] != "1040" : - print "Wrong reply received for", type + if (not reply.startswith(":X19A48")) : + print("Wrong reply "+reply+" received for "+str(type)) return 4 return 0 diff --git a/unknownMtiAddressed.py b/unknownMtiAddressed.py index 2d5a283..521ab31 100755 --- a/unknownMtiAddressed.py +++ b/unknownMtiAddressed.py @@ -12,28 +12,30 @@ def makeframe(alias, dest, mti) : return canolcbutils.makeframestring(0x19000000+alias+(mti<<12),[(dest>>8)&0xFF, dest&0xFF]) - + def usage() : - print "" - print "Called standalone, will send one CAN message with unknown MTI" - print " and display response" - print "" - print "Expect a single error reply in return" - print "e.g. [1Edddsss] 0C nn nn nn nn nn nn" - print "containing dest alias and error info" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-n --node dest nodeID (default 01.02.03.04.05.06)" - print "-t find destination alias automatically" - print "-v verbose" - print "-V Very verbose" + print("") + print("Called standalone, will send one CAN message with unknown MTI") + print(" and display response") + print("") + print("Expect a single error reply in return") + print("e.g. [1Edddsss] 0C nn nn nn nn nn nn") + print("containing dest alias and error info") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-n --node dest nodeID (default 01.02.03.04.05.06)") + print("-t find destination alias automatically") + print("-v verbose") + print("-V Very verbose") import getopt, sys -knownMti = [0x488, 0x068, 0x0A8, 0x828, 0x668, 0x968, 0x5EA, 0x1EA, 0x5E8, 0x1E8, 0x948, 0x949, 0xDA8, 0x9C8, 0xDE8, 0xA08, 0x1C48, 0xA28, 0xA48, 0xCC8, 0x868, 0x1F88, 0x888, 0x8A8] +knownMti = [0x488, 0x068, 0x0A8, 0x828, 0x668, 0x968, 0x5EA, 0x1EA, 0x5E8, 0x1E8, 0x948, + 0x949, 0xDA8, 0x9C8, 0xDE8, 0xA08, 0x1C48, 0xA28, 0xA48, 0xCC8, 0x868, 0x1F88, + 0x888, 0x8A8] def main(): # argument processing @@ -41,12 +43,12 @@ def main(): dest = connection.testNodeAlias identifynode = False verbose = False - + try: opts, remainder = getopt.getopt(sys.argv[1:], "d:a:vVt", ["alias=", "dest="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -71,19 +73,19 @@ def main(): retval = test(alias, dest, connection, verbose) connection.network.close() exit(retval) - + def test(alias, dest, connection, verbose) : for mti in range(0,4096) : if mti in knownMti : continue - if (mti&0x08) == 0 : continue + if (mti&0x08) == 0 : continue # global MTI, may not get reply frame = makeframe(alias, dest, mti) connection.network.send(frame) reply = connection.network.receive() - if reply == None : - print "No reply received for ", mti, "expected OIR" + if reply == None : + print("No reply received for "+hex(mti)+" expected OIR") return 2 - if (not reply.startswith(":X19068")) or reply[12:15] != frame[7:10] or reply[7:10] != frame[12:15] : - print "Wrong reply received for", mti, "was", reply + if (not reply.startswith(":X19068")) or reply[12:15] != frame[7:10] or reply[7:10] != frame[12:15] : + print("Wrong reply received for "+hex(mti)+" was "+reply) return 4 return 0 diff --git a/verifyNodeAddressed.py b/verifyNodeAddressed.py index c994a4d..b8debfa 100755 --- a/verifyNodeAddressed.py +++ b/verifyNodeAddressed.py @@ -10,6 +10,7 @@ import canolcbutils import copy +# create a VerifyNodeAddress message frame def makeframe(alias, dest, nodeID) : body = [(dest>>8)&0xFF, dest&0xFF] if nodeID != None : body = body+nodeID @@ -40,7 +41,7 @@ def main(): parser.add_option("-d", "--dest", dest="dest", metavar="ALIAS", default=connection.testNodeAlias, type = int, help="destination alias") - parser.add_option("-n", "--node", dest="nodeid", + parser.add_option("-n", "--node", dest="nodeID", metavar="0x1 0x2 0x3 0x4 0x5 0x6", default=connection.testNodeID, type=int, nargs=6, help="destination Node ID") @@ -59,64 +60,66 @@ def main(): if options.veryverbose : connection.network.verbose = True - - ''' - @todo identifynode option not currently implemented - ''' - #if identifynode : - # import getUnderTestAlias - # dest, otherNodeId = getUnderTestAlias.get(alias, None, verbose) - # if nodeID == None : nodeID = otherNodeId - - retval = test(options.alias, options.dest, options.nodeid, connection, + options.verbose = True + + if options.identifynode : + import getUnderTestAlias + options.dest, options.nodeID = getUnderTestAlias.get(options.alias, None, options.verbose or options.veryverbose) + + retval = test(options.alias, options.dest, options.nodeID, connection, options.verbose) connection.network.close() exit(retval) - + def test(alias, dest, nodeID, connection, verbose) : - # send correct address, correct node ID in body + retval = 0 + + if verbose : print ("send correct address, correct node ID in body") connection.network.send(makeframe(alias, dest, nodeID)) expect = canolcbutils.makeframestring(0x19170000 + dest, nodeID) - if (connection.network.expect(exact=expect) == None) : - print "Expected reply to correct alias & correct ID not received" - return 2 + if (connection.network.expect(startswith=expect) == None) : + print ("Expected reply "+expect+" to correct alias & correct ID not received") + retval = retval | 1 - # send correct address, no node ID in body + if verbose : print ("send correct address, no node ID in body") connection.network.send(makeframe(alias, dest, None)) if (connection.network.expect(startswith=":X19170", data=nodeID) == None) : - print "Expected reply to correct alias & no ID not received" - return 2 + print ("Expected reply not received to correct alias & no ID") + retval = retval | 2 - # send correct address, wrong node ID in body + if verbose : print ("send correct address, wrong node ID in body") tnodeID = copy.copy(nodeID) tnodeID[0] = tnodeID[0]^1 - connection.network.send(makeframe(alias, dest, tnodeID)) if (connection.network.expect(startswith=":X19170", data=nodeID) == None) : - print "Expected reply to correct alias & incorrect ID not received" - return 2 + print ("Expected reply not received to correct alias & incorrect ID") + retval = retval | 4 - # repeat all three with invalid alias + if verbose : print ("repeat all three with invalid alias") + + if verbose : print ("send correct address, correct node ID in body") connection.network.send(makeframe(alias, (~dest)&0xFFF, nodeID)) expect = canolcbutils.makeframestring(0x19170000 + dest, nodeID) - reply = connection.network.expect(exact=expect) + reply = connection.network.expect(startswith=expect) if (reply != None) : - print "Unexpected reply received on incorrect alias, OK nodeID", reply - return 1 - + print ("Unexpected reply received on incorrect alias, OK nodeID "+reply) + retval = retval | 8 + + if verbose : print ("send correct address, no node ID in body") connection.network.send(makeframe(alias, (~dest)&0xFFF, None)) reply = connection.network.expect(startswith=":X19170", data=nodeID) if (reply != None) : - print "Unexpected reply received on incorrect alias, no nodeID", reply - return 1 - + print ("Unexpected reply received on incorrect alias, no nodeID "+reply) + retval = retval | 16 + + if verbose : print ("send correct address, wrong node ID in body") connection.network.send(makeframe(alias, (~dest)&0xFFF, tnodeID)) reply = connection.network.expect(startswith=":X19170", data=nodeID) if (reply != None) : - print "Unexpected reply received on incorrect alias, wrong nodeID", reply - return 1 - - return 0 + print ("Unexpected reply received on incorrect alias, wrong nodeID "+reply) + retval = retvl | 32 + + return retval if __name__ == '__main__': main() diff --git a/verifyNodeGlobal.py b/verifyNodeGlobal.py index ca8f3b2..18ae470 100755 --- a/verifyNodeGlobal.py +++ b/verifyNodeGlobal.py @@ -23,6 +23,7 @@ def makeframe(alias, nodeID) : from optparse import OptionParser def main(): + # argument processing usage = "usage: %prog [options]\n\n" + \ "Called standalone, will send one CAN VerifyNode (Global) " + \ @@ -41,7 +42,7 @@ def main(): parser.add_option("-a", "--alias", dest="alias", metavar="ALIAS", default=connection.thisNodeAlias, type = int, help="source alias") - parser.add_option("-n", "--node", dest="nodeid", + parser.add_option("-n", "--node", dest="nodeID", metavar="0x1 0x2 0x3 0x4 0x5 0x6", default=connection.testNodeID, type=int, nargs=6, help="destination Node ID") @@ -61,31 +62,29 @@ def main(): if options.veryverbose : connection.network.verbose = True - ''' - @todo identifynode option not currently implemented - ''' - #if identifynode : - # import getUnderTestAlias - # dest, nodeID = getUnderTestAlias.get(alias, None, verbose) - # if nodeID == None : nodeID = otherNodeId + if options.identifynode : + import getUnderTestAlias + options.dest, options.nodeID = getUnderTestAlias.get(options.alias, None, options.verbose or options.veryverbose) # now execute - retval = test(options.alias, options.nodeid, connection) + retval = test(options.alias, options.nodeID, connection) connection.network.close() - exit(retval) - + exit(retval) + def test(alias, nodeID, connection): + retval = 0 + # first, send to this node connection.network.send(makeframe(alias, nodeID)) if (connection.network.expect(startswith=":X19170", data=nodeID) == None) : - print "Global verify with matching node ID did not receive expected reply" - return 2 + print ("Global verify with matching node ID did not receive expected reply") + retval = retval | 1 # send without node ID connection.network.send(makeframe(alias, None)) if (connection.network.expect(startswith=":X19170", data=nodeID) == None) : - print "Global verify without node ID did not receive expected reply" - return 12 + print ("Global verify without node ID did not receive expected reply") + retval = retval | 2 # allow time for the bus to settle time.sleep(3) @@ -95,11 +94,11 @@ def test(alias, nodeID, connection): # send with wrong node ID connection.network.send(makeframe(alias, [0,0,0,0,0,1])) reply = connection.network.expect(startswith=":X19170") - if (reply == None) : - return 0 - else : - print "Global verify with wrong node ID should not receive reply but did: ", reply - return 24 + if (reply != None) : + print ("Global verify with wrong node ID should not receive reply but did: ", reply) + rretval = retval | 4 + + return retval if __name__ == '__main__': main() diff --git a/verifyNodeGlobalTcp.py b/verifyNodeGlobalTcp.py index 8dceec9..559c375 100755 --- a/verifyNodeGlobalTcp.py +++ b/verifyNodeGlobalTcp.py @@ -15,19 +15,19 @@ def makeMessage(sourceNodeID, destNodeID) : return tcpolcbutils.makemessagestring(sourceNodeID, None, body) def usage() : - print "" - print "Called standalone, will send TCP VerifyNode (Global) message." - print "By default, this carries no Node ID information in the body, " - print "but if you supply the -n or --node option, it will be included." - print "" - print "Expect a single VerifiedNode reply in return" - print "containing destination NodeID" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-n --node dest nodeID (default None, format 01.02.03.04.05.06)" - print "-v verbose" - print "-V Very verbose" + print("") + print("Called standalone, will send TCP VerifyNode (Global) message.") + print("By default, this carries no Node ID information in the body, ") + print("but if you supply the -n or --node option, it will be included.") + print("") + print("Expect a single VerifiedNode reply in return") + print("containing destination NodeID") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-n --node dest nodeID (default None, format 01.02.03.04.05.06)") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -41,9 +41,9 @@ def main(): try: opts, remainder = getopt.getopt(sys.argv[1:], "tn:a:vV", ["alias=", "node="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: @@ -65,30 +65,30 @@ def main(): def test(sourceNodeID, destNodeID, connection, verbose): if verbose : - print "First message sent: "+tcpolcbutils.format(makeMessage(sourceNodeID, destNodeID)) + print("First message sent: "+tcpolcbutils.format(makeMessage(sourceNodeID, destNodeID))) # first, send with dest node's nodeID in data connection.network.send(makeMessage(sourceNodeID, destNodeID)) reply = connection.network.receive() if (reply == None ) : - print "Global verify with matching node ID did not receive expected reply" + print("Global verify with matching node ID did not receive expected reply") return 2 [transmitter, message] = reply [mti, source, dest, body] = tcpolcbutils.parseMessage(message) if not mti == 0x0170 : - print "Global verify with matching node ID received wrong reply message", tcpolcbutils.formatMessage(message) + print("Global verify with matching node ID received wrong reply message", tcpolcbutils.formatMessage(message)) return 4 # send without nodeID in data connection.network.send(makeMessage(sourceNodeID, None)) reply = connection.network.receive() if (reply == None ) : - print "Global verify without node ID did not receive expected reply" + print("Global verify without node ID did not receive expected reply") return 12 [transmitter, message] = reply [mti, source, dest, body] = tcpolcbutils.parseMessage(message) if not mti == 0x0170 : - print "Global verify without node ID received wrong reply message ", tcpolcbutils.formatMessage(message) + print("Global verify without node ID received wrong reply message ", tcpolcbutils.formatMessage(message)) return 14 # send with wrong node ID in data @@ -98,7 +98,7 @@ def test(sourceNodeID, destNodeID, connection, verbose): return 0 else : [transmitter, message] = reply - print "Global verify with wrong node ID should not receive reply but did: ", tcpolcbutils.formatMessage(message) + print("Global verify with wrong node ID should not receive reply but did: ", tcpolcbutils.formatMessage(message)) return 24 if __name__ == '__main__': diff --git a/writeConfiguration.py b/writeConfiguration.py index 48340c2..11827d7 100755 --- a/writeConfiguration.py +++ b/writeConfiguration.py @@ -10,20 +10,20 @@ import datagram def usage() : - print "" - print "Called standalone, will do one-byte memory write" - print " and display response" - print "" - print "Default connection detail taken from connection.py" - print "" - print "-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")" - print "-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")" - print "-s --space address space (default 254, configuration; CDI is 255, all-mem is 253)" - print "-t find destination alias automatically" - print "-A address (decimal, required)" - print "-D data (decimal, one byte, required)" - print "-v verbose" - print "-V Very verbose" + print("") + print("Called standalone, will do one-byte memory write") + print(" and display response") + print("") + print("Default connection detail taken from connection.py") + print("") + print("-a --alias source alias (default 0x"+hex(connection.thisNodeAlias).upper()+")") + print("-d --dest dest alias (default 0x"+hex(connection.testNodeAlias).upper()+")") + print("-s --space address space (default 254, configuration; CDI is 255, all-mem is 253)") + print("-t find destination alias automatically") + print("-A address (decimal, required)") + print("-D data (decimal, one byte, required)") + print("-v verbose") + print("-V Very verbose") import getopt, sys @@ -39,9 +39,9 @@ def main(): try: opts, remainder = getopt.getopt(sys.argv[1:], "A:D:s:d:a:c:vVt", ["space=", "dest=", "alias="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: