Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add application restart command #1

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ See the [InfoCenter](https://infocenter.nordicsemi.com/topic/ug_nrfutil/UG/nrfut

Please report issues on the [DevZone](https://devzone.nordicsemi.com) portal.

## Tests

Unittests can be ran from project root directory with `python -m unittest discover -s test`.

## Contributing

Feel free to propose changes by creating a pull request.
Expand Down
66 changes: 66 additions & 0 deletions nordicsemi/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1500,6 +1500,72 @@ def zigbee():
"""
pass

@cli.group()
def restart():
"""
Utility command to restart dongle application.
"""
pass

@restart.command(short_help='Restart application on a device over a USB serial connection. The DFU '
'target must be a chip with USB pins (i.e. nRF52840) and provide a USB ACM '
'CDC serial interface.')
@click.option('-p', '--port',
help='Serial port address to which the device is connected. (e.g. COM1 in windows systems, /dev/ttyACM0 in linux/mac)',
type=click.STRING,
cls=OptionRequiredIf)
@click.option('-cd', '--connect-delay',
help='Delay in seconds before each connection to the target device during DFU. Default is 3.',
type=click.INT,
required=False,
default=3)
@click.option('-fc', '--flow-control',
help='To enable flow control set this flag to 1',
type=click.BOOL,
required=False)
@click.option('-prn', '--packet-receipt-notification',
help='Set the packet receipt notification value',
type=click.INT,
required=False)
@click.option('-b', '--baud-rate',
help='Set the baud rate',
type=click.INT,
required=False)
@click.option('-snr', '--serial-number',
help='Serial number of the device. Ignored if --port is set.',
type=click.STRING,
required=False)
@click.option('-t', '--timeout',
help='Set the timeout in seconds for board to respond (default: 30 seconds)',
type=click.INT,
required=False)
def usb_serial_restart(port, connect_delay, flow_control, packet_receipt_notification, baud_rate, serial_number,
timeout):
"""Perform an application restart"""
if flow_control is None:
flow_control = DfuTransportSerial.DEFAULT_FLOW_CONTROL
if packet_receipt_notification is None:
packet_receipt_notification = DfuTransportSerial.DEFAULT_PRN
if baud_rate is None:
baud_rate = DfuTransportSerial.DEFAULT_BAUD_RATE
if port is None:
device_lister = DeviceLister()
device = device_lister.get_device(serial_number=serial_number)
if device is None:
raise NordicSemiException("A device with serial number %s is not connected." % serial_number)
port = device.get_first_available_com_port()
logger.info("Resolved serial number {} to port {}".format(serial_number, port))

if timeout is None:
timeout = DfuTransportSerial.DEFAULT_TIMEOUT

logger.info("Using board at serial port: {}".format(port))
serial_backend = DfuTransportSerial(com_port=str(port), baud_rate=baud_rate,
flow_control=flow_control, prn=packet_receipt_notification, do_ping=False,
timeout=timeout, serial_number=serial_number)
Dfu.restart(serial_backend, connect_delay)
click.echo("Device restarted")


def _pretty_help_option(text: str):
formatted_lines = []
Expand Down
7 changes: 7 additions & 0 deletions nordicsemi/dfu/dfu.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,10 @@ def dfu_get_total_size(self):
self.manifest.application.bin_file))

return total_size

@staticmethod
def restart(dfu_transport, connect_delay):
time.sleep(connect_delay)
dfu_transport.open()
dfu_transport.exit_bootloader()
dfu_transport.close()
17 changes: 13 additions & 4 deletions nordicsemi/dfu/dfu_transport_serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ class DfuTransportSerial(DfuTransport):
'WriteObject' : 0x08,
'Ping' : 0x09,
'Response' : 0x60,
'Abort' : 0x0C,
}

def __init__(self,
Expand All @@ -173,7 +174,8 @@ def __init__(self,
flow_control=DEFAULT_FLOW_CONTROL,
timeout=DEFAULT_TIMEOUT,
prn=DEFAULT_PRN,
do_ping=DEFAULT_DO_PING):
do_ping=DEFAULT_DO_PING,
serial_number=None):

super().__init__()
self.com_port = com_port
Expand All @@ -185,6 +187,7 @@ def __init__(self,
self.dfu_adapter = None
self.ping_id = 0
self.do_ping = do_ping
self.serial_number = serial_number

self.mtu = 0

Expand Down Expand Up @@ -220,6 +223,9 @@ def close(self):
super().close()
self.serial_port.close()

def exit_bootloader(self):
self.dfu_adapter.send_message([DfuTransportSerial.OP_CODE['Abort']])

def send_init_packet(self, init_packet):
def try_to_recover():
if response['offset'] == 0 or response['offset'] > len(init_packet):
Expand Down Expand Up @@ -312,14 +318,17 @@ def __ensure_bootloader(self):
start = datetime.now()
while not device and datetime.now() - start < timedelta(seconds=self.timeout):
time.sleep(0.5)
device = lister.get_device(com=self.com_port)
if self.serial_number:
device = lister.get_device(serial_number=self.serial_number)
else:
device = lister.get_device(com=self.com_port)

if device:
device_serial_number = device.serial_number

if not self.__is_device_in_bootloader_mode(device):
retry_count = 10
wait_time_ms = 500
wait_time_ms = 2000

trigger = DFUTrigger()
try:
Expand All @@ -331,7 +340,7 @@ def __ensure_bootloader(self):

for checks in range(retry_count):
logger.info("Serial: Waiting {} ms for device to enter bootloader {}/{} time"\
.format(500, checks + 1, retry_count))
.format(wait_time_ms, checks + 1, retry_count))

time.sleep(wait_time_ms / 1000.0)

Expand Down
2 changes: 0 additions & 2 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
-r requirements.txt
behave
nose
pyinstaller
19 changes: 0 additions & 19 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
import sys

from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand

from nordicsemi import version

Expand Down Expand Up @@ -123,17 +122,6 @@
reqs = reqs_file.readlines()


class NoseTestCommand(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True

def run_tests(self):
import nose
nose.run_exit(argv=['nosetests', '--with-xunit', '--xunit-file=unittests.xml'])


setup(
name="nrfutil",
version=version.NRFUTIL_VERSION,
Expand All @@ -151,10 +139,6 @@ def run_tests(self):
python_requires='>=3.7, <3.11',
install_requires=reqs,
zipfile=None,
tests_require=[
"nose >= 1.3.4",
"behave"
],
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
Expand All @@ -177,9 +161,6 @@ def run_tests(self):
'Programming Language :: Python :: 3.10',
],
keywords='nordic nrf51 nrf52 ble bluetooth dfu ota softdevice serialization nrfutil pc-nrfutil',
cmdclass={
'test': NoseTestCommand
},
entry_points='''
[console_scripts]
nrfutil = nordicsemi.__main__:cli
Expand Down