Exemple #1
0
    def __init__(self):
        #I am not shure this is correct. According to docs, you do not instantate a logger.
        os.system('sudo ifconfig wlan0 down')  # Can't have this up at comp
        logging.basicConfig(filename="../logs/runLogs.log",
                            level=logging.DEBUG)

        logging.debug("\n--------------------New run------------------")
        logging.debug("Run started at: ")
        logging.debug(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
        logging.debug("---------------------------------------------\n")
        self.windowName = "picamera"
        self.target = comm.Target()
        self.commChan = None
        self.parseArgs()
        print("testPCam pid: %d args:" % os.getpid())
        print(self.args)
        print("OpenCV version: {}".format(cv2.__version__))

        if self.args.robot != "none":
            if self.args.robot == "roborio":
                logging.debug(
                    datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
                logging.debug("Connecting to robot at 10.49.15.2...")
                ip = "10.49.15.2"
            else:
                ip = "localhost"
            print("starting comm to " + ip)
            self.commChan = comm.Comm(ip)

        self.picam = picam.PiCam(resolution=(self.args.iwidth,
                                             self.args.iheight),
                                 framerate=(self.args.fps))
        # Push something down the pipe.
        self.commChan.SetTarget(self.target)
    def __init__(self):

        self._ser = comm.Comm(
        )  #serial.Serial(port=dev, baudrate=57600, timeout=1.0)
        #self._queue = queue.LifoQueue(1)
        self._runEn = False
        self._dataCallBack = self._debugCallBack
        self._configCallBack = None
        self._file = None
        self._last = None

        self._respRate = 0
        self._inhTime = 0
        self._pipMax = 0
        self._pipOffset = 0
        self._volMax = 0
        self._volFactor = 0
        self._volInThold = 0
        self._peepMin = 0
        self._runState = 0

        self._status = 0
        self._prevmillis = 0
        self._stime = 0
        self._smillis = -1
        self._refresh = time.time()
        self._version = 'unknown'
        self._cpuid = [0] * 4
        self.artime = 0
        self._tOffset = 0
        self._timestamp = time.time()
        self._cfgSerialNum = 0
        self._queue = None

        self._data = npfifo.npfifo(9, 6000)
Exemple #3
0
 def __init__(self):
     Thread.__init__(self)
     self.scheduler = Scheduler()
     self.comm = comm.Comm()
     self.money = Money()
     self.status = BOX_INIT
     self.button = NO_BUTTON
     self.products = Products()
Exemple #4
0
    def __init__(self):

        self.commChan = None
        self.parseArgs()

        #   logger init:
        #     - we write logging info to file, for performance this should be
        #       minimized.
        #     - during debugging, set the loglevel to debug and see the 'spew'
        #       via:  "tail -f /tmp/runPiCam.log"
        if self.args.debug:
            logLevel = logging.DEBUG
        else:
            logLevel = logging.INFO

        logging.basicConfig(
            level=logLevel,
            format="%(asctime)s %(levelname)-6s: %(message)s",
            datefmt="%m/%d %H:%M:%S",
            # This file is avible to write to, even when the pi is in 'read-only' mode
            filename="/tmp/runPiCam.log",
            filemode="a")
        logging.info("--------------------New run------------------")
        logging.info("pid: %d" % os.getpid())
        logging.info("args: " + str(self.args))
        logging.info("opencv version: {}".format(cv2.__version__))
        logging.debug("Parsed the following args:")
        logging.debug(self.args)

        if self.args.robot != "none":
            if self.args.robot == "roborio":
                fmt = "%Y/%m/%d %H:%M:%S"
                logging.debug(datetime.datetime.now().strftime(fmt))
                logging.debug("Connecting to robot at 10.49.15.2...")
                ip = "10.49.15.2"
            else:
                ip = self.args.robot
            logging.info("starting comm to " + ip)
            self.commChan = comm.Comm(ip)

        # parameter configuration -----
        self.config = getattr(config, self.args.config)  # reads named dict
        self.picam = picam.PiCam(self.config["picam"])
        self.algoConfig = self.config["algo"]
        # Updating config with passed commands
        # XXX: Need logic to check if these values exist in the chosen config
        #      Unsure if an error will be thrown
        # Overriding config values with passed values
        if (self.args.display):
            self.algoConfig["display"] = True

        if (self.args.algo is not None):
            self.algoConfig["algo"] = self.args.algo
Exemple #5
0
    def __init__(self, gui):
        # The current open design
        self.design = None

        self.gui = gui
        self.timer = None
        self.comm = comm.Comm()

        # A list of folder mappings for the source code.
        # This is useful if you are debugging on a different file
        # system than where the compile was done.
        self.folder_mapping = {}

        # Debugging state
        self._currentState = (None, None)
        self._executionMode = backend.BACKEND_FPGA_LIVE
        self._instruction_mode = None

        # Trigger functions
        self.executionModeChanged = signals.Signal()
        self.stateChanged = signals.Signal()
        self.comm_disconnected = signals.Signal()
        self.traceMaxChanged = signals.Signal()
        self.designClosed = signals.Signal()
        self.designOpened = signals.Signal()
        self.errorOccurred = signals.Signal()
        self.minorMessage = signals.Signal()
        self.majorMessage = signals.Signal()
        self.enteringLongWork = signals.Signal()
        self.leavingLongWork = signals.Signal()

        # Initialize back-ends
        self.backends = {}
        self.backends[backend.BACKEND_FPGA_LIVE] = hardware.Hardware(self)
        self.backends[backend.BACKEND_FPGA_REPLAY] = replay.Replay(self)
        self.backends[backend.BACKEND_MODELSIM] = sim.Simulate(self)

        #       self.instruction_mode = self.DEFAULT_INSTRUCTION_MODE

        #       self.backends[self.executionMode].updateState()

        if self.gui:
            self.timer = QtCore.QTimer()
            self.timer.setInterval(self.TIMER_INTERVAL * 1000)
            self.timer.timeout.connect(self.timer_timeout)
            self.timer.start()
Exemple #6
0
    def __init__(self):
        self.windowName = "picamera"
        self.target = comm.Target()
        self.commChan = None
        self.parseArgs()
        print("testPCam pid: %d args:" % os.getpid())
        print(self.args)
        print("OpenCV version: {}".format(cv2.__version__))

        if self.args.robot != "none":
            if self.args.robot == "roborio":
                ip = "10.49.15.2"
            else:
                ip = "localhost"
            print("starting comm on " + ip)
            self.commChan = comm.Comm(ip)

        self.picam = picam.PiCam(resolution=(self.args.iwidth,
                                             self.args.iheight),
                                 framerate=(self.args.fps))
Exemple #7
0
    def __init__(self):

        self.commChan = None
        self.parseArgs()

        #   logger init:
        #     - we write logging info to file, for performance this should be
        #       minimized.
        #     - during debugging, set the loglevel to debug and see the 'spew'
        #       via:  "tail -f /tmp/runPiCam.log"
        if self.args.debug:
            logLevel = logging.DEBUG
        else:
            logLevel = logging.INFO

        logging.basicConfig(level=logLevel,
                            format="%(asctime)s %(levelname)-6s: %(message)s",
                            datefmt="%m/%d %H:%M:%S",
                            filename="/tmp/runPiCam.log",
                            filemode="a")
        logging.info("--------------------New run------------------")
        logging.info("pid: %d" % os.getpid())
        logging.info("args: " + str(self.args))
        logging.info("opencv version: {}".format(cv2.__version__))
        logging.debug("Parsed the following args:")
        logging.debug(self.args)

        if self.args.robot != "none":
            if self.args.robot == "roborio":
                fmt = "%Y/%m/%d %H:%M:%S"
                logging.debug(datetime.datetime.now().strftime(fmt))
                logging.debug("Connecting to robot at 10.49.15.2...")
                ip = "10.49.15.2"
            else:
                ip = self.args.robot
            logging.info("starting comm to " + ip)
            self.commChan = comm.Comm(ip)

        # parameter configuration -----
        self.config = getattr(config, self.args.config)  # reads named dict
        self.picam = picam.PiCam(self.config["picam"])
Exemple #8
0
def main():
    global s_args
    global s_comm
    global s_config
    try:
        parser = argparse.ArgumentParser(
            description="Start the picam streamer")
        parser.add_argument("--robot",
                            dest="robot",
                            help="robot (none, localhost, roborio) [none]",
                            default="none")
        parser.add_argument("--debug",
                            dest="debug",
                            help="debug: [0,1] ",
                            default=0)
        parser.add_argument("--config",
                            dest="config",
                            help="config: default,greenled,noled...",
                            default="default")
        s_args = parser.parse_args()
        s_config = getattr(config, s_args.config)
        if s_args.robot != "none":
            if s_args.robot == "roborio":
                ip = "10.49.15.2"
            else:
                ip = s_args.robot
            s_comm = comm.Comm(ip)
        logFmt = "streamer %(levelname)-6s %(message)s"
        dateFmt = "%H:%M"
        if s_args.debug:
            loglevel = logging.DEBUG
        else:
            loglevel = logging.INFO
        logging.basicConfig(level=loglevel, format=logFmt, datefmt=dateFmt)
        server = HTTPServer(('', 5080), CamHandler)
        logging.info("server started with config " + s_args.config)
        server.serve_forever()
    except KeyboardInterrupt:
        logging.warning("aborting server")
        server.socket.close()
Exemple #9
0
getRotateCorners,\
getLocalTranslation,\
rotateLocalTranslation,\
getGlobalTranslation,\
sortRects,\
getLocalRotateType
from util import mapToWorld, mapToImage, deg
from math import sin, cos
import preprocess

import comm
import protocol

draw = True

mycomm = comm.Comm(print)

protocol.init(mycomm)

sensor.reset()
# grayscale is faster (160x120 max on OpenMV-M7)
# sensor.set_pixformat(sensor.RGB565)
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(time=2000)
clock = time.clock()

size = [160, 120]
Size = [280, 240]

equations = []
Exemple #10
0
import comm
import logging
import time

logging.basicConfig(level=logging.DEBUG)

print("starting comm")
c = comm.Comm("localhost")  # connect to fake robot on localhost
t = comm.Target()

threshold = time.clock() - .01

while True:
    now = time.clock()
    if now > threshold:
        print(".")
        t.clock = now
        threshold = now + .01  # 100 hz
        if t.angleX == None:
            t.angleX = 0
            t.angleY = 0
        else:
            t.angleX += 1
            t.angleY -= 1
        c.SetTarget(t)
Exemple #11
0
    else:
        logf = None

    start_time = time.time()

    print('Initializing communications on {} {} ...'.format(
        args.port, args.baud))
    if args.port.upper() == 'MOCK':
        import mock

        # unless we are reading out the chip firmware read a new file to load
        with open('mock.hex') as fp:
            mock_firmware = intelhex.Hexfile()
            mock_firmware.read(fp)

        ser = mock.ICSPHost('12F1822', mock_firmware)
    else:
        import serial

        ser = serial.Serial(args.port,
                            baudrate=args.baud,
                            bytesize=DATA,
                            timeout=TOUT)

    # create wrapper
    with comm.Comm(ser, logf) as ser_com:
        print(ser_com)
        program(ser_com)

    print(f"elapsed time: {time.time() - start_time:0.2f} seconds")
Exemple #12
0
def main(portName1, simulated):
    print "INITIALIZING TORSO..."

    ###Connection with ROS
    rospy.init_node("torso")

    jointStates = JointState()
    jointStates.name = [
        "spine_connect", "waist_connect", "shoulders_connect",
        "shoulders_left_connect", "shoulders_right_connect"
    ]
    jointStates.position = [0.0, 0.0, 0.0, 0.0, 0.0]

    pubTorsoPos = rospy.Publisher("/hardware/torso/current_pose",
                                  Float32MultiArray,
                                  queue_size=1)
    pubGoalReached = rospy.Publisher("/hardware/torso/goal_reached",
                                     Bool,
                                     queue_size=1)
    pubJointStates = rospy.Publisher("/joint_states", JointState, queue_size=1)
    pubStop = rospy.Publisher("robot_state/stop", Empty, queue_size=1)
    pubEmergencyStop = rospy.Publisher("robot_state/emergency_stop",
                                       Bool,
                                       queue_size=1)
    subRelativeHeight = rospy.Subscriber("/hardware/torso/goal_rel_pose",
                                         Float32MultiArray, callbackRelative)
    subAbsoluteHeight = rospy.Subscriber("/hardware/torso/goal_pose",
                                         Float32MultiArray, callbackAbsolute)
    subStop = rospy.Subscriber("robot_state/stop", Empty, callbackStop)
    subEmergencyStop = rospy.Subscriber("robot_state/emergency_stop", Bool,
                                        callbackEmergency)
    subTorsoUp = rospy.Subscriber("/hardware/torso/torso_up", String,
                                  callbackTorsoUp)
    subTorsoDown = rospy.Subscriber("/hardware/torso/torso_down", String,
                                    callbackTorsoDown)

    rate = rospy.Rate(ITER_RATE)
    global valueRel
    global valueAbs
    global absH
    global relH
    global stop
    global torsoUp
    global torsoDown
    global eme_stop
    global new_eme_msg_recv

    valueAbs = False
    valueRel = False
    torsoUp = False
    torsoDown = False
    torsoPos = 0
    bumper = 0
    stop = False
    msgCurrentPose = Float32MultiArray()
    msgGoalReached = Bool()
    msgCurrentPose.data = [0, 0, 0]
    msgMotor = None
    initTimeMtrMsg = datetime.now()
    initTimeSnrMsg = datetime.now()
    timeoutSnr = 0
    timeoutMtr = 0
    ArdIfc = comm.Comm(portName1)
    msgSensor = comm.Msg(comm.ARDUINO_ID, comm.MOD_SENSORS,
                         comm.OP_GETCURRENTDIST, [], 0)
    ArdIfc.send(msgSensor)
    goalPose = 0
    new_eme_msg_recv = False
    eme_stop = Bool()
    eme_stop.data = False
    while not rospy.is_shutdown():
        try:
            timeoutSnr = datetime.now() - initTimeSnrMsg
            if timeoutSnr.microseconds > MSG_SENSOR_TIMEOUT:
                ArdIfc.send(msgSensor)
                initTimeSnrMsg = datetime.now()
            newMsg = ArdIfc.recv()
            if newMsg != None:
                if newMsg.mod == comm.MOD_SENSORS:
                    if newMsg.op == comm.OP_GETCURRENTDIST:
                        torsoPos = newMsg.param[0]
                        #rospy.loginfo("Torso-> Arduino ack GET CURRENT DIST msg received.")
                if newMsg.mod == comm.MOD_SYSTEM:
                    if newMsg.op == comm.OP_PING:
                        rospy.loginfo("Torso-> Arduino ack PING msg received.")
                    if newMsg.op == comm.OP_STOP:
                        rospy.loginfo(
                            "Torso-> Arduino Emercenty STOP system received.  "
                        )
                        if eme_stop.data != bool(newMsg.param[0]):
                            eme_stop.data = newMsg.param[0]
                            pubEmergencyStop.publish(eme_stop)
                if newMsg.mod == comm.MOD_MOTORS:
                    if newMsg.op == comm.OP_SETTORSOPOSE:
                        msgMotor_ack_received = True
                        rospy.loginfo(
                            "Torso-> Arduino ack SETTORSOPOSE msg received.")
                    if newMsg.op == comm.OP_GOUP:
                        msgMotor_ack_received = True
                        rospy.loginfo("Torso-> Arduino ack GOUP msg received.")
                    if newMsg.op == comm.OP_GODOWN:
                        msgMotor_ack_received = True
                        rospy.loginfo(
                            "Torso-> Arduino ack GODOWN msg received.")
                    if newMsg.op == comm.OP_STOP_MOTOR:
                        msgMotor_ack_received = True
                        #rospy.loginfo("Torso-> Arduino ack STOP MOTOR msg received.")

            #until ack received
            timeoutMtr = datetime.now() - initTimeMtrMsg
            if msgMotor != None and timeoutMtr.microseconds > MSG_MOTOR_TIMEOUT and not msgMotor_ack_received:
                ArdIfc.send(msgMotor)
                initTimeMtrMsg = datetime.now()

            if valueAbs and not eme_stop.data and absH >= DIST_LIM_INF and absH <= DIST_LIM_SUP:
                msgMotor_ack_received = False
                msgMotor = comm.Msg(comm.ARDUINO_ID, comm.MOD_MOTORS,
                                    comm.OP_SETTORSOPOSE, int(absH), 1)
                ArdIfc.send(msgMotor)
                valueAbs = False
                goalPose = absH
                initTimeMtrMsg = datetime.now()
            elif valueRel and not eme_stop.data and (
                    torsoPos + relH) >= DIST_LIM_INF and (
                        torsoPos + relH) <= DIST_LIM_SUP:
                msgMotor_ack_received = False
                absCalH = torsoPos + relH
                msgMotor = comm.Msg(comm.ARDUINO_ID, comm.MOD_MOTORS,
                                    comm.OP_SETTORSOPOSE, int(absCalH), 1)
                ArdIfc.send(msgMotor)
                goalPose = absCalH
                valueRel = False
                initTimeMtrMsg = datetime.now()
            elif (valueAbs and
                  (absH < DIST_LIM_INF or absH > DIST_LIM_SUP)) or (
                      valueRel and (torsoPos + relH > DIST_LIM_SUP
                                    or torsoPos + relH < DIST_LIM_INF)):
                rospy.logerr("Torso-> Can not reach te position.")
                valueAbs = False
                valueRel = False
                goalPose = torsoPos
            elif torsoUp and not eme_stop.data:
                rospy.loginfo("Torso-> Moving torso up.")
                msgMotor = comm.Msg(comm.ARDUINO_ID, comm.MOD_MOTORS,
                                    comm.OP_GOUP, [], 0)
                ArdIfc.send(msgMotor)
                torsoUp = False
                msgMotor_ack_received = False
                initTimeMtrMsg = datetime.now()
                goalPose = torsoPos
            elif torsoDown and not eme_stop.data:
                rospy.loginfo("Torso-> Moving torso down.")
                msgMotor = comm.Msg(comm.ARDUINO_ID, comm.MOD_MOTORS,
                                    comm.OP_GODOWN, [], 0)
                ArdIfc.send(msgMotor)
                torsoDown = False
                msgMotor_ack_received = False
                initTimeMtrMsg = datetime.now()
                goalPose = torsoPos
            elif eme_stop.data and new_eme_msg_recv:
                rospy.loginfo("Torso-> Stop message.")
                msgMotor = comm.Msg(comm.ARDUINO_ID, comm.MOD_MOTORS,
                                    comm.OP_STOP_MOTOR, [], 0)
                ArdIfc.send(msgMotor)
                msgMotor_ack_received = False
                initTimeMtrMsg = datetime.now()
                new_eme_msg_recv = False
                torsoDown = False
                torsoUp = False
                valueAbs = False
                valueRel = False

            jointStates.header.stamp = rospy.Time.now()
            jointStates.position = [(torsoPos - TORSO_ADJUSTMENT) / 100.0, 0.0,
                                    0.0, 0.0, 0.0]
            pubJointStates.publish(jointStates)

            msgCurrentPose.data[0] = (torsoPos - TORSO_ADJUSTMENT) / 100.0
            msgCurrentPose.data[1] = 0.0
            msgCurrentPose.data[2] = 0.0
            pubTorsoPos.publish(msgCurrentPose)
            msgGoalReached.data = abs(goalPose - torsoPos) < THR_DIFF_POS
            pubGoalReached.publish(msgGoalReached)

            rate.sleep()
        except:
            rospy.logerr(
                "Torso-> Oopps...we have some issues in this node :( ")
Exemple #13
0
def main():
    parser = argparse.ArgumentParser(prog='flash',
                                     description='icsp programming tool.')
    parser.add_argument('-p',
                        '--port',
                        default=DEFAULT_PORT,
                        help='serial device')
    parser.add_argument('-b', '--baud', default=DEFAULT_BAUD, help='baud rate')

    group = parser.add_mutually_exclusive_group()
    group.add_argument('-i',
                       '--id',
                       action='store_true',
                       help='read chip id info from target')
    group.add_argument('-w',
                       '--write',
                       action='store_true',
                       help='write firmware to target')
    group.add_argument('-r',
                       '--read',
                       action='store_true',
                       help='Read target and save to file')

    parser.add_argument('-1',
                        '--mclr1',
                        action='store_true',
                        help="use mclr1 for 28 pin chips")
    parser.add_argument('-q',
                        '--quiet',
                        action='store_true',
                        help="quiet mode. don't dump hex files")
    parser.add_argument('-e',
                        '--enh',
                        action='store_true',
                        help='Enhanced midrange programming method')
    parser.add_argument('-f',
                        '--fast',
                        action='store_true',
                        help='Fast mode.  Do minimal verification')
    parser.add_argument('-l',
                        '--log',
                        nargs='?',
                        const='bload.log',
                        default=None,
                        help='Log all I/O to file')
    parser.add_argument('-t', '--test', action='store_true', help='Test')
    parser.add_argument(
        '--version',
        action='version',
        version='$Id: flash.py 740 2017-11-25 02:25:22Z rnee $')
    parser.add_argument('filename',
                        default=None,
                        nargs='?',
                        action='store',
                        help='HEX filename')

    args = parser.parse_args()

    args.write = not args.read and not args.id

    if args.log:
        if os.path.exists(args.log):
            os.unlink(args.log)
        logf = open(args.log, 'a')
    else:
        logf = None
    # logf = sys.stdout

    # Check for a filename
    if not args.id and args.filename is None:
        parser.print_help()
        sys.exit()

    # unless we are reading out the chip firmware read a new file to load
    if not args.read and not args.id:
        with open(args.filename) as fp:
            file_firmware = intelhex.Hexfile()
            file_firmware.read(fp)
            if not args.quiet:
                print(args.filename)
                print(file_firmware.display())
    else:
        file_firmware = None

    # Init comm (holds target in reset)
    print(f'Initializing communications on {args.port} at {args.baud} ...')
    if MOCK:
        # read firmware to simulate target and load and create mock target
        firmware = intelhex.Hexfile()
        with open(TMP + 'icsp.hex') as fp:
            firmware.read(fp)

        ser = mock.ICSPHost(firmware)
    else:
        ser = serial.Serial(args.port,
                            baudrate=args.baud,
                            bytesize=DATA,
                            timeout=TOUT)

    # Create wrapper
    com = comm.Comm(ser, logf)

    # Bring target out of reset
    print('Reset...')
    time.sleep(0.050)
    com.pulse_dtr(0.250)
    time.sleep(0.050)

    # Trigger and look for prompt
    for _ in range(5):
        com.flush()
        com.write(b'K')
        (count, value) = com.read(1)
        if value == b'K':
            break
    else:
        com.close()

        print(f'[{count}, {value}] Could not find ICSP on {args.port}\n')
        sys.exit()

    print('Connected...')

    # flush input buffer so that we can start out synchronized
    com.flush()

    # Get host controller version
    print('Getting Version...')
    ver = icsp.get_version(com)
    print('KT150 firmware version:', ver)

    display_status(com)

    if args.mclr1:
        print('Start using MCLR1...')
        send_start1(com)
    else:
        print('Start using MCLR2...')
        send_start2(com)

    icsp.sync(com)
    display_status(com)

    print("\nDevice Info:")
    chip_id, cfg1, cfg2, cal1, cal2 = read_info(com)

    # enhanced and midrange have different id/rev bits
    for mask, shift in ((0x00F, 4), (0x01F, 5)):
        device_id = chip_id >> shift
        device_rev = chip_id & mask

        if device_id in picdevice.PARAM:
            break
    else:
        print(" ID: %04X not in device list" % chip_id)

        print("End...")
        icsp.release(com)

        sys.exit()

    device_param = picdevice.PARAM[device_id]
    device_name = device_param['name']

    print(f" ID: {device_id:04X} {device_name} rev {device_rev:02X}")
    print(f"CFG: {cfg1:04X} {cfg2:04X}")
    print(f"CAL: {cal1:04X} {cal2:04X}")

    # Set ranges and addresses based on the bootloader config and device information
    min_page = 0
    max_page = device_param['max_page']
    min_data = device_param['min_data']
    max_data = device_param['max_data']
    conf_page_num = device_param['conf_page']

    if args.read:
        print("Reset Address...")
        icsp.reset_address(com)

        print("Reading Firmware...")
        chip_firmware = read_firmware(com, device_param)
        print()

        with open(args.filename, mode='w') as fp:
            chip_firmware.write(fp)

        if not args.quiet:
            print(chip_firmware.display())
    elif args.write:
        # Erase entire device including userid locations
        print("Erase Device...")
        icsp.load_config(com)
        icsp.erase_program(com)
        icsp.erase_data(com)

        icsp.reset_address(com)

        sys.stderr.flush()
        print(f"Writing Program 0x0 .. 0x{max_page:#0X} ...")
        icsp.write_program_pages(com, file_firmware, device_param)

        print(f"Writing Data {min_data:#0X} .. {max_data:#0X} ...")
        icsp.write_data_pages(com, file_firmware, device_param)

        print("Writing Config 0x%X ..." % conf_page_num)
        icsp.reset_address(com)
        icsp.write_config(com, file_firmware, device_param)

        print("Reading Firmware...")
        icsp.reset_address(com)
        verify_firmware = read_firmware(com, device_param)
        print()

        # Compare protected regions to ensure they are compatible
        print("Comparing firmware pages 0x%X .. 0x%X, 0x%X .. 0x%X, 0x%X..." %
              (min_page, max_page, min_data, max_data, conf_page_num))
        check_list = list(range(min_page, max_page + 1)) + list(
            range(min_data, max_data)) + [conf_page_num]
        error_list = file_firmware.compare(verify_firmware, check_list)

        if error_list:
            print("\nWARNING!\nError verifying firmware.")

            for page_num in error_list:
                if file_firmware[page_num]:
                    print("File:")
                    print(file_firmware[page_num].display(page_num))
                if verify_firmware[page_num]:
                    print("Chip:")
                    print(verify_firmware[page_num].display(page_num))
        else:
            print(" OK")

    print("End...")
    icsp.release(com)

    com.close()
Exemple #14
0
if __name__ == "__main__":

    import logging

    manager = Manager()
    import json

    state = manager.dict()
    state['time'] = time.time()
    state['log_lvl'] = zlog.DEBUG

    import worker1

    import comm
    comm_obj = comm.Comm()

    # short cuts
    dm = msg_que.demux_lst
    mx = msg_que.mux_lst

    proc_lst = [{
        'target': comm_obj.incoming,
        'args': (),
        'kwargs': {
            'state': state
        },
        'name': 'incoming'
    }, {
        'target': comm_obj.outgoing,
        'args': (),
import sys
sys.path.append("python_client")
import comm
import message
import time


c=comm.Comm()
c.connect()

print("Found device id=%s, port=%s" % (c.id,c.port))

run=True
count=0
first=0
last=0
start=0
while (run):
    line=c.readPacket()
    if(line is None): continue
    m=message.Message()
    try:
        m.decode(line)
    except:
        continue
    if(m.status!=m.ERR_OK): continue
    if(m.id == m.DATA and m.nFloat==5 and m.nInt==2):
        if(count==0): 
            first=m.millis
            start=time.time()
        count=count+1
Exemple #16
0
def run(argv=None):
    parser = argparse.ArgumentParser(
        prog='pyload', description='pyload Bload bootloader tool.')
    parser.add_argument('-p',
                        '--port',
                        default=DEFAULT_PORT,
                        help=f'serial device ({DEFAULT_PORT})')
    parser.add_argument('-b', '--baud', default=DEFAULT_BAUD, help='baud rate')
    parser.add_argument('-q',
                        '--quiet',
                        action='store_true',
                        help='quiet mode. dont dump hex files')
    parser.add_argument('-c',
                        '--cdef',
                        action='store_true',
                        help='Convert filename to C definition statements')
    parser.add_argument('-f',
                        '--fast',
                        action='store_true',
                        help='Fast mode.  Do minimal verification')
    parser.add_argument('-r',
                        '--read',
                        action='store_true',
                        help='Read target and save to filename')
    parser.add_argument('-x',
                        '--reset',
                        action='store_true',
                        help='Reset target and exit')
    parser.add_argument('-t',
                        '--term',
                        action='store_true',
                        help='Start terminal mode after processing')
    parser.add_argument('-l',
                        '--log',
                        nargs='?',
                        const='bload.log',
                        default=None,
                        help='Log all I/O to file')
    parser.add_argument(
        '--version',
        action='version',
        version='$Id: pyload.py 901 2018-04-28 21:44:56Z rnee $')

    parser.add_argument('filename',
                        default=None,
                        nargs='?',
                        action='store',
                        help='HEX filename')

    args = parser.parse_args(args=argv if argv else sys.argv[1:])

    # reading and fast mode are incompatible
    if args.read and args.fast:
        parser.print_help()
        sys.exit()

    if args.log:
        if os.path.exists(args.log):
            os.unlink(args.log)
        logf = open(args.log, 'a')
    else:
        logf = None

    print('Initializing communications on {} {} ...'.format(
        args.port, args.baud))
    if args.port.upper() == 'MOCK':
        import mock

        # unless we are reading out the chip firmware read a new file to load
        with open('mock.hex') as fp:
            mock_firmware = intelhex.Hexfile()
            mock_firmware.read(fp)

        ser = mock.BLoadHost('12F1822', mock_firmware)
    else:
        import serial

        ser = serial.Serial(args.port,
                            baudrate=args.baud,
                            bytesize=DATA,
                            timeout=TOUT)

    # create wrapper
    with comm.Comm(ser, logf) as ser_com:
        if args.reset:
            ser_com.pulse_dtr(0.250)
            if args.term:
                term.terminal(ser_com)

        # Check for commands that require a filename
        if args.filename is not None:
            program(ser_com, args)

        if args.term:
            ser_com.pulse_dtr(0.250)
            term.terminal(ser_com)