INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
Translates the given address to another address specific to network or service.
:param address: (:class:`~hazelcast.core.Address`), private address to be translated
:return: (:class:`~hazelcast.core.Address`), new address if given address is known, otherwise returns null | def translate(self, address):
"""
Translates the given address to another address specific to network or service.
:param address: (:class:`~hazelcast.core.Address`), private address to be translated
:return: (:class:`~hazelcast.core.Address`), new address if given address is known, otherwise returns null
"""
if address is None:
return None
public_address = self._private_to_public.get(address)
if public_address:
return public_address
self.refresh()
return self._private_to_public.get(address) |
Refreshes the internal lookup table if necessary. | def refresh(self):
"""
Refreshes the internal lookup table if necessary.
"""
try:
self._private_to_public = self.cloud_discovery.discover_nodes()
except Exception as ex:
self.logger.warning("Failed to load addresses from Hazelcast.cloud: {}".format(ex.args[0]),
extra=self._logger_extras) |
Helper method to get host and url that can be used in HTTPSConnection.
:param properties: Client config properties.
:param cloud_token: Cloud discovery token.
:return: Host and URL pair | def get_host_and_url(properties, cloud_token):
"""
Helper method to get host and url that can be used in HTTPSConnection.
:param properties: Client config properties.
:param cloud_token: Cloud discovery token.
:return: Host and URL pair
"""
host = properties.get(HazelcastCloudDiscovery.CLOUD_URL_BASE_PROPERTY.name,
HazelcastCloudDiscovery.CLOUD_URL_BASE_PROPERTY.default_value)
host = host.replace("https://", "")
host = host.replace("http://", "")
return host, HazelcastCloudDiscovery._CLOUD_URL_PATH + cloud_token |
Calculates the request payload size | def calculate_size(name, message):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_data(message)
return data_size |
Event handler | def handle(client_message, handle_event_partition_lost=None, to_object=None):
""" Event handler """
message_type = client_message.get_message_type()
if message_type == EVENT_PARTITIONLOST and handle_event_partition_lost is not None:
partition_id = client_message.read_int()
lost_backup_count = client_message.read_int()
source = None
if not client_message.read_bool():
source = AddressCodec.decode(client_message, to_object)
handle_event_partition_lost(partition_id=partition_id, lost_backup_count=lost_backup_count, source=source) |
Calculates the request payload size | def calculate_size(name, timeout_millis):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
return data_size |
Calculates the request payload size | def calculate_size(name, txn_id, thread_id, key, old_value, new_value):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_str(txn_id)
data_size += LONG_SIZE_IN_BYTES
data_size += calculate_size_data(key)
data_size += calculate_size_data(old_value)
data_size += calculate_size_data(new_value)
return data_size |
Calculates the request payload size | def calculate_size(name, thread_id):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
return data_size |
Calculates the request payload size | def calculate_size(uuid, address, interrupt):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(uuid)
data_size += calculate_size_address(address)
data_size += BOOLEAN_SIZE_IN_BYTES
return data_size |
Encode request into client_message | def encode_request(uuid, address, interrupt):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(uuid, address, interrupt))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(uuid)
AddressCodec.encode(client_message, address)
client_message.append_bool(interrupt)
client_message.update_frame_length()
return client_message |
Sets the count to the given value if the current count is zero. If count is not zero, this method does nothing
and returns ``false``.
:param count: (int), the number of times count_down() must be invoked before threads can pass through await().
:return: (bool), ``true`` if the new count was set, ``false`` if the current count is not zero. | def try_set_count(self, count):
"""
Sets the count to the given value if the current count is zero. If count is not zero, this method does nothing
and returns ``false``.
:param count: (int), the number of times count_down() must be invoked before threads can pass through await().
:return: (bool), ``true`` if the new count was set, ``false`` if the current count is not zero.
"""
check_not_negative(count, "count can't be negative")
return self._encode_invoke(count_down_latch_try_set_count_codec, count=count) |
Destroys this proxy.
:return: (bool), ``true`` if this proxy is deleted successfully, ``false`` otherwise. | def destroy(self):
"""
Destroys this proxy.
:return: (bool), ``true`` if this proxy is deleted successfully, ``false`` otherwise.
"""
self._on_destroy()
return self._client.proxy.destroy_proxy(self.service_name, self.name) |
Calculates the request payload size | def calculate_size(name, delta):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
return data_size |
Adds a membership listener to listen for membership updates, it will be notified when a member is added to
cluster or removed from cluster. There is no check for duplicate registrations, so if you register the listener
twice, it will get events twice.
:param member_added: (Function), function to be called when a member is added to the cluster (optional).
:param member_removed: (Function), function to be called when a member is removed to the cluster (optional).
:param fire_for_existing: (bool), (optional).
:return: (str), registration id of the listener which will be used for removing this listener. | def add_listener(self, member_added=None, member_removed=None, fire_for_existing=False):
"""
Adds a membership listener to listen for membership updates, it will be notified when a member is added to
cluster or removed from cluster. There is no check for duplicate registrations, so if you register the listener
twice, it will get events twice.
:param member_added: (Function), function to be called when a member is added to the cluster (optional).
:param member_removed: (Function), function to be called when a member is removed to the cluster (optional).
:param fire_for_existing: (bool), (optional).
:return: (str), registration id of the listener which will be used for removing this listener.
"""
registration_id = str(uuid.uuid4())
self.listeners[registration_id] = (member_added, member_removed)
if fire_for_existing:
for member in self.get_member_list():
member_added(member)
return registration_id |
Removes the specified membership listener.
:param registration_id: (str), registration id of the listener to be deleted.
:return: (bool), if the registration is removed, ``false`` otherwise. | def remove_listener(self, registration_id):
"""
Removes the specified membership listener.
:param registration_id: (str), registration id of the listener to be deleted.
:return: (bool), if the registration is removed, ``false`` otherwise.
"""
try:
self.listeners.pop(registration_id)
return True
except KeyError:
return False |
Returns the member with specified member uuid.
:param member_uuid: (int), uuid of the desired member.
:return: (:class:`~hazelcast.core.Member`), the corresponding member. | def get_member_by_uuid(self, member_uuid):
"""
Returns the member with specified member uuid.
:param member_uuid: (int), uuid of the desired member.
:return: (:class:`~hazelcast.core.Member`), the corresponding member.
"""
for member in self.get_member_list():
if member.uuid == member_uuid:
return member |
Returns the members that satisfy the given selector.
:param selector: (:class:`~hazelcast.core.MemberSelector`), Selector to be applied to the members.
:return: (List), List of members. | def get_members(self, selector):
"""
Returns the members that satisfy the given selector.
:param selector: (:class:`~hazelcast.core.MemberSelector`), Selector to be applied to the members.
:return: (List), List of members.
"""
members = []
for member in self.get_member_list():
if selector.select(member):
members.append(member)
return members |
Returns true if this vector clock is causally strictly after the
provided vector clock. This means that it the provided clock is neither
equal to, greater than or concurrent to this vector clock.
:param other: (:class:`~hazelcast.cluster.VectorClock`), Vector clock to be compared
:return: (bool), True if this vector clock is strictly after the other vector clock, False otherwise | def is_after(self, other):
"""
Returns true if this vector clock is causally strictly after the
provided vector clock. This means that it the provided clock is neither
equal to, greater than or concurrent to this vector clock.
:param other: (:class:`~hazelcast.cluster.VectorClock`), Vector clock to be compared
:return: (bool), True if this vector clock is strictly after the other vector clock, False otherwise
"""
any_timestamp_greater = False
for replica_id, other_timestamp in other.entry_set():
local_timestamp = self._replica_timestamps.get(replica_id)
if local_timestamp is None or local_timestamp < other_timestamp:
return False
elif local_timestamp > other_timestamp:
any_timestamp_greater = True
# there is at least one local timestamp greater or local vector clock has additional timestamps
return any_timestamp_greater or other.size() < self.size() |
Determines whether this set contains the specified item or not.
:param item: (object), the specified item to be searched.
:return: (bool), ``true`` if the specified item exists in this set, ``false`` otherwise. | def contains(self, item):
"""
Determines whether this set contains the specified item or not.
:param item: (object), the specified item to be searched.
:return: (bool), ``true`` if the specified item exists in this set, ``false`` otherwise.
"""
check_not_none(item, "Value can't be None")
item_data = self._to_data(item)
return self._encode_invoke(set_contains_codec, value=item_data) |
Determines whether this set contains all of the items in the specified collection or not.
:param items: (Collection), the specified collection which includes the items to be searched.
:return: (bool), ``true`` if all of the items in the specified collection exist in this set, ``false`` otherwise. | def contains_all(self, items):
"""
Determines whether this set contains all of the items in the specified collection or not.
:param items: (Collection), the specified collection which includes the items to be searched.
:return: (bool), ``true`` if all of the items in the specified collection exist in this set, ``false`` otherwise.
"""
check_not_none(items, "Value can't be None")
data_items = []
for item in items:
check_not_none(item, "Value can't be None")
data_items.append(self._to_data(item))
return self._encode_invoke(set_contains_all_codec, items=data_items) |
Removes the specified item listener. Returns silently if the specified listener was not added before.
:param registration_id: (str), id of the listener to be deleted.
:return: (bool), ``true`` if the item listener is removed, ``false`` otherwise. | def remove_listener(self, registration_id):
"""
Removes the specified item listener. Returns silently if the specified listener was not added before.
:param registration_id: (str), id of the listener to be deleted.
:return: (bool), ``true`` if the item listener is removed, ``false`` otherwise.
"""
return self._stop_listening(registration_id, lambda i: set_remove_listener_codec.encode_request(self.name, i)) |
Calculates the request payload size | def calculate_size(name, expected, updated):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
data_size += LONG_SIZE_IN_BYTES
return data_size |
Encode request into client_message | def encode_request(name, expected, updated):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, expected, updated))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.append_long(expected)
client_message.append_long(updated)
client_message.update_frame_length()
return client_message |
Calculates the request payload size | def calculate_size(name, interceptor):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_data(interceptor)
return data_size |
Calculates the request payload size | def calculate_size(name, uuid, callable, partition_id):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_str(uuid)
data_size += calculate_size_data(callable)
data_size += INT_SIZE_IN_BYTES
return data_size |
Encode request into client_message | def encode_request(name, uuid, callable, partition_id):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, uuid, callable, partition_id))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.append_str(uuid)
client_message.append_data(callable)
client_message.append_int(partition_id)
client_message.update_frame_length()
return client_message |
Alters the currently stored value by applying a function on it.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with the actual
``org.hazelcast.core.IFunction`` implementation. | def alter(self, function):
"""
Alters the currently stored value by applying a function on it.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with the actual
``org.hazelcast.core.IFunction`` implementation.
"""
check_not_none(function, "function can't be None")
return self._encode_invoke(atomic_long_alter_codec, function=self._to_data(function)) |
Alters the currently stored value by applying a function on it and gets the result.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with the actual
``org.hazelcast.core.IFunction`` implementation.
:return: (long), the new value. | def alter_and_get(self, function):
"""
Alters the currently stored value by applying a function on it and gets the result.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with the actual
``org.hazelcast.core.IFunction`` implementation.
:return: (long), the new value.
"""
check_not_none(function, "function can't be None")
return self._encode_invoke(atomic_long_alter_and_get_codec, function=self._to_data(function)) |
Applies a function on the value, the actual stored value will not change.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with the actual
``org.hazelcast.core.IFunction`` implementation.
:return: (object), the result of the function application. | def apply(self, function):
"""
Applies a function on the value, the actual stored value will not change.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with the actual
``org.hazelcast.core.IFunction`` implementation.
:return: (object), the result of the function application.
"""
check_not_none(function, "function can't be None")
return self._encode_invoke(atomic_long_apply_codec, function=self._to_data(function)) |
Atomically sets the value to the given updated value only if the current value == the expected value.
:param expected: (long), the expected value.
:param updated: (long), the new value.
:return: (bool), ``true`` if successful; or ``false`` if the actual value was not equal to the expected value. | def compare_and_set(self, expected, updated):
"""
Atomically sets the value to the given updated value only if the current value == the expected value.
:param expected: (long), the expected value.
:param updated: (long), the new value.
:return: (bool), ``true`` if successful; or ``false`` if the actual value was not equal to the expected value.
"""
return self._encode_invoke(atomic_long_compare_and_set_codec, expected=expected,
updated=updated) |
Alters the currently stored value by applying a function on it on and gets the old value.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with the actual
``org.hazelcast.core.IFunction`` implementation.
:return: (long), the old value. | def get_and_alter(self, function):
"""
Alters the currently stored value by applying a function on it on and gets the old value.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with the actual
``org.hazelcast.core.IFunction`` implementation.
:return: (long), the old value.
"""
check_not_none(function, "function can't be None")
return self._encode_invoke(atomic_long_get_and_alter_codec, function=self._to_data(function)) |
Calculates the request payload size | def calculate_size(name, key):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_data(key)
return data_size |
Prints the core's information.
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error | def main(jlink_serial, device):
"""Prints the core's information.
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error
"""
buf = StringIO.StringIO()
jlink = pylink.JLink(log=buf.write, detailed_log=buf.write)
jlink.open(serial_no=jlink_serial)
# Use Serial Wire Debug as the target interface.
jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
jlink.connect(device, verbose=True)
sys.stdout.write('ARM Id: %d\n' % jlink.core_id())
sys.stdout.write('CPU Id: %d\n' % jlink.core_cpu())
sys.stdout.write('Core Name: %s\n' % jlink.core_name())
sys.stdout.write('Device Family: %d\n' % jlink.device_family()) |
Attempts to acquire a lock for the J-Link lockfile.
If the lockfile exists but does not correspond to an active process,
the lockfile is first removed, before an attempt is made to acquire it.
Args:
self (Jlock): the ``JLock`` instance
Returns:
``True`` if the lock was acquired, otherwise ``False``.
Raises:
OSError: on file errors. | def acquire(self):
"""Attempts to acquire a lock for the J-Link lockfile.
If the lockfile exists but does not correspond to an active process,
the lockfile is first removed, before an attempt is made to acquire it.
Args:
self (Jlock): the ``JLock`` instance
Returns:
``True`` if the lock was acquired, otherwise ``False``.
Raises:
OSError: on file errors.
"""
if os.path.exists(self.path):
try:
pid = None
with open(self.path, 'r') as f:
line = f.readline().strip()
pid = int(line)
# In the case that the lockfile exists, but the pid does not
# correspond to a valid process, remove the file.
if not psutil.pid_exists(pid):
os.remove(self.path)
except ValueError as e:
# Pidfile is invalid, so just delete it.
os.remove(self.path)
except IOError as e:
# Something happened while trying to read/remove the file, so
# skip trying to read/remove it.
pass
try:
self.fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_RDWR)
# PID is written to the file, so that if a process exits wtihout
# cleaning up the lockfile, we can still acquire the lock.
to_write = '%s%s' % (os.getpid(), os.linesep)
os.write(self.fd, to_write.encode())
except OSError as e:
if not os.path.exists(self.path):
raise
return False
self.acquired = True
return True |
Cleans up the lockfile if it was acquired.
Args:
self (JLock): the ``JLock`` instance
Returns:
``False`` if the lock was not released or the lock is not acquired,
otherwise ``True``. | def release(self):
"""Cleans up the lockfile if it was acquired.
Args:
self (JLock): the ``JLock`` instance
Returns:
``False`` if the lock was not released or the lock is not acquired,
otherwise ``True``.
"""
if not self.acquired:
return False
os.close(self.fd)
if os.path.exists(self.path):
os.remove(self.path)
self.acquired = False
return True |
Starts the SWD transaction.
Steps for a Write Transaction:
1. First phase in which the request is sent.
2. Second phase in which an ACK is received. This phase consists of
three bits. An OK response has the value ``1``.
3. Everytime the SWD IO may change directions, a turnaround phase is
inserted. For reads, this happens after the data phase, while
for writes this happens after between the acknowledge and data
phase, so we have to do the turnaround before writing data. This
phase consists of two bits.
4. Write the data and parity bits.
Args:
self (WriteRequest): the ``WriteRequest`` instance
jlink (JLink): the ``JLink`` instance to use for write/read
Returns:
An ``Response`` instance. | def send(self, jlink):
"""Starts the SWD transaction.
Steps for a Write Transaction:
1. First phase in which the request is sent.
2. Second phase in which an ACK is received. This phase consists of
three bits. An OK response has the value ``1``.
3. Everytime the SWD IO may change directions, a turnaround phase is
inserted. For reads, this happens after the data phase, while
for writes this happens after between the acknowledge and data
phase, so we have to do the turnaround before writing data. This
phase consists of two bits.
4. Write the data and parity bits.
Args:
self (WriteRequest): the ``WriteRequest`` instance
jlink (JLink): the ``JLink`` instance to use for write/read
Returns:
An ``Response`` instance.
"""
ack = super(WriteRequest, self).send(jlink)
# Turnaround phase for write.
jlink.swd_write(0x0, 0x0, 2)
# Write the data and the parity bits.
jlink.swd_write32(0xFFFFFFFF, self.data)
jlink.swd_write8(0xFF, util.calculate_parity(self.data))
return Response(jlink.swd_read8(ack) & 7) |
Starts the SWD transaction.
Steps for a Read Transaction:
1. First phase in which the request is sent.
2. Second phase in which an ACK is received. This phase consists of
three bits. An OK response has the value ``1``.
3. Once the ACK is received, the data phase can begin. Consists of
``32`` data bits followed by ``1`` parity bit calclulated based
on all ``32`` data bits.
4. After the data phase, the interface must be clocked for at least
eight cycles to clock the transaction through the SW-DP; this is
done by reading an additional eight bits (eight clocks).
Args:
self (ReadRequest): the ``ReadRequest`` instance
jlink (JLink): the ``JLink`` instance to use for write/read
Returns:
An ``Response`` instance. | def send(self, jlink):
"""Starts the SWD transaction.
Steps for a Read Transaction:
1. First phase in which the request is sent.
2. Second phase in which an ACK is received. This phase consists of
three bits. An OK response has the value ``1``.
3. Once the ACK is received, the data phase can begin. Consists of
``32`` data bits followed by ``1`` parity bit calclulated based
on all ``32`` data bits.
4. After the data phase, the interface must be clocked for at least
eight cycles to clock the transaction through the SW-DP; this is
done by reading an additional eight bits (eight clocks).
Args:
self (ReadRequest): the ``ReadRequest`` instance
jlink (JLink): the ``JLink`` instance to use for write/read
Returns:
An ``Response`` instance.
"""
ack = super(ReadRequest, self).send(jlink)
# Write the read command, then read the data and status.
jlink.swd_write32(0x0, 0x0)
jlink.swd_write8(0xFC, 0x0)
status = jlink.swd_read8(ack) & 7
data = jlink.swd_read32(ack + 3)
if status == Response.STATUS_ACK:
# Check the parity
parity = jlink.swd_read8(ack + 35) & 1
if util.calculate_parity(data) != parity:
return Response(-1, data)
return Response(status, data) |
Creates a console progress bar.
This should be called in a loop to create a progress bar.
See `StackOverflow <http://stackoverflow.com/questions/3173320/>`__.
Args:
iteration (int): current iteration
total (int): total iterations
prefix (str): prefix string
suffix (str): suffix string
decs (int): positive number of decimals in percent complete
length (int): character length of the bar
Returns:
``None``
Note:
This function assumes that nothing else is printed to the console in the
interim. | def progress_bar(iteration,
total,
prefix=None,
suffix=None,
decs=1,
length=100):
"""Creates a console progress bar.
This should be called in a loop to create a progress bar.
See `StackOverflow <http://stackoverflow.com/questions/3173320/>`__.
Args:
iteration (int): current iteration
total (int): total iterations
prefix (str): prefix string
suffix (str): suffix string
decs (int): positive number of decimals in percent complete
length (int): character length of the bar
Returns:
``None``
Note:
This function assumes that nothing else is printed to the console in the
interim.
"""
if prefix is None:
prefix = ''
if suffix is None:
suffix = ''
format_str = '{0:.' + str(decs) + 'f}'
percents = format_str.format(100 * (iteration / float(total)))
filled_length = int(round(length * iteration / float(total)))
bar = '█' * filled_length + '-' * (length - filled_length)
prefix, suffix = prefix.strip(), suffix.strip()
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix))
sys.stdout.flush()
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
return None |
Callback that can be used with ``JLink.flash()``.
This callback generates a progress bar in the console to show the progress
of each of the steps of the flash.
Args:
action (str): the current action being invoked
progress_string (str): the current step in the progress
percentage (int): the percent to which the current step has been done
Returns:
``None``
Note:
This function ignores the compare action. | def flash_progress_callback(action, progress_string, percentage):
"""Callback that can be used with ``JLink.flash()``.
This callback generates a progress bar in the console to show the progress
of each of the steps of the flash.
Args:
action (str): the current action being invoked
progress_string (str): the current step in the progress
percentage (int): the percent to which the current step has been done
Returns:
``None``
Note:
This function ignores the compare action.
"""
if action.lower() != 'compare':
return progress_bar(min(100, percentage), 100, prefix=action)
return None |
Calculates and returns the parity of a number.
The parity of a number is ``1`` if the number has an odd number of ones
in its binary representation, otherwise ``0``.
Args:
n (int): the number whose parity to calculate
Returns:
``1`` if the number has an odd number of ones, otherwise ``0``.
Raises:
ValueError: if ``n`` is less than ``0``. | def calculate_parity(n):
"""Calculates and returns the parity of a number.
The parity of a number is ``1`` if the number has an odd number of ones
in its binary representation, otherwise ``0``.
Args:
n (int): the number whose parity to calculate
Returns:
``1`` if the number has an odd number of ones, otherwise ``0``.
Raises:
ValueError: if ``n`` is less than ``0``.
"""
if not is_natural(n):
raise ValueError('Expected n to be a positive integer.')
y = 0
n = abs(n)
while n:
y += n & 1
n = n >> 1
return y & 1 |
Implements a Serial Wire Viewer (SWV).
A Serial Wire Viewer (SWV) allows us implement real-time logging of output
from a connected device over Serial Wire Output (SWO).
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error | def serial_wire_viewer(jlink_serial, device):
"""Implements a Serial Wire Viewer (SWV).
A Serial Wire Viewer (SWV) allows us implement real-time logging of output
from a connected device over Serial Wire Output (SWO).
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error
"""
buf = StringIO.StringIO()
jlink = pylink.JLink(log=buf.write, detailed_log=buf.write)
jlink.open(serial_no=jlink_serial)
# Use Serial Wire Debug as the target interface. Need this in order to use
# Serial Wire Output.
jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
jlink.connect(device, verbose=True)
jlink.coresight_configure()
jlink.set_reset_strategy(pylink.enums.JLinkResetStrategyCortexM3.RESETPIN)
# Have to halt the CPU before getitng its speed.
jlink.reset()
jlink.halt()
# Output the information about the program.
sys.stdout.write('Serial Wire Viewer\n')
sys.stdout.write('Press Ctrl-C to Exit\n')
sys.stdout.write('Reading data from port 0:\n\n')
# Reset the core without halting so that it runs.
jlink.reset(ms=10, halt=False)
# Use the `try` loop to catch a keyboard interrupt in order to stop logging
# serial wire output.
try:
while True:
# Check the vector catch.
if jlink.register_read(0x0) != 0x05:
continue
offset = jlink.register_read(0x1)
handle, ptr, num_bytes = jlink.memory_read32(offset, 3)
read = ''.join(map(chr, jlink.memory_read8(ptr, num_bytes)))
if num_bytes == 0:
# If no bytes exist, sleep for a bit before trying again.
time.sleep(1)
continue
jlink.register_write(0x0, 0)
jlink.step(thumb=True)
jlink.restart(2, skip_breakpoints=True)
sys.stdout.write(read)
sys.stdout.flush()
except KeyboardInterrupt:
pass
sys.stdout.write('\n')
return 0 |
Packs a given value into an array of 8-bit unsigned integers.
If ``nbits`` is not present, calculates the minimal number of bits required
to represent the given ``value``. The result is little endian.
Args:
value (int): the integer value to pack
nbits (int): optional number of bits to use to represent the value
Returns:
An array of ``ctypes.c_uint8`` representing the packed ``value``.
Raises:
ValueError: if ``value < 0`` and ``nbits`` is ``None`` or ``nbits <= 0``.
TypeError: if ``nbits`` or ``value`` are not numbers. | def pack(value, nbits=None):
"""Packs a given value into an array of 8-bit unsigned integers.
If ``nbits`` is not present, calculates the minimal number of bits required
to represent the given ``value``. The result is little endian.
Args:
value (int): the integer value to pack
nbits (int): optional number of bits to use to represent the value
Returns:
An array of ``ctypes.c_uint8`` representing the packed ``value``.
Raises:
ValueError: if ``value < 0`` and ``nbits`` is ``None`` or ``nbits <= 0``.
TypeError: if ``nbits`` or ``value`` are not numbers.
"""
if nbits is None:
nbits = pack_size(value) * BITS_PER_BYTE
elif nbits <= 0:
raise ValueError('Given number of bits must be greater than 0.')
buf_size = int(math.ceil(nbits / float(BITS_PER_BYTE)))
buf = (ctypes.c_uint8 * buf_size)()
for (idx, _) in enumerate(buf):
buf[idx] = (value >> (idx * BITS_PER_BYTE)) & 0xFF
return buf |
Reads and returns the contents of the README.
On failure, returns the project long description.
Returns:
The project's long description. | def long_description():
"""Reads and returns the contents of the README.
On failure, returns the project long description.
Returns:
The project's long description.
"""
cwd = os.path.abspath(os.path.dirname(__file__))
readme_path = os.path.join(cwd, 'README.md')
if not os.path.exists(readme_path):
return pylink.__long_description__
try:
import pypandoc
return pypandoc.convert(readme_path, 'rst')
except (IOError, ImportError):
pass
return open(readme_path, 'r').read() |
Populate the attributes.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None`` | def finalize_options(self):
"""Populate the attributes.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None``
"""
self.cwd = os.path.abspath(os.path.dirname(__file__))
self.build_dirs = [
os.path.join(self.cwd, 'build'),
os.path.join(self.cwd, 'htmlcov'),
os.path.join(self.cwd, 'dist'),
os.path.join(self.cwd, 'pylink_square.egg-info')
]
self.build_artifacts = ['.pyc', '.o', '.elf', '.bin'] |
Runs the command.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None`` | def run(self):
"""Runs the command.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None``
"""
for build_dir in self.build_dirs:
if os.path.isdir(build_dir):
sys.stdout.write('Removing %s%s' % (build_dir, os.linesep))
shutil.rmtree(build_dir)
for (root, dirs, files) in os.walk(self.cwd):
for name in files:
fullpath = os.path.join(root, name)
if any(fullpath.endswith(ext) for ext in self.build_artifacts):
sys.stdout.write('Removing %s%s' % (fullpath, os.linesep))
os.remove(fullpath) |
Finalizes the command's options.
Args:
self (CoverageCommand): the ``CoverageCommand`` instance
Returns:
``None`` | def finalize_options(self):
"""Finalizes the command's options.
Args:
self (CoverageCommand): the ``CoverageCommand`` instance
Returns:
``None``
"""
self.cwd = os.path.abspath(os.path.dirname(__file__))
self.test_dir = os.path.join(self.cwd, 'tests') |
Returns the string message for the given ``error_code``.
Args:
cls (JlinkGlobalErrors): the ``JLinkGlobalErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid. | def to_string(cls, error_code):
"""Returns the string message for the given ``error_code``.
Args:
cls (JlinkGlobalErrors): the ``JLinkGlobalErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
"""
if error_code == cls.EMU_NO_CONNECTION:
return 'No connection to emulator.'
elif error_code == cls.EMU_COMM_ERROR:
return 'Emulator connection error.'
elif error_code == cls.DLL_NOT_OPEN:
return 'DLL has not been opened. Did you call \'.connect()\'?'
elif error_code == cls.VCC_FAILURE:
return 'Target system has no power.'
elif error_code == cls.INVALID_HANDLE:
return 'Given file / memory handle is invalid.'
elif error_code == cls.NO_CPU_FOUND:
return 'Could not find supported CPU.'
elif error_code == cls.EMU_FEATURE_UNSUPPORTED:
return 'Emulator does not support the selected feature.'
elif error_code == cls.EMU_NO_MEMORY:
return 'Emulator out of memory.'
elif error_code == cls.TIF_STATUS_ERROR:
return 'Target interface error.'
elif error_code == cls.FLASH_PROG_COMPARE_FAILED:
return 'Programmed data differs from source data.'
elif error_code == cls.FLASH_PROG_PROGRAM_FAILED:
return 'Programming error occured.'
elif error_code == cls.FLASH_PROG_VERIFY_FAILED:
return 'Error while verifying programmed data.'
elif error_code == cls.OPEN_FILE_FAILED:
return 'Specified file could not be opened.'
elif error_code == cls.UNKNOWN_FILE_FORMAT:
return 'File format of selected file is not supported.'
elif error_code == cls.WRITE_TARGET_MEMORY_FAILED:
return 'Could not write target memory.'
elif error_code == cls.DEVICE_FEATURE_NOT_SUPPORTED:
return 'Feature not supported by connected device.'
elif error_code == cls.WRONG_USER_CONFIG:
return 'User configured DLL parameters incorrectly.'
elif error_code == cls.NO_TARGET_DEVICE_SELECTED:
return 'User did not specify core to connect to.'
elif error_code == cls.CPU_IN_LOW_POWER_MODE:
return 'Target CPU is in low power mode.'
elif error_code == cls.UNSPECIFIED_ERROR:
return 'Unspecified error.'
raise ValueError('Invalid error code: %d' % error_code) |
Returns the string message for the given ``error_code``.
Args:
cls (JLinkEraseErrors): the ``JLinkEraseErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid. | def to_string(cls, error_code):
"""Returns the string message for the given ``error_code``.
Args:
cls (JLinkEraseErrors): the ``JLinkEraseErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
"""
if error_code == cls.ILLEGAL_COMMAND:
return 'Failed to erase sector.'
return super(JLinkEraseErrors, cls).to_string(error_code) |
Returns the string message for the given ``error_code``.
Args:
cls (JLinkFlashErrors): the ``JLinkFlashErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid. | def to_string(cls, error_code):
"""Returns the string message for the given ``error_code``.
Args:
cls (JLinkFlashErrors): the ``JLinkFlashErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
"""
if error_code == cls.COMPARE_ERROR:
return 'Error comparing flash content to programming data.'
elif error_code == cls.PROGRAM_ERASE_ERROR:
return 'Error during program/erase phase.'
elif error_code == cls.VERIFICATION_ERROR:
return 'Error verifying programmed data.'
return super(JLinkFlashErrors, cls).to_string(error_code) |
Returns the string message for the given ``error_code``.
Args:
cls (JLinkWriteErrors): the ``JLinkWriteErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid. | def to_string(cls, error_code):
"""Returns the string message for the given ``error_code``.
Args:
cls (JLinkWriteErrors): the ``JLinkWriteErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
"""
if error_code == cls.ZONE_NOT_FOUND_ERROR:
return 'Zone not found'
return super(JLinkWriteErrors, cls).to_string(error_code) |
Returns the string message for the given ``error_code``.
Args:
cls (JLinkReadErrors): the ``JLinkReadErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid. | def to_string(cls, error_code):
"""Returns the string message for the given ``error_code``.
Args:
cls (JLinkReadErrors): the ``JLinkReadErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
"""
if error_code == cls.ZONE_NOT_FOUND_ERROR:
return 'Zone not found'
return super(JLinkReadErrors, cls).to_string(error_code) |
Returns the string message for the given error code.
Args:
cls (JLinkDataErrors): the ``JLinkDataErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid. | def to_string(cls, error_code):
"""Returns the string message for the given error code.
Args:
cls (JLinkDataErrors): the ``JLinkDataErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
"""
if error_code == cls.ERROR_UNKNOWN:
return 'Unknown error.'
elif error_code == cls.ERROR_NO_MORE_EVENTS:
return 'There are no more available watchpoint units.'
elif error_code == cls.ERROR_NO_MORE_ADDR_COMP:
return 'No more address comparisons can be set.'
elif error_code == cls.ERROR_NO_MORE_DATA_COMP:
return 'No more data comparisons can be set.'
elif error_code == cls.ERROR_INVALID_ADDR_MASK:
return 'Invalid flags passed for the address mask.'
elif error_code == cls.ERROR_INVALID_DATA_MASK:
return 'Invalid flags passed for the data mask.'
elif error_code == cls.ERROR_INVALID_ACCESS_MASK:
return 'Invalid flags passed for the access mask.'
return super(JLinkDataErrors, cls).to_string(error_code) |
Returns the string message for the given error code.
Args:
cls (JLinkRTTErrors): the ``JLinkRTTErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid. | def to_string(cls, error_code):
"""Returns the string message for the given error code.
Args:
cls (JLinkRTTErrors): the ``JLinkRTTErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
"""
if error_code == cls.RTT_ERROR_CONTROL_BLOCK_NOT_FOUND:
return 'The RTT Control Block has not yet been found (wait?)'
return super(JLinkRTTErrors, cls).to_string(error_code) |
Checks whether the given flags are a valid identity.
Args:
identity (Identity): the identity to validate against
flags (register.IDCodeRegisterFlags): the set idcode flags
Returns:
``True`` if the given ``flags`` correctly identify the the debug
interface, otherwise ``False``. | def unlock_kinetis_identified(identity, flags):
"""Checks whether the given flags are a valid identity.
Args:
identity (Identity): the identity to validate against
flags (register.IDCodeRegisterFlags): the set idcode flags
Returns:
``True`` if the given ``flags`` correctly identify the the debug
interface, otherwise ``False``.
"""
if flags.version_code != identity.version_code:
return False
if flags.part_no != identity.part_no:
return False
return flags.valid |
Returns the abort register clear code.
Returns:
The abort register clear code. | def unlock_kinetis_abort_clear():
"""Returns the abort register clear code.
Returns:
The abort register clear code.
"""
flags = registers.AbortRegisterFlags()
flags.STKCMPCLR = 1
flags.STKERRCLR = 1
flags.WDERRCLR = 1
flags.ORUNERRCLR = 1
return flags.value |
Polls the device until the request is acknowledged.
Sends a read request to the connected device to read the register at the
given 'address'. Polls indefinitely until either the request is ACK'd or
the request ends in a fault.
Args:
jlink (JLink): the connected J-Link
address (int) the address of the register to poll
Returns:
``SWDResponse`` object on success.
Raises:
KinetisException: when read exits with non-ack or non-wait status.
Note:
This function is required in order to avoid reading corrupt or otherwise
invalid data from registers when communicating over SWD. | def unlock_kinetis_read_until_ack(jlink, address):
"""Polls the device until the request is acknowledged.
Sends a read request to the connected device to read the register at the
given 'address'. Polls indefinitely until either the request is ACK'd or
the request ends in a fault.
Args:
jlink (JLink): the connected J-Link
address (int) the address of the register to poll
Returns:
``SWDResponse`` object on success.
Raises:
KinetisException: when read exits with non-ack or non-wait status.
Note:
This function is required in order to avoid reading corrupt or otherwise
invalid data from registers when communicating over SWD.
"""
request = swd.ReadRequest(address, ap=True)
response = None
while True:
response = request.send(jlink)
if response.ack():
break
elif response.wait():
continue
raise KinetisException('Read exited with status: %s', response.status)
return response |
Unlocks a Kinetis device over SWD.
Steps Involved in Unlocking:
1. Verify that the device is configured to read/write from the CoreSight
registers; this is done by reading the Identification Code Register
and checking its validity. This register is always at 0x0 on reads.
2. Check for errors in the status register. If there are any errors,
they must be cleared by writing to the Abort Register (this is always
0x0 on writes).
3. Turn on the device power and debug power so that the target is
powered by the J-Link as more power is required during an unlock.
4. Assert the ``RESET`` pin to force the target to hold in a reset-state
as to avoid interrupts and other potentially breaking behaviour.
5. At this point, SWD is configured, so send a request to clear the
errors, if any, that may currently be set.
6. Our next SWD request selects the MDM-AP register so that we can start
sending unlock instructions. ``SELECT[31:24] = 0x01`` selects it.
7. Poll the MDM-AP Status Register (AP[1] bank 0, register 0) until the
flash ready bit is set to indicate we can flash.
8. Write to the MDM-AP Control Register (AP[1] bank 0, register 1) to
request a flash mass erase.
9. Poll the system until the flash mass erase bit is acknowledged in the
MDM-AP Status Register.
10. Poll the control register until it clears it's mass erase bit to
indicate that it finished mass erasing, and therefore the system is
now unsecure.
Args:
jlink (JLink): the connected J-Link
Returns:
``True`` if the device was unlocked successfully, otherwise ``False``.
Raises:
KinetisException: when the device cannot be unlocked or fails to unlock.
See Also:
`NXP Forum <https://community.nxp.com/thread/317167>`_.
See Also:
`Kinetis Docs <nxp.com/files/32bit/doc/ref_manual/K12P48M50SF4RM.pdf>` | def unlock_kinetis_swd(jlink):
"""Unlocks a Kinetis device over SWD.
Steps Involved in Unlocking:
1. Verify that the device is configured to read/write from the CoreSight
registers; this is done by reading the Identification Code Register
and checking its validity. This register is always at 0x0 on reads.
2. Check for errors in the status register. If there are any errors,
they must be cleared by writing to the Abort Register (this is always
0x0 on writes).
3. Turn on the device power and debug power so that the target is
powered by the J-Link as more power is required during an unlock.
4. Assert the ``RESET`` pin to force the target to hold in a reset-state
as to avoid interrupts and other potentially breaking behaviour.
5. At this point, SWD is configured, so send a request to clear the
errors, if any, that may currently be set.
6. Our next SWD request selects the MDM-AP register so that we can start
sending unlock instructions. ``SELECT[31:24] = 0x01`` selects it.
7. Poll the MDM-AP Status Register (AP[1] bank 0, register 0) until the
flash ready bit is set to indicate we can flash.
8. Write to the MDM-AP Control Register (AP[1] bank 0, register 1) to
request a flash mass erase.
9. Poll the system until the flash mass erase bit is acknowledged in the
MDM-AP Status Register.
10. Poll the control register until it clears it's mass erase bit to
indicate that it finished mass erasing, and therefore the system is
now unsecure.
Args:
jlink (JLink): the connected J-Link
Returns:
``True`` if the device was unlocked successfully, otherwise ``False``.
Raises:
KinetisException: when the device cannot be unlocked or fails to unlock.
See Also:
`NXP Forum <https://community.nxp.com/thread/317167>`_.
See Also:
`Kinetis Docs <nxp.com/files/32bit/doc/ref_manual/K12P48M50SF4RM.pdf>`
"""
SWDIdentity = Identity(0x2, 0xBA01)
jlink.power_on()
jlink.coresight_configure()
# 1. Verify that the device is configured properly.
flags = registers.IDCodeRegisterFlags()
flags.value = jlink.coresight_read(0x0, False)
if not unlock_kinetis_identified(SWDIdentity, flags):
return False
# 2. Check for errors.
flags = registers.ControlStatusRegisterFlags()
flags.value = jlink.coresight_read(0x01, False)
if flags.STICKYORUN or flags.STICKYCMP or flags.STICKYERR or flags.WDATAERR:
jlink.coresight_write(0x0, unlock_kinetis_abort_clear(), False)
# 3. Turn on device power and debug.
flags = registers.ControlStatusRegisterFlags()
flags.value = 0
flags.CSYSPWRUPREQ = 1 # System power-up request
flags.CDBGPWRUPREQ = 1 # Debug power-up request
jlink.coresight_write(0x01, flags.value, False)
# 4. Assert the reset pin.
jlink.set_reset_pin_low()
time.sleep(1)
# 5. Send a SWD Request to clear any errors.
request = swd.WriteRequest(0x0, False, unlock_kinetis_abort_clear())
request.send(jlink)
# 6. Send a SWD Request to select the MDM-AP register, SELECT[31:24] = 0x01
request = swd.WriteRequest(0x2, False, (1 << 24))
request.send(jlink)
try:
# 7. Poll until the Flash-ready bit is set in the status register flags.
# Have to read first to ensure the data is valid.
unlock_kinetis_read_until_ack(jlink, 0x0)
flags = registers.MDMAPStatusRegisterFlags()
flags.flash_ready = 0
while not flags.flash_ready:
flags.value = unlock_kinetis_read_until_ack(jlink, 0x0).data
# 8. System may still be secure at this point, so request a mass erase.
# AP[1] bank 0, register 1 is the MDM-AP Control Register.
flags = registers.MDMAPControlRegisterFlags()
flags.flash_mass_erase = 1
request = swd.WriteRequest(0x1, True, flags.value)
request.send(jlink)
# 9. Poll the status register until the mass erase command has been
# accepted.
unlock_kinetis_read_until_ack(jlink, 0x0)
flags = registers.MDMAPStatusRegisterFlags()
flags.flash_mass_erase_ack = 0
while not flags.flash_mass_erase_ack:
flags.value = unlock_kinetis_read_until_ack(jlink, 0x0).data
# 10. Poll the control register until the ``flash_mass_erase`` bit is
# cleared, which is done automatically when the mass erase
# finishes.
unlock_kinetis_read_until_ack(jlink, 0x1)
flags = registers.MDMAPControlRegisterFlags()
flags.flash_mass_erase = 1
while flags.flash_mass_erase:
flags.value = unlock_kinetis_read_until_ack(jlink, 0x1).data
except KinetisException as e:
jlink.set_reset_pin_high()
return False
jlink.set_reset_pin_high()
time.sleep(1)
jlink.reset()
return True |
Unlock for Freescale Kinetis K40 or K60 device.
Args:
jlink (JLink): an instance of a J-Link that is connected to a target.
Returns:
``True`` if the device was successfully unlocked, otherwise ``False``.
Raises:
ValueError: if the J-Link is not connected to a target. | def unlock_kinetis(jlink):
"""Unlock for Freescale Kinetis K40 or K60 device.
Args:
jlink (JLink): an instance of a J-Link that is connected to a target.
Returns:
``True`` if the device was successfully unlocked, otherwise ``False``.
Raises:
ValueError: if the J-Link is not connected to a target.
"""
if not jlink.connected():
raise ValueError('No target to unlock.')
method = UNLOCK_METHODS.get(jlink.tif, None)
if method is None:
raise NotImplementedError('Unsupported target interface for unlock.')
return method(jlink) |
Implements a Serial Wire Viewer (SWV).
A Serial Wire Viewer (SWV) allows us implement real-time logging of output
from a connected device over Serial Wire Output (SWO).
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error | def serial_wire_viewer(jlink_serial, device):
"""Implements a Serial Wire Viewer (SWV).
A Serial Wire Viewer (SWV) allows us implement real-time logging of output
from a connected device over Serial Wire Output (SWO).
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error
"""
buf = StringIO.StringIO()
jlink = pylink.JLink(log=buf.write, detailed_log=buf.write)
jlink.open(serial_no=jlink_serial)
# Use Serial Wire Debug as the target interface. Need this in order to use
# Serial Wire Output.
jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
jlink.connect(device, verbose=True)
jlink.coresight_configure()
jlink.set_reset_strategy(pylink.enums.JLinkResetStrategyCortexM3.RESETPIN)
# Have to halt the CPU before getitng its speed.
jlink.reset()
jlink.halt()
cpu_speed = jlink.cpu_speed()
swo_speed = jlink.swo_supported_speeds(cpu_speed, 10)[0]
# Start logging serial wire output.
jlink.swo_start(swo_speed)
jlink.swo_flush()
# Output the information about the program.
sys.stdout.write('Serial Wire Viewer\n')
sys.stdout.write('Press Ctrl-C to Exit\n')
sys.stdout.write('Reading data from port 0:\n\n')
# Reset the core without halting so that it runs.
jlink.reset(ms=10, halt=False)
# Use the `try` loop to catch a keyboard interrupt in order to stop logging
# serial wire output.
try:
while True:
# Check for any bytes in the stream.
num_bytes = jlink.swo_num_bytes()
if num_bytes == 0:
# If no bytes exist, sleep for a bit before trying again.
time.sleep(1)
continue
data = jlink.swo_read_stimulus(0, num_bytes)
sys.stdout.write(''.join(map(chr, data)))
sys.stdout.flush()
except KeyboardInterrupt:
pass
sys.stdout.write('\n')
# Stop logging serial wire output.
jlink.swo_stop()
return 0 |
Decorator to specify the minimum SDK version required.
Args:
version (str): valid version string
Returns:
A decorator function. | def minimum_required(version):
"""Decorator to specify the minimum SDK version required.
Args:
version (str): valid version string
Returns:
A decorator function.
"""
def _minimum_required(func):
"""Internal decorator that wraps around the given function.
Args:
func (function): function being decorated
Returns:
The wrapper unction.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
"""Wrapper function to compare the DLL's SDK version.
Args:
self (JLink): the ``JLink`` instance
args (list): list of arguments to pass to ``func``
kwargs (dict): key-word arguments dict to pass to ``func``
Returns:
The return value of the wrapped function.
Raises:
JLinkException: if the DLL's version is less than ``version``.
"""
if list(self.version) < list(version):
raise errors.JLinkException('Version %s required.' % version)
return func(self, *args, **kwargs)
return wrapper
return _minimum_required |
Decorator to specify that the J-Link DLL must be opened, and a
J-Link connection must be established.
Args:
func (function): function being decorated
Returns:
The wrapper function. | def open_required(func):
"""Decorator to specify that the J-Link DLL must be opened, and a
J-Link connection must be established.
Args:
func (function): function being decorated
Returns:
The wrapper function.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
"""Wrapper function to check that the given ``JLink`` has been
opened.
Args:
self (JLink): the ``JLink`` instance
args: list of arguments to pass to the wrapped function
kwargs: key-word arguments dict to pass to the wrapped function
Returns:
The return value of the wrapped function.
Raises:
JLinkException: if the J-Link DLL is not open or the J-Link is
disconnected.
"""
if not self.opened():
raise errors.JLinkException('J-Link DLL is not open.')
elif not self.connected():
raise errors.JLinkException('J-Link connection has been lost.')
return func(self, *args, **kwargs)
return wrapper |
Decorator to specify that a target connection is required in order
for the given method to be used.
Args:
func (function): function being decorated
Returns:
The wrapper function. | def connection_required(func):
"""Decorator to specify that a target connection is required in order
for the given method to be used.
Args:
func (function): function being decorated
Returns:
The wrapper function.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
"""Wrapper function to check that the given ``JLink`` has been
connected to a target.
Args:
self (JLink): the ``JLink`` instance
args: list of arguments to pass to the wrapped function
kwargs: key-word arguments dict to pass to the wrapped function
Returns:
The return value of the wrapped function.
Raises:
JLinkException: if the JLink's target is not connected.
"""
if not self.target_connected():
raise errors.JLinkException('Target is not connected.')
return func(self, *args, **kwargs)
return wrapper |
Decorator to specify that a particular interface type is required
for the given method to be used.
Args:
interface (int): attribute of ``JLinkInterfaces``
Returns:
A decorator function. | def interface_required(interface):
"""Decorator to specify that a particular interface type is required
for the given method to be used.
Args:
interface (int): attribute of ``JLinkInterfaces``
Returns:
A decorator function.
"""
def _interface_required(func):
"""Internal decorator that wraps around the decorated function.
Args:
func (function): function being decorated
Returns:
The wrapper function.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
"""Wrapper function to check that the given ``JLink`` has the
same interface as the one specified by the decorator.
Args:
self (JLink): the ``JLink`` instance
args: list of arguments to pass to ``func``
kwargs: key-word arguments dict to pass to ``func``
Returns:
The return value of the wrapped function.
Raises:
JLinkException: if the current interface is not supported by
the wrapped method.
"""
if self.tif != interface:
raise errors.JLinkException('Unsupported for current interface.')
return func(self, *args, **kwargs)
return wrapper
return _interface_required |
Setter for the log handler function.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None`` | def log_handler(self, handler):
"""Setter for the log handler function.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
"""
if not self.opened():
handler = handler or util.noop
self._log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
self._dll.JLINKARM_EnableLog(self._log_handler) |
Setter for the detailed log handler function.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None`` | def detailed_log_handler(self, handler):
"""Setter for the detailed log handler function.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
"""
if not self.opened():
handler = handler or util.noop
self._detailed_log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
self._dll.JLINKARM_EnableLogCom(self._detailed_log_handler) |
Setter for the error handler function.
If the DLL is open, this function is a no-op, so it should be called
prior to calling ``open()``.
Args:
self (JLink): the ``JLink`` instance
handler (function): function to call on error messages
Returns:
``None`` | def error_handler(self, handler):
"""Setter for the error handler function.
If the DLL is open, this function is a no-op, so it should be called
prior to calling ``open()``.
Args:
self (JLink): the ``JLink`` instance
handler (function): function to call on error messages
Returns:
``None``
"""
if not self.opened():
handler = handler or util.noop
self._error_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
self._dll.JLINKARM_SetErrorOutHandler(self._error_handler) |
Setter for the warning handler function.
If the DLL is open, this function is a no-op, so it should be called
prior to calling ``open()``.
Args:
self (JLink): the ``JLink`` instance
handler (function): function to call on warning messages
Returns:
``None`` | def warning_handler(self, handler):
"""Setter for the warning handler function.
If the DLL is open, this function is a no-op, so it should be called
prior to calling ``open()``.
Args:
self (JLink): the ``JLink`` instance
handler (function): function to call on warning messages
Returns:
``None``
"""
if not self.opened():
handler = handler or util.noop
self._warning_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
self._dll.JLINKARM_SetWarnOutHandler(self._warning_handler) |
Returns a list of all the connected emulators.
Args:
self (JLink): the ``JLink`` instance
host (int): host type to search (default: ``JLinkHost.USB``)
Returns:
List of ``JLinkConnectInfo`` specifying the connected emulators.
Raises:
JLinkException: if fails to enumerate devices. | def connected_emulators(self, host=enums.JLinkHost.USB):
"""Returns a list of all the connected emulators.
Args:
self (JLink): the ``JLink`` instance
host (int): host type to search (default: ``JLinkHost.USB``)
Returns:
List of ``JLinkConnectInfo`` specifying the connected emulators.
Raises:
JLinkException: if fails to enumerate devices.
"""
res = self._dll.JLINKARM_EMU_GetList(host, 0, 0)
if res < 0:
raise errors.JLinkException(res)
num_devices = res
info = (structs.JLinkConnectInfo * num_devices)()
num_found = self._dll.JLINKARM_EMU_GetList(host, info, num_devices)
if num_found < 0:
raise errors.JLinkException(num_found)
return list(info)[:num_found] |
Gets the device at the given ``index``.
Args:
self (JLink): the ``JLink`` instance
index (int): the index of the device whose information to get
Returns:
A ``JLinkDeviceInfo`` describing the requested device.
Raises:
ValueError: if index is less than 0 or >= supported device count. | def supported_device(self, index=0):
"""Gets the device at the given ``index``.
Args:
self (JLink): the ``JLink`` instance
index (int): the index of the device whose information to get
Returns:
A ``JLinkDeviceInfo`` describing the requested device.
Raises:
ValueError: if index is less than 0 or >= supported device count.
"""
if not util.is_natural(index) or index >= self.num_supported_devices():
raise ValueError('Invalid index.')
info = structs.JLinkDeviceInfo()
result = self._dll.JLINKARM_DEVICE_GetInfo(index, ctypes.byref(info))
return info |
Connects to the J-Link emulator (defaults to USB).
If ``serial_no`` and ``ip_addr`` are both given, this function will
connect to the J-Link over TCP/IP.
Args:
self (JLink): the ``JLink`` instance
serial_no (int): serial number of the J-Link
ip_addr (str): IP address and port of the J-Link (e.g. 192.168.1.1:80)
Returns:
``None``
Raises:
JLinkException: if fails to open (i.e. if device is unplugged)
TypeError: if ``serial_no`` is present, but not ``int`` coercible.
AttributeError: if ``serial_no`` and ``ip_addr`` are both ``None``. | def open(self, serial_no=None, ip_addr=None):
"""Connects to the J-Link emulator (defaults to USB).
If ``serial_no`` and ``ip_addr`` are both given, this function will
connect to the J-Link over TCP/IP.
Args:
self (JLink): the ``JLink`` instance
serial_no (int): serial number of the J-Link
ip_addr (str): IP address and port of the J-Link (e.g. 192.168.1.1:80)
Returns:
``None``
Raises:
JLinkException: if fails to open (i.e. if device is unplugged)
TypeError: if ``serial_no`` is present, but not ``int`` coercible.
AttributeError: if ``serial_no`` and ``ip_addr`` are both ``None``.
"""
# For some reason, the J-Link driver complains if this isn't called
# first (may have something to do with it trying to establish a
# connection). Without this call, it will log an error stating
# NET_WriteRead(): USB communication not locked
# PID0017A8C (): Lock count error (decrement)
self.close()
if ip_addr is not None:
addr, port = ip_addr.rsplit(':', 1)
if serial_no is None:
result = self._dll.JLINKARM_SelectIP(addr.encode(), int(port))
if result == 1:
raise errors.JLinkException('Could not connect to emulator at %s.' % ip_addr)
else:
# Note: No return code when selecting IP by serial number.
self._dll.JLINKARM_EMU_SelectIPBySN(int(serial_no))
elif serial_no is not None:
result = self._dll.JLINKARM_EMU_SelectByUSBSN(int(serial_no))
if result < 0:
raise errors.JLinkException('No emulator with serial number %s found.' % serial_no)
else:
# The original method of connecting to USB0-3 via
# JLINKARM_SelectUSB has been obsolesced, however its use is
# preserved here to simplify workflows using one emulator:
result = self._dll.JLINKARM_SelectUSB(0)
if result != 0:
raise errors.JlinkException('Could not connect to default emulator.')
# Acquire the lock for the J-Link being opened only if the serial
# number was passed in, otherwise skip it here. Note that the lock
# must be acquired before calling 'JLINKARM_OpenEx()', otherwise the
# call will fail on Windows.
if serial_no is not None:
self._lock = jlock.JLock(serial_no)
if not self._lock.acquire():
raise errors.JLinkException('J-Link is already open.')
result = self._dll.JLINKARM_OpenEx(self.log_handler, self.error_handler)
result = ctypes.cast(result, ctypes.c_char_p).value
if result is not None:
raise errors.JLinkException(result.decode())
# Configuration of the J-Link DLL. These are configuration steps that
# have to be done after 'open()'. The unsecure hook is only supported
# on versions greater than V4.98a.
unsecure_hook = self._unsecure_hook
if unsecure_hook is not None and hasattr(self._dll, 'JLINK_SetHookUnsecureDialog'):
func = enums.JLinkFunctions.UNSECURE_HOOK_PROTOTYPE(unsecure_hook)
self._dll.JLINK_SetHookUnsecureDialog(func)
return None |
Connects to the J-Link emulator (over SEGGER tunnel).
Args:
self (JLink): the ``JLink`` instance
serial_no (int): serial number of the J-Link
port (int): optional port number (default to 19020).
Returns:
``None`` | def open_tunnel(self, serial_no, port=19020):
"""Connects to the J-Link emulator (over SEGGER tunnel).
Args:
self (JLink): the ``JLink`` instance
serial_no (int): serial number of the J-Link
port (int): optional port number (default to 19020).
Returns:
``None``
"""
return self.open(ip_addr='tunnel:' + str(serial_no) + ':' + str(port)) |
Closes the open J-Link.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
Raises:
JLinkException: if there is no connected JLink. | def close(self):
"""Closes the open J-Link.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
Raises:
JLinkException: if there is no connected JLink.
"""
self._dll.JLINKARM_Close()
if self._lock is not None:
del self._lock
self._lock = None
return None |
Syncs the emulator's firmware version and the DLL's firmware.
This method is useful for ensuring that the firmware running on the
J-Link matches the firmware supported by the DLL.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None`` | def sync_firmware(self):
"""Syncs the emulator's firmware version and the DLL's firmware.
This method is useful for ensuring that the firmware running on the
J-Link matches the firmware supported by the DLL.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
"""
serial_no = self.serial_number
if self.firmware_newer():
# The J-Link's firmware is newer than the one compatible with the
# DLL (though there are promises of backwards compatibility), so
# perform a downgrade.
try:
# This may throw an exception on older versions of the J-Link
# software due to the software timing out after a firmware
# upgrade.
self.invalidate_firmware()
self.update_firmware()
except errors.JLinkException as e:
pass
res = self.open(serial_no=serial_no)
if self.firmware_newer():
raise errors.JLinkException('Failed to sync firmware version.')
return res
elif self.firmware_outdated():
# The J-Link's firmware is older than the one compatible with the
# DLL, so perform a firmware upgrade.
try:
# This may throw an exception on older versions of the J-Link
# software due to the software timing out after a firmware
# upgrade.
self.update_firmware()
except errors.JLinkException as e:
pass
if self.firmware_outdated():
raise errors.JLinkException('Failed to sync firmware version.')
return self.open(serial_no=serial_no)
return None |
Executes the given command.
This method executes a command by calling the DLL's exec method.
Direct API methods should be prioritized over calling this method.
Args:
self (JLink): the ``JLink`` instance
cmd (str): the command to run
Returns:
The return code of running the command.
Raises:
JLinkException: if the command is invalid or fails.
See Also:
For a full list of the supported commands, please see the SEGGER
J-Link documentation,
`UM08001 <https://www.segger.com/downloads/jlink>`__. | def exec_command(self, cmd):
"""Executes the given command.
This method executes a command by calling the DLL's exec method.
Direct API methods should be prioritized over calling this method.
Args:
self (JLink): the ``JLink`` instance
cmd (str): the command to run
Returns:
The return code of running the command.
Raises:
JLinkException: if the command is invalid or fails.
See Also:
For a full list of the supported commands, please see the SEGGER
J-Link documentation,
`UM08001 <https://www.segger.com/downloads/jlink>`__.
"""
err_buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
res = self._dll.JLINKARM_ExecCommand(cmd.encode(), err_buf, self.MAX_BUF_SIZE)
err_buf = ctypes.string_at(err_buf).decode()
if len(err_buf) > 0:
# This is how they check for error in the documentation, so check
# this way as well.
raise errors.JLinkException(err_buf.strip())
return res |
Configures the JTAG scan chain to determine which CPU to address.
Must be called if the J-Link is connected to a JTAG scan chain with
multiple devices.
Args:
self (JLink): the ``JLink`` instance
instr_regs (int): length of instruction registers of all devices
closer to TD1 then the addressed CPU
data_bits (int): total number of data bits closer to TD1 than the
addressed CPU
Returns:
``None``
Raises:
ValueError: if ``instr_regs`` or ``data_bits`` are not natural numbers | def jtag_configure(self, instr_regs=0, data_bits=0):
"""Configures the JTAG scan chain to determine which CPU to address.
Must be called if the J-Link is connected to a JTAG scan chain with
multiple devices.
Args:
self (JLink): the ``JLink`` instance
instr_regs (int): length of instruction registers of all devices
closer to TD1 then the addressed CPU
data_bits (int): total number of data bits closer to TD1 than the
addressed CPU
Returns:
``None``
Raises:
ValueError: if ``instr_regs`` or ``data_bits`` are not natural numbers
"""
if not util.is_natural(instr_regs):
raise ValueError('IR value is not a natural number.')
if not util.is_natural(data_bits):
raise ValueError('Data bits is not a natural number.')
self._dll.JLINKARM_ConfigJTAG(instr_regs, data_bits)
return None |
Prepares target and J-Link for CoreSight function usage.
Args:
self (JLink): the ``JLink`` instance
ir_pre (int): sum of instruction register length of all JTAG devices
in the JTAG chain, close to TDO than the actual one, that J-Link
shall communicate with
dr_pre (int): number of JTAG devices in the JTAG chain, closer to TDO
than the actual one, that J-Link shall communicate with
ir_post (int): sum of instruction register length of all JTAG devices
in the JTAG chain, following the actual one, that J-Link shall
communicate with
dr_post (int): Number of JTAG devices in the JTAG chain, following
the actual one, J-Link shall communicate with
ir_len (int): instruction register length of the actual device that
J-Link shall communicate with
perform_tif_init (bool): if ``False``, then do not output switching
sequence on completion
Returns:
``None``
Note:
This must be called before calling ``coresight_read()`` or
``coresight_write()``. | def coresight_configure(self,
ir_pre=0,
dr_pre=0,
ir_post=0,
dr_post=0,
ir_len=0,
perform_tif_init=True):
"""Prepares target and J-Link for CoreSight function usage.
Args:
self (JLink): the ``JLink`` instance
ir_pre (int): sum of instruction register length of all JTAG devices
in the JTAG chain, close to TDO than the actual one, that J-Link
shall communicate with
dr_pre (int): number of JTAG devices in the JTAG chain, closer to TDO
than the actual one, that J-Link shall communicate with
ir_post (int): sum of instruction register length of all JTAG devices
in the JTAG chain, following the actual one, that J-Link shall
communicate with
dr_post (int): Number of JTAG devices in the JTAG chain, following
the actual one, J-Link shall communicate with
ir_len (int): instruction register length of the actual device that
J-Link shall communicate with
perform_tif_init (bool): if ``False``, then do not output switching
sequence on completion
Returns:
``None``
Note:
This must be called before calling ``coresight_read()`` or
``coresight_write()``.
"""
if self.tif == enums.JLinkInterfaces.SWD:
# No special setup is needed for SWD, just need to output the
# switching sequence.
res = self._dll.JLINKARM_CORESIGHT_Configure('')
if res < 0:
raise errors.JLinkException(res)
return None
# JTAG requires more setup than SWD.
config_string = 'IRPre=%s;DRPre=%s;IRPost=%s;DRPost=%s;IRLenDevice=%s;'
config_string = config_string % (ir_pre, dr_pre, ir_post, dr_post, ir_len)
if not perform_tif_init:
config_string = config_string + ('PerformTIFInit=0;')
res = self._dll.JLINKARM_CORESIGHT_Configure(config_string.encode())
if res < 0:
raise errors.JLinkException(res)
return None |
Connects the J-Link to its target.
Args:
self (JLink): the ``JLink`` instance
chip_name (str): target chip name
speed (int): connection speed, one of ``{5-12000, 'auto', 'adaptive'}``
verbose (bool): boolean indicating if connection should be verbose in logging
Returns:
``None``
Raises:
JLinkException: if connection fails to establish.
TypeError: if given speed is invalid | def connect(self, chip_name, speed='auto', verbose=False):
"""Connects the J-Link to its target.
Args:
self (JLink): the ``JLink`` instance
chip_name (str): target chip name
speed (int): connection speed, one of ``{5-12000, 'auto', 'adaptive'}``
verbose (bool): boolean indicating if connection should be verbose in logging
Returns:
``None``
Raises:
JLinkException: if connection fails to establish.
TypeError: if given speed is invalid
"""
if verbose:
self.exec_command('EnableRemarks = 1')
# This is weird but is currently the only way to specify what the
# target is to the J-Link.
self.exec_command('Device = %s' % chip_name)
# Need to select target interface speed here, so the J-Link knows what
# speed to use to establish target communication.
if speed == 'auto':
self.set_speed(auto=True)
elif speed == 'adaptive':
self.set_speed(adaptive=True)
else:
self.set_speed(speed)
result = self._dll.JLINKARM_Connect()
if result < 0:
raise errors.JLinkException(result)
try:
# Issue a no-op command after connect. This has to be in a try-catch.
self.halted()
except errors.JLinkException:
pass
# Determine which device we are. This is essential for using methods
# like 'unlock' or 'lock'.
for index in range(self.num_supported_devices()):
device = self.supported_device(index)
if device.name.lower() == chip_name.lower():
self._device = device
break
else:
raise errors.JLinkException('Unsupported device was connected to.')
return None |
Returns the device's version.
The device's version is returned as a string of the format: M.mr where
``M`` is major number, ``m`` is minor number, and ``r`` is revision
character.
Args:
self (JLink): the ``JLink`` instance
Returns:
Device version string. | def version(self):
"""Returns the device's version.
The device's version is returned as a string of the format: M.mr where
``M`` is major number, ``m`` is minor number, and ``r`` is revision
character.
Args:
self (JLink): the ``JLink`` instance
Returns:
Device version string.
"""
version = int(self._dll.JLINKARM_GetDLLVersion())
major = version / 10000
minor = (version / 100) % 100
rev = version % 100
rev = '' if rev == 0 else chr(rev + ord('a') - 1)
return '%d.%02d%s' % (major, minor, rev) |
Returns a string specifying the date and time at which the DLL was
translated.
Args:
self (JLink): the ``JLink`` instance
Returns:
Datetime string. | def compile_date(self):
"""Returns a string specifying the date and time at which the DLL was
translated.
Args:
self (JLink): the ``JLink`` instance
Returns:
Datetime string.
"""
result = self._dll.JLINKARM_GetCompileDateTime()
return ctypes.cast(result, ctypes.c_char_p).value.decode() |
Returns the DLL's compatible J-Link firmware version.
Args:
self (JLink): the ``JLink`` instance
Returns:
The firmware version of the J-Link that the DLL is compatible
with.
Raises:
JLinkException: on error. | def compatible_firmware_version(self):
"""Returns the DLL's compatible J-Link firmware version.
Args:
self (JLink): the ``JLink`` instance
Returns:
The firmware version of the J-Link that the DLL is compatible
with.
Raises:
JLinkException: on error.
"""
identifier = self.firmware_version.split('compiled')[0]
buf_size = self.MAX_BUF_SIZE
buf = (ctypes.c_char * buf_size)()
res = self._dll.JLINKARM_GetEmbeddedFWString(identifier.encode(), buf, buf_size)
if res < 0:
raise errors.JLinkException(res)
return ctypes.string_at(buf).decode() |
Returns whether the J-Link's firmware version is older than the one
that the DLL is compatible with.
Note:
This is not the same as calling ``not jlink.firmware_newer()``.
Args:
self (JLink): the ``JLink`` instance
Returns:
``True`` if the J-Link's firmware is older than the one supported by
the DLL, otherwise ``False``. | def firmware_outdated(self):
"""Returns whether the J-Link's firmware version is older than the one
that the DLL is compatible with.
Note:
This is not the same as calling ``not jlink.firmware_newer()``.
Args:
self (JLink): the ``JLink`` instance
Returns:
``True`` if the J-Link's firmware is older than the one supported by
the DLL, otherwise ``False``.
"""
datefmt = ' %b %d %Y %H:%M:%S'
compat_date = self.compatible_firmware_version.split('compiled')[1]
compat_date = datetime.datetime.strptime(compat_date, datefmt)
fw_date = self.firmware_version.split('compiled')[1]
fw_date = datetime.datetime.strptime(fw_date, datefmt)
return (compat_date > fw_date) |
Returns a list of 32 integer values corresponding to the bitfields
specifying the power consumption of the target.
The values returned by this function only have significance if the
J-Link is powering the target.
The words, indexed, have the following significance:
0. If ``1``, target is powered via J-Link.
1. Overcurrent bitfield:
0: No overcurrent.
1: Overcurrent happened. 2ms @ 3000mA
2: Overcurrent happened. 10ms @ 1000mA
3: Overcurrent happened. 40ms @ 400mA
2. Power consumption of target (mA).
3. Peak of target power consumption (mA).
4. Peak of target power consumption during J-Link operation (mA).
Args:
self (JLink): the ``JLink`` instance
mask (int): bit mask to decide which hardware information words are
returned (defaults to all the words).
Returns:
List of bitfields specifying different states based on their index
within the list and their value.
Raises:
JLinkException: on hardware error. | def hardware_info(self, mask=0xFFFFFFFF):
"""Returns a list of 32 integer values corresponding to the bitfields
specifying the power consumption of the target.
The values returned by this function only have significance if the
J-Link is powering the target.
The words, indexed, have the following significance:
0. If ``1``, target is powered via J-Link.
1. Overcurrent bitfield:
0: No overcurrent.
1: Overcurrent happened. 2ms @ 3000mA
2: Overcurrent happened. 10ms @ 1000mA
3: Overcurrent happened. 40ms @ 400mA
2. Power consumption of target (mA).
3. Peak of target power consumption (mA).
4. Peak of target power consumption during J-Link operation (mA).
Args:
self (JLink): the ``JLink`` instance
mask (int): bit mask to decide which hardware information words are
returned (defaults to all the words).
Returns:
List of bitfields specifying different states based on their index
within the list and their value.
Raises:
JLinkException: on hardware error.
"""
buf = (ctypes.c_uint32 * 32)()
res = self._dll.JLINKARM_GetHWInfo(mask, ctypes.byref(buf))
if res != 0:
raise errors.JLinkException(res)
return list(buf) |
Retrieves and returns the hardware status.
Args:
self (JLink): the ``JLink`` instance
Returns:
A ``JLinkHardwareStatus`` describing the J-Link hardware. | def hardware_status(self):
"""Retrieves and returns the hardware status.
Args:
self (JLink): the ``JLink`` instance
Returns:
A ``JLinkHardwareStatus`` describing the J-Link hardware.
"""
stat = structs.JLinkHardwareStatus()
res = self._dll.JLINKARM_GetHWStatus(ctypes.byref(stat))
if res == 1:
raise errors.JLinkException('Error in reading hardware status.')
return stat |
Returns the hardware version of the connected J-Link as a
major.minor string.
Args:
self (JLink): the ``JLink`` instance
Returns:
Hardware version string. | def hardware_version(self):
"""Returns the hardware version of the connected J-Link as a
major.minor string.
Args:
self (JLink): the ``JLink`` instance
Returns:
Hardware version string.
"""
version = self._dll.JLINKARM_GetHardwareVersion()
major = version / 10000 % 100
minor = version / 100 % 100
return '%d.%02d' % (major, minor) |
Returns a firmware identification string of the connected J-Link.
It consists of the following:
- Product Name (e.g. J-Link)
- The string: compiled
- Compile data and time.
- Optional additional information.
Args:
self (JLink): the ``JLink`` instance
Returns:
Firmware identification string. | def firmware_version(self):
"""Returns a firmware identification string of the connected J-Link.
It consists of the following:
- Product Name (e.g. J-Link)
- The string: compiled
- Compile data and time.
- Optional additional information.
Args:
self (JLink): the ``JLink`` instance
Returns:
Firmware identification string.
"""
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
self._dll.JLINKARM_GetFirmwareString(buf, self.MAX_BUF_SIZE)
return ctypes.string_at(buf).decode() |
Gets the capabilities of the connected emulator as a list.
Args:
self (JLink): the ``JLink`` instance
Returns:
List of 32 integers which define the extended capabilities based on
their value and index within the list. | def extended_capabilities(self):
"""Gets the capabilities of the connected emulator as a list.
Args:
self (JLink): the ``JLink`` instance
Returns:
List of 32 integers which define the extended capabilities based on
their value and index within the list.
"""
buf = (ctypes.c_uint8 * 32)()
self._dll.JLINKARM_GetEmuCapsEx(buf, 32)
return list(buf) |
Returns a list of the J-Link embedded features.
Args:
self (JLink): the ``JLink`` instance
Returns:
A list of strings, each a feature. Example:
``[ 'RDI', 'FlashBP', 'FlashDL', 'JFlash', 'GDB' ]`` | def features(self):
"""Returns a list of the J-Link embedded features.
Args:
self (JLink): the ``JLink`` instance
Returns:
A list of strings, each a feature. Example:
``[ 'RDI', 'FlashBP', 'FlashDL', 'JFlash', 'GDB' ]``
"""
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
self._dll.JLINKARM_GetFeatureString(buf)
result = ctypes.string_at(buf).decode().strip()
if len(result) == 0:
return list()
return result.split(', ') |
Returns the product name of the connected J-Link.
Args:
self (JLink): the ``JLink`` instance
Returns:
Product name. | def product_name(self):
"""Returns the product name of the connected J-Link.
Args:
self (JLink): the ``JLink`` instance
Returns:
Product name.
"""
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
self._dll.JLINKARM_EMU_GetProductName(buf, self.MAX_BUF_SIZE)
return ctypes.string_at(buf).decode() |
Retrieves and returns the OEM string of the connected J-Link.
Args:
self (JLink): the ``JLink`` instance
Returns:
The string of the OEM. If this is an original SEGGER product, then
``None`` is returned instead.
Raises:
JLinkException: on hardware error. | def oem(self):
"""Retrieves and returns the OEM string of the connected J-Link.
Args:
self (JLink): the ``JLink`` instance
Returns:
The string of the OEM. If this is an original SEGGER product, then
``None`` is returned instead.
Raises:
JLinkException: on hardware error.
"""
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
res = self._dll.JLINKARM_GetOEMString(ctypes.byref(buf))
if res != 0:
raise errors.JLinkException('Failed to grab OEM string.')
oem = ctypes.string_at(buf).decode()
if len(oem) == 0:
# In the case that the product is an original SEGGER product, then
# the OEM string is the empty string, so there is no OEM.
return None
return oem |
Sets the speed of the JTAG communication with the ARM core.
If no arguments are present, automatically detects speed.
If a ``speed`` is provided, the speed must be no larger than
``JLink.MAX_JTAG_SPEED`` and no smaller than ``JLink.MIN_JTAG_SPEED``.
The given ``speed`` can also not be ``JLink.INVALID_JTAG_SPEED``.
Args:
self (JLink): the ``JLink`` instance
speed (int): the speed in kHz to set the communication at
auto (bool): automatically detect correct speed
adaptive (bool): select adaptive clocking as JTAG speed
Returns:
``None``
Raises:
TypeError: if given speed is not a natural number.
ValueError: if given speed is too high, too low, or invalid. | def set_speed(self, speed=None, auto=False, adaptive=False):
"""Sets the speed of the JTAG communication with the ARM core.
If no arguments are present, automatically detects speed.
If a ``speed`` is provided, the speed must be no larger than
``JLink.MAX_JTAG_SPEED`` and no smaller than ``JLink.MIN_JTAG_SPEED``.
The given ``speed`` can also not be ``JLink.INVALID_JTAG_SPEED``.
Args:
self (JLink): the ``JLink`` instance
speed (int): the speed in kHz to set the communication at
auto (bool): automatically detect correct speed
adaptive (bool): select adaptive clocking as JTAG speed
Returns:
``None``
Raises:
TypeError: if given speed is not a natural number.
ValueError: if given speed is too high, too low, or invalid.
"""
if speed is None:
speed = 0
elif not util.is_natural(speed):
raise TypeError('Expected positive number for speed, given %s.' % speed)
elif speed > self.MAX_JTAG_SPEED:
raise ValueError('Given speed exceeds max speed of %d.' % self.MAX_JTAG_SPEED)
elif speed < self.MIN_JTAG_SPEED:
raise ValueError('Given speed is too slow. Minimum is %d.' % self.MIN_JTAG_SPEED)
if auto:
speed = speed | self.AUTO_JTAG_SPEED
if adaptive:
speed = speed | self.ADAPTIVE_JTAG_SPEED
self._dll.JLINKARM_SetSpeed(speed)
return None |
Retrieves information about supported target interface speeds.
Args:
self (JLink): the ``JLink`` instance
Returns:
The ``JLinkSpeedInfo`` instance describing the supported target
interface speeds. | def speed_info(self):
"""Retrieves information about supported target interface speeds.
Args:
self (JLink): the ``JLink`` instance
Returns:
The ``JLinkSpeedInfo`` instance describing the supported target
interface speeds.
"""
speed_info = structs.JLinkSpeedInfo()
self._dll.JLINKARM_GetSpeedInfo(ctypes.byref(speed_info))
return speed_info |
Returns a string of the built-in licenses the J-Link has.
Args:
self (JLink): the ``JLink`` instance
Returns:
String of the contents of the built-in licenses the J-Link has. | def licenses(self):
"""Returns a string of the built-in licenses the J-Link has.
Args:
self (JLink): the ``JLink`` instance
Returns:
String of the contents of the built-in licenses the J-Link has.
"""
buf_size = self.MAX_BUF_SIZE
buf = (ctypes.c_char * buf_size)()
res = self._dll.JLINK_GetAvailableLicense(buf, buf_size)
if res < 0:
raise errors.JLinkException(res)
return ctypes.string_at(buf).decode() |
Returns a string of the installed licenses the J-Link has.
Args:
self (JLink): the ``JLink`` instance
Returns:
String of the contents of the custom licenses the J-Link has. | def custom_licenses(self):
"""Returns a string of the installed licenses the J-Link has.
Args:
self (JLink): the ``JLink`` instance
Returns:
String of the contents of the custom licenses the J-Link has.
"""
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
result = self._dll.JLINK_EMU_GetLicenses(buf, self.MAX_BUF_SIZE)
if result < 0:
raise errors.JLinkException(result)
return ctypes.string_at(buf).decode() |
Adds the given ``contents`` as a new custom license to the J-Link.
Args:
self (JLink): the ``JLink`` instance
contents: the string contents of the new custom license
Returns:
``True`` if license was added, ``False`` if license already existed.
Raises:
JLinkException: if the write fails.
Note:
J-Link V9 and J-Link ULTRA/PRO V4 have 336 Bytes of memory for
licenses, while older versions of 80 bytes. | def add_license(self, contents):
"""Adds the given ``contents`` as a new custom license to the J-Link.
Args:
self (JLink): the ``JLink`` instance
contents: the string contents of the new custom license
Returns:
``True`` if license was added, ``False`` if license already existed.
Raises:
JLinkException: if the write fails.
Note:
J-Link V9 and J-Link ULTRA/PRO V4 have 336 Bytes of memory for
licenses, while older versions of 80 bytes.
"""
buf_size = len(contents)
buf = (ctypes.c_char * (buf_size + 1))(*contents.encode())
res = self._dll.JLINK_EMU_AddLicense(buf)
if res == -1:
raise errors.JLinkException('Unspecified error.')
elif res == -2:
raise errors.JLinkException('Failed to read/write license area.')
elif res == -3:
raise errors.JLinkException('J-Link out of space.')
return (res == 0) |
Returns a bitmask of the supported target interfaces.
Args:
self (JLink): the ``JLink`` instance
Returns:
Bitfield specifying which target interfaces are supported. | def supported_tifs(self):
"""Returns a bitmask of the supported target interfaces.
Args:
self (JLink): the ``JLink`` instance
Returns:
Bitfield specifying which target interfaces are supported.
"""
buf = ctypes.c_uint32()
self._dll.JLINKARM_TIF_GetAvailable(ctypes.byref(buf))
return buf.value |
Selects the specified target interface.
Note that a restart must be triggered for this to take effect.
Args:
self (Jlink): the ``JLink`` instance
interface (int): integer identifier of the interface
Returns:
``True`` if target was updated, otherwise ``False``.
Raises:
JLinkException: if the given interface is invalid or unsupported. | def set_tif(self, interface):
"""Selects the specified target interface.
Note that a restart must be triggered for this to take effect.
Args:
self (Jlink): the ``JLink`` instance
interface (int): integer identifier of the interface
Returns:
``True`` if target was updated, otherwise ``False``.
Raises:
JLinkException: if the given interface is invalid or unsupported.
"""
if not ((1 << interface) & self.supported_tifs()):
raise errors.JLinkException('Unsupported target interface: %s' % interface)
# The return code here is actually *NOT* the previous set interface, it
# is ``0`` on success, otherwise ``1``.
res = self._dll.JLINKARM_TIF_Select(interface)
if res != 0:
return False
self._tif = interface
return True |
Returns the properties of the user-controllable GPIOs.
Provided the device supports user-controllable GPIOs, they will be
returned by this method.
Args:
self (JLink): the ``JLink`` instance
Returns:
A list of ``JLinkGPIODescriptor`` instances totalling the number of
requested properties.
Raises:
JLinkException: on error. | def gpio_properties(self):
"""Returns the properties of the user-controllable GPIOs.
Provided the device supports user-controllable GPIOs, they will be
returned by this method.
Args:
self (JLink): the ``JLink`` instance
Returns:
A list of ``JLinkGPIODescriptor`` instances totalling the number of
requested properties.
Raises:
JLinkException: on error.
"""
res = self._dll.JLINK_EMU_GPIO_GetProps(0, 0)
if res < 0:
raise errors.JLinkException(res)
num_props = res
buf = (structs.JLinkGPIODescriptor * num_props)()
res = self._dll.JLINK_EMU_GPIO_GetProps(ctypes.byref(buf), num_props)
if res < 0:
raise errors.JLinkException(res)
return list(buf) |
Returns a list of states for the given pins.
Defaults to the first four pins if an argument is not given.
Args:
self (JLink): the ``JLink`` instance
pins (list): indices of the GPIO pins whose states are requested
Returns:
A list of states.
Raises:
JLinkException: on error. | def gpio_get(self, pins=None):
"""Returns a list of states for the given pins.
Defaults to the first four pins if an argument is not given.
Args:
self (JLink): the ``JLink`` instance
pins (list): indices of the GPIO pins whose states are requested
Returns:
A list of states.
Raises:
JLinkException: on error.
"""
if pins is None:
pins = range(4)
size = len(pins)
indices = (ctypes.c_uint8 * size)(*pins)
statuses = (ctypes.c_uint8 * size)()
result = self._dll.JLINK_EMU_GPIO_GetState(ctypes.byref(indices),
ctypes.byref(statuses),
size)
if result < 0:
raise errors.JLinkException(result)
return list(statuses) |
Sets the state for one or more user-controllable GPIOs.
For each of the given pins, sets the the corresponding state based on
the index.
Args:
self (JLink): the ``JLink`` instance
pins (list): list of GPIO indices
states (list): list of states to set
Returns:
A list of updated states.
Raises:
JLinkException: on error.
ValueError: if ``len(pins) != len(states)`` | def gpio_set(self, pins, states):
"""Sets the state for one or more user-controllable GPIOs.
For each of the given pins, sets the the corresponding state based on
the index.
Args:
self (JLink): the ``JLink`` instance
pins (list): list of GPIO indices
states (list): list of states to set
Returns:
A list of updated states.
Raises:
JLinkException: on error.
ValueError: if ``len(pins) != len(states)``
"""
if len(pins) != len(states):
raise ValueError('Length mismatch between pins and states.')
size = len(pins)
indices = (ctypes.c_uint8 * size)(*pins)
states = (ctypes.c_uint8 * size)(*states)
result_states = (ctypes.c_uint8 * size)()
result = self._dll.JLINK_EMU_GPIO_SetState(ctypes.byref(indices),
ctypes.byref(states),
ctypes.byref(result_states),
size)
if result < 0:
raise errors.JLinkException(result)
return list(result_states) |
Unlocks the device connected to the J-Link.
Unlocking a device allows for access to read/writing memory, as well as
flash programming.
Note:
Unlock is not supported on all devices.
Supported Devices:
Kinetis
Returns:
``True``.
Raises:
JLinkException: if the device fails to unlock. | def unlock(self):
"""Unlocks the device connected to the J-Link.
Unlocking a device allows for access to read/writing memory, as well as
flash programming.
Note:
Unlock is not supported on all devices.
Supported Devices:
Kinetis
Returns:
``True``.
Raises:
JLinkException: if the device fails to unlock.
"""
if not unlockers.unlock(self, self._device.manufacturer):
raise errors.JLinkException('Failed to unlock device.')
return True |
Subsets and Splits