import threading
import ipdb
import connection
import logging

LOGGER = logging.getLogger(__name__)


ORIGINAL_RIDE = open('ride_data_0', 'r').read()
#INITIAL_RIDE = ORIGINAL_RIDE[:82+15*8] + ORIGINAL_RIDE[-15:]
INITIAL_RIDE = ORIGINAL_RIDE

class NewtonSimulator(threading.Thread):
	firmware_version = 6.12
	serial_number = '-'.join(['00'] * 16)
	def __init__(self, serial_connection=None):
		super(NewtonSimulator, self).__init__()
		if serial_connection is None:
			serial_connection = connection.NewtonSerialConnection()
		self.serial_connection = serial_connection
		self.protocol = None
		self.profiles = None
		self.reload = False
		self.init()

	def do_reload(self):
		self.reload = False
		reload(connection)
		self.init()

	def init(self):
		self.profiles = connection.NewtonProfile.from_binary_get_profile_result(INITIAL_PROFILE)
		self.rides = [connection.NewtonRide.from_binary(INITIAL_RIDE)]
		self.protocol = connection.NewtonSerialProtocol(self.serial_connection)

	def run(self):
		last_identifier = 0x09 # skip first firmware
		with self.serial_connection:
			while True:
				if self.reload:
					self.do_reload()
					break
				message = self.protocol.read_message()
				identifier = ord(message[0])
				data = message[1:]
				command = connection.NewtonCommand.MAP[identifier].parse(data)
				if (identifier, last_identifier) in [(0x09, 0x0e), (0x0e, 0x09)]:
					log = LOGGER.debug
					last_identifier = identifier
				else:
					log = LOGGER.info
				log("<- %r", command)
				response = command.get_response(self)
				log("-> %r", str(response)[:200])
				self.protocol.write_message(response)

if __name__ == '__main__':
	logging.basicConfig(level=logging.INFO)
	sim = NewtonSimulator()
	sim.setDaemon(True)
	sim.start()
	ipdb.set_trace()

@@ -54,16 +54,32 @@
  logging
+%0Aimport argparse
 %0A%0ALOGGER
@@ -1632,33 +1632,119 @@
 e)%0A%0A
-if __name__ == '__
+def arg_parser():%0A%09parser = argparse.ArgumentParser()%0A%09parser.add_argument('--port')%0A%09return parser%0A%0Adef 
 main
-__'
+()
 :%0A%09l
@@ -1782,16 +1782,172 @@
 g.INFO)%0A
+%09args = arg_parser().parse_args()%0A%09kwargs = %7B%7D%0A%09if args.port is not None:%0A%09%09kwargs%5B'serial_connection'%5D = connection.NewtonSerialConnection(port=args.port)%0A
 %09sim = N
@@ -1961,16 +1961,24 @@
 mulator(
+**kwargs
 )%0A%09sim.s
@@ -2019,12 +2019,48 @@
 set_trace()%0A
+%0Aif __name__ == '__main__':%0A%09main()%0A

allow port on simulator command line