INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns the matrix for transforming struct to supercell. This can be used for very distorted supercells where the primitive cell is impossible to find | def get_supercell_matrix(self, supercell, struct):
"""
Returns the matrix for transforming struct to supercell. This
can be used for very distorted 'supercells' where the primitive cell
is impossible to find
"""
if self._primitive_cell:
raise ValueError("get_s... |
Returns the supercell transformation fractional translation vector and a mapping to transform struct2 to be similar to struct1. | def get_transformation(self, struct1, struct2):
"""
Returns the supercell transformation, fractional translation vector,
and a mapping to transform struct2 to be similar to struct1.
Args:
struct1 (Structure): Reference structure
struct2 (Structure): Structure to ... |
Performs transformations on struct2 to put it in a basis similar to struct1 ( without changing any of the inter - site distances ) | def get_s2_like_s1(self, struct1, struct2, include_ignored_species=True):
"""
Performs transformations on struct2 to put it in a basis similar to
struct1 (without changing any of the inter-site distances)
Args:
struct1 (Structure): Reference structure
struct2 (St... |
Calculate the mapping from superset to subset. | def get_mapping(self, superset, subset):
"""
Calculate the mapping from superset to subset.
Args:
superset (Structure): Structure containing at least the sites in
subset (within the structure matching tolerance)
subset (Structure): Structure containing so... |
Args: d1: First defect. A pymatgen Defect object. d2: Second defect. A pymatgen Defect object. | def are_equal(self, d1, d2):
"""
Args:
d1: First defect. A pymatgen Defect object.
d2: Second defect. A pymatgen Defect object.
Returns:
True if defects are identical in type and sublattice.
"""
possible_defect_types = (Defect, Vacancy, Substi... |
Convenience constructor to make a ConversionElectrode from a composition and a phase diagram. | def from_composition_and_pd(comp, pd, working_ion_symbol="Li"):
"""
Convenience constructor to make a ConversionElectrode from a
composition and a phase diagram.
Args:
comp:
Starting composition for ConversionElectrode, e.g.,
Composition("FeF3... |
Convenience constructor to make a ConversionElectrode from a composition and all entries in a chemical system. | def from_composition_and_entries(comp, entries_in_chemsys,
working_ion_symbol="Li"):
"""
Convenience constructor to make a ConversionElectrode from a
composition and all entries in a chemical system.
Args:
comp: Starting composition for C... |
If this electrode contains multiple voltage steps then it is possible to use only a subset of the voltage steps to define other electrodes. For example an LiTiO2 electrode might contain three subelectrodes: [ LiTiO2 -- > TiO2 LiTiO2 -- > Li0. 5TiO2 Li0. 5TiO2 -- > TiO2 ] This method can be used to return all the subele... | def get_sub_electrodes(self, adjacent_only=True):
"""
If this electrode contains multiple voltage steps, then it is possible
to use only a subset of the voltage steps to define other electrodes.
For example, an LiTiO2 electrode might contain three subelectrodes:
[LiTiO2 --> TiO2,... |
Checks if a particular conversion electrode is a sub electrode of the current electrode. Starting from a more lithiated state may result in a subelectrode that is essentially on the same path. For example a ConversionElectrode formed by starting from an FePO4 composition would be a super_electrode of a ConversionElectr... | def is_super_electrode(self, conversion_electrode):
"""
Checks if a particular conversion electrode is a sub electrode of the
current electrode. Starting from a more lithiated state may result in
a subelectrode that is essentially on the same path. For example, a
ConversionElect... |
Args: print_subelectrodes: Also print data on all the possible subelectrodes | def get_summary_dict(self, print_subelectrodes=True):
"""
Args:
print_subelectrodes:
Also print data on all the possible subelectrodes
Returns:
a summary of this electrode"s properties in dictionary format
"""
d = {}
framework_com... |
Creates a ConversionVoltagePair from two steps in the element profile from a PD analysis. | def from_steps(step1, step2, normalization_els):
"""
Creates a ConversionVoltagePair from two steps in the element profile
from a PD analysis.
Args:
step1: Starting step
step2: Ending step
normalization_els: Elements to normalize the reaction by. To
... |
Creates an Xr object from a string representation. | def from_string(string, use_cores=True, thresh=1.e-4):
"""
Creates an Xr object from a string representation.
Args:
string (str): string representation of an Xr object.
use_cores (bool): use core positions and discard shell
positions if set to True (d... |
Reads an xr - formatted file to create an Xr object. | def from_file(filename, use_cores=True, thresh=1.e-4):
"""
Reads an xr-formatted file to create an Xr object.
Args:
filename (str): name of file to read from.
use_cores (bool): use core positions and discard shell
positions if set to True (default). ... |
Frame a signal into overlapping frames. | def framesig(sig, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,)), stride_trick=True):
"""Frame a signal into overlapping frames.
:param sig: the audio signal to frame.
:param frame_len: length of each frame measured in samples.
:param frame_step: number of samples after the start of the prev... |
Does overlap - add procedure to undo the action of framesig. | def deframesig(frames, siglen, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,))):
"""Does overlap-add procedure to undo the action of framesig.
:param frames: the array of frames.
:param siglen: the length of the desired signal, use 0 if unknown. Output will be truncated to siglen samples.
:pa... |
Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix output will be Nx ( NFFT/ 2 + 1 ). | def magspec(frames, NFFT):
"""Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1).
:param frames: the array of frames. Each row is a frame.
:param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded.
:returns: If frame... |
Compute the log power spectrum of each frame in frames. If frames is an NxD matrix output will be Nx ( NFFT/ 2 + 1 ). | def logpowspec(frames, NFFT, norm=1):
"""Compute the log power spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1).
:param frames: the array of frames. Each row is a frame.
:param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded.
:param ... |
Calculates the FFT size as a power of two greater than or equal to the number of samples in a single window length. Having an FFT less than the window length loses precision by dropping many of the samples ; a longer FFT than the window allows zero - padding of the FFT buffer which is neutral in terms of frequency doma... | def calculate_nfft(samplerate, winlen):
"""Calculates the FFT size as a power of two greater than or equal to
the number of samples in a single window length.
Having an FFT less than the window length loses precision by dropping
many of the samples; a longer FFT than the window allows zero-padding
... |
Compute MFCC features from an audio signal. | def mfcc(signal,samplerate=16000,winlen=0.025,winstep=0.01,numcep=13,
nfilt=26,nfft=None,lowfreq=0,highfreq=None,preemph=0.97,ceplifter=22,appendEnergy=True,
winfunc=lambda x:numpy.ones((x,))):
"""Compute MFCC features from an audio signal.
:param signal: the audio signal from which to comput... |
Compute Mel - filterbank energy features from an audio signal. | def fbank(signal,samplerate=16000,winlen=0.025,winstep=0.01,
nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97,
winfunc=lambda x:numpy.ones((x,))):
"""Compute Mel-filterbank energy features from an audio signal.
:param signal: the audio signal from which to compute features. Should be ... |
Compute log Mel - filterbank energy features from an audio signal. | def logfbank(signal,samplerate=16000,winlen=0.025,winstep=0.01,
nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97,
winfunc=lambda x:numpy.ones((x,))):
"""Compute log Mel-filterbank energy features from an audio signal.
:param signal: the audio signal from which to compute feature... |
Compute Spectral Subband Centroid features from an audio signal. | def ssc(signal,samplerate=16000,winlen=0.025,winstep=0.01,
nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97,
winfunc=lambda x:numpy.ones((x,))):
"""Compute Spectral Subband Centroid features from an audio signal.
:param signal: the audio signal from which to compute features. Should be an... |
Compute a Mel - filterbank. The filters are stored in the rows the columns correspond to fft bins. The filters are returned as an array of size nfilt * ( nfft/ 2 + 1 ) | def get_filterbanks(nfilt=20,nfft=512,samplerate=16000,lowfreq=0,highfreq=None):
"""Compute a Mel-filterbank. The filters are stored in the rows, the columns correspond
to fft bins. The filters are returned as an array of size nfilt * (nfft/2 + 1)
:param nfilt: the number of filters in the filterbank, defa... |
Apply a cepstral lifter the the matrix of cepstra. This has the effect of increasing the magnitude of the high frequency DCT coeffs. | def lifter(cepstra, L=22):
"""Apply a cepstral lifter the the matrix of cepstra. This has the effect of increasing the
magnitude of the high frequency DCT coeffs.
:param cepstra: the matrix of mel-cepstra, will be numframes * numcep in size.
:param L: the liftering coefficient to use. Default is 22. L ... |
Compute delta features from a feature vector sequence. | def delta(feat, N):
"""Compute delta features from a feature vector sequence.
:param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector.
:param N: For each frame, calculate delta features based on preceding and following N frames
:returns:... |
Opens a CAN connection using CanalOpen (). | def open(self, configuration, flags):
"""
Opens a CAN connection using `CanalOpen()`.
:param str configuration: the configuration: "device_id; baudrate"
:param int flags: the flags to be set
:raises can.CanError: if any error occurred
:returns: Valid handle for CANAL AP... |
Fetches all messages in the database. | def read_all(self):
"""Fetches all messages in the database.
:rtype: Generator[can.Message]
"""
result = self._cursor.execute("SELECT * FROM {}".format(self.table_name)).fetchall()
return (SqliteReader._assemble_message(frame) for frame in result) |
Creates a new databae or opens a connection to an existing one. | def _create_db(self):
"""Creates a new databae or opens a connection to an existing one.
.. note::
You can't share sqlite3 connections between threads (by default)
hence we setup the db here. It has the upside of running async.
"""
log.debug("Creating sqlite data... |
Stops the reader an writes all remaining messages to the database. Thus this might take a while and block. | def stop(self):
"""Stops the reader an writes all remaining messages to the database. Thus, this
might take a while and block.
"""
BufferedReader.stop(self)
self._stop_running_event.set()
self._writer_thread.join()
BaseIOHandler.stop(self) |
Checks if the message parameters are valid. Assumes that the types are already correct. | def _check(self):
"""Checks if the message parameters are valid.
Assumes that the types are already correct.
:raises ValueError: iff one or more attributes are invalid
"""
if self.timestamp < 0.0:
raise ValueError("the timestamp may not be negative")
if isin... |
Compares a given message with this one. | def equals(self, other, timestamp_delta=1.0e-6):
"""
Compares a given message with this one.
:param can.Message other: the message to compare with
:type timestamp_delta: float or int or None
:param timestamp_delta: the maximum difference at which two timestamps are
... |
Map and return a symbol ( function ) from a C library. A reference to the mapped symbol is also held in the instance | def map_symbol(self, func_name, restype=None, argtypes=(), errcheck=None):
"""
Map and return a symbol (function) from a C library. A reference to the
mapped symbol is also held in the instance
:param str func_name:
symbol_name
:param ctypes.c_* restype:
... |
Decode ( if needed ) and return the ICS device serial string | def get_serial_number(device):
"""Decode (if needed) and return the ICS device serial string
:param device: ics device
:return: ics device serial string
:rtype: str
"""
a0000 = 604661760
if device.SerialNumber >= a0000:
return ics.base36enc(device.Ser... |
Detect all configurations/ channels that this interface could currently connect with. | def _detect_available_configs():
"""Detect all configurations/channels that this interface could
currently connect with.
:rtype: Iterator[dict]
:return: an iterable of dicts, each being a configuration suitable
for usage in the interface's bus constructor.
"""
... |
CAN frame packing/ unpacking ( see struct can_frame in <linux/ can. h > )/ ** * struct can_frame - basic CAN frame structure * @can_id: the CAN ID of the frame and CAN_ * _FLAG flags see above. * @can_dlc: the data length field of the CAN frame * @data: the CAN frame payload. */ struct can_frame { canid_t can_id ;/ * 3... | def build_can_frame(msg):
""" CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)
/**
* struct can_frame - basic CAN frame structure
* @can_id: the CAN ID of the frame and CAN_*_FLAG flags, see above.
* @can_dlc: the data length field of the CAN frame
* @data: the CAN f... |
create a broadcast manager socket and connect to the given interface | def create_bcm_socket(channel):
"""create a broadcast manager socket and connect to the given interface"""
s = socket.socket(PF_CAN, socket.SOCK_DGRAM, CAN_BCM)
if HAS_NATIVE_SUPPORT:
s.connect((channel,))
else:
addr = get_addr(s, channel)
libc.connect(s.fileno(), addr, len(addr)... |
Send raw frame to a BCM socket and handle errors. | def send_bcm(bcm_socket, data):
"""
Send raw frame to a BCM socket and handle errors.
"""
try:
return bcm_socket.send(data)
except OSError as e:
base = "Couldn't send CAN BCM frame. OS Error {}: {}\n".format(e.errno, e.strerror)
if e.errno == errno.EINVAL:
raise ... |
Creates a raw CAN socket. The socket will be returned unbound to any interface. | def create_socket():
"""Creates a raw CAN socket. The socket will
be returned unbound to any interface.
"""
sock = socket.socket(PF_CAN, socket.SOCK_RAW, CAN_RAW)
log.info('Created a socket')
return sock |
Binds the given socket to the given interface. | def bind_socket(sock, channel='can0'):
"""
Binds the given socket to the given interface.
:param socket.socket sock:
The socket to be bound
:raises OSError:
If the specified interface isn't found.
"""
log.debug('Binding socket to channel=%s', channel)
if HAS_NATIVE_SUPPORT:
... |
Captures a message from given socket. | def capture_message(sock, get_channel=False):
"""
Captures a message from given socket.
:param socket.socket sock:
The socket to read a message from.
:param bool get_channel:
Find out which channel the message comes from.
:return: The received message, or None on failure.
"""
... |
Send a TX_DELETE message to cancel this task. | def stop(self):
"""Send a TX_DELETE message to cancel this task.
This will delete the entry for the transmission of the CAN-message
with the specified can_id CAN identifier. The message length for the command
TX_DELETE is {[bcm_msg_head]} (only the header).
"""
log.debug... |
Update the contents of this periodically sent message. | def modify_data(self, message):
"""Update the contents of this periodically sent message.
Note the Message must have the same :attr:`~can.Message.arbitration_id`
like the first message.
"""
assert message.arbitration_id == self.can_id, "You cannot modify the can identifier"
... |
Stops all active periodic tasks and closes the socket. | def shutdown(self):
"""Stops all active periodic tasks and closes the socket."""
self.stop_all_periodic_tasks()
for channel in self._bcm_sockets:
log.debug("Closing bcm socket for channel {}".format(channel))
bcm_socket = self._bcm_sockets[channel]
bcm_socket.... |
Transmit a message to the CAN bus. | def send(self, msg, timeout=None):
"""Transmit a message to the CAN bus.
:param can.Message msg: A message object.
:param float timeout:
Wait up to this many seconds for the transmit queue to be ready.
If not given, the call may fail immediately.
:raises can.Can... |
Start sending a message at a given period on this bus. | def _send_periodic_internal(self, msg, period, duration=None):
"""Start sending a message at a given period on this bus.
The kernel's broadcast manager will be used.
:param can.Message msg:
Message to transmit
:param float period:
Period in seconds between each ... |
Finds a list of USB devices where the serial number ( partially ) matches the given string. | def find_serial_devices(serial_matcher="ED"):
"""
Finds a list of USB devices where the serial number (partially) matches the given string.
:param str serial_matcher (optional):
only device IDs starting with this string are returned
:rtype: List[str]
"""
objWMIService = win32com.client... |
Returns the names of all open can/ vcan interfaces using the ip link list command. If the lookup fails an error is logged to the console and an empty list is returned. | def find_available_interfaces():
"""Returns the names of all open can/vcan interfaces using
the ``ip link list`` command. If the lookup fails, an error
is logged to the console and an empty list is returned.
:rtype: an iterable of :class:`str`
"""
try:
# it might be good to add "type v... |
Converts a given error code ( errno ) to a useful and human readable string. | def error_code_to_str(code):
"""
Converts a given error code (errno) to a useful and human readable string.
:param int code: a possibly invalid/unknown error code
:rtype: str
:returns: a string explaining and containing the given error code, or a string
explaining that the errorcode i... |
Spam the bus with messages including the data id. | def producer(id, message_count=16):
"""Spam the bus with messages including the data id.
:param int id: the id of the thread/process
"""
with can.Bus(bustype='socketcan', channel='vcan0') as bus:
for i in range(message_count):
msg = can.Message(arbitration_id=0x0cf02200+id, data=[i... |
Append a message to the buffer. | def on_message_received(self, msg):
"""Append a message to the buffer.
:raises: BufferError
if the reader has already been stopped
"""
if self.is_stopped:
raise RuntimeError("reader has already been stopped")
else:
self.buffer.put(msg) |
Attempts to retrieve the latest message received by the instance. If no message is available it blocks for given timeout or until a message is received or else returns None ( whichever is shorter ). This method does not block after: meth: can. BufferedReader. stop has been called. | def get_message(self, timeout=0.5):
"""
Attempts to retrieve the latest message received by the instance. If no message is
available it blocks for given timeout or until a message is received, or else
returns None (whichever is shorter). This method does not block after
:meth:`ca... |
Gets the text using the GetErrorText API function. If the function call succeeds the translated error is returned. If it fails a text describing the current error is returned. Multiple errors may be present in which case their individual messages are included in the return string one line per error. | def _get_formatted_error(self, error):
"""
Gets the text using the GetErrorText API function.
If the function call succeeds, the translated error is returned. If it fails,
a text describing the current error is returned. Multiple errors may
be present in which case their individu... |
Command the PCAN driver to reset the bus after an error. | def reset(self):
"""
Command the PCAN driver to reset the bus after an error.
"""
status = self.m_objPCANBasic.Reset(self.m_PcanHandle)
return status == PCAN_ERROR_OK |
Turn on or off flashing of the device s LED for physical identification purposes. | def flash(self, flash):
"""
Turn on or off flashing of the device's LED for physical
identification purposes.
"""
self.m_objPCANBasic.SetValue(self.m_PcanHandle, PCAN_CHANNEL_IDENTIFYING, bool(flash)) |
Convert status code to descriptive string. | def get_error_message(status_code):
"""Convert status code to descriptive string."""
errmsg = ctypes.create_string_buffer(1024)
nican.ncStatusToString(status_code, len(errmsg), errmsg)
return errmsg.value.decode("ascii") |
Read a message from a NI - CAN bus. | def _recv_internal(self, timeout):
"""
Read a message from a NI-CAN bus.
:param float timeout:
Max time to wait in seconds or None if infinite
:raises can.interfaces.nican.NicanError:
If reception fails
"""
if timeout is None:
timeout... |
Send a message to NI - CAN. | def send(self, msg, timeout=None):
"""
Send a message to NI-CAN.
:param can.Message msg:
Message to send
:raises can.interfaces.nican.NicanError:
If writing to transmit buffer fails.
It does not wait for message to be ACKed currently.
"""
... |
Unsupported. See note on: class: ~can. interfaces. nican. NicanBus. | def set_filters(self, can_filers=None):
"""Unsupported. See note on :class:`~can.interfaces.nican.NicanBus`.
"""
if self.__set_filters_has_been_called:
logger.warn("using filters is not supported like this, see note on NicanBus")
else:
# allow the constructor to c... |
Send a: class: ~can. Message every period seconds on the given bus. | def send_periodic(bus, message, period, *args, **kwargs):
"""
Send a :class:`~can.Message` every `period` seconds on the given bus.
:param can.BusABC bus: A CAN bus which supports sending.
:param can.Message message: Message to send periodically.
:param float period: The minimum time between sendin... |
Read a message from kvaser device and return whether filtering has taken place. | def _recv_internal(self, timeout=None):
"""
Read a message from kvaser device and return whether filtering has taken place.
"""
arb_id = ctypes.c_long(0)
data = ctypes.create_string_buffer(64)
dlc = ctypes.c_uint(0)
flags = ctypes.c_uint(0)
timestamp = cty... |
Turn on or off flashing of the device s LED for physical identification purposes. | def flash(self, flash=True):
"""
Turn on or off flashing of the device's LED for physical
identification purposes.
"""
if flash:
action = canstat.kvLED_ACTION_ALL_LEDS_ON
else:
action = canstat.kvLED_ACTION_ALL_LEDS_OFF
try:
kv... |
Retrieves the bus statistics. | def get_stats(self):
"""Retrieves the bus statistics.
Use like so:
>>> stats = bus.get_stats()
>>> print(stats)
std_data: 0, std_remote: 0, ext_data: 0, ext_remote: 0, err_frame: 0, bus_load: 0.0%, overruns: 0
:returns: bus statistics.
:rtype: can.interfaces.kv... |
Format a VCI error and attach failed function decoded HRESULT and arguments: param CLibrary library_instance: Mapped instance of IXXAT vcinpl library: param callable function: Failed function: param HRESULT HRESULT: HRESULT returned by vcinpl call: param arguments: Arbitrary arguments tuple: return: Formatted string | def __vciFormatErrorExtended(library_instance, function, HRESULT, arguments):
""" Format a VCI error and attach failed function, decoded HRESULT and arguments
:param CLibrary library_instance:
Mapped instance of IXXAT vcinpl library
:param callable function:
Failed function
... |
Format a VCI error and attach failed function and decoded HRESULT: param CLibrary library_instance: Mapped instance of IXXAT vcinpl library: param callable function: Failed function: param HRESULT HRESULT: HRESULT returned by vcinpl call: return: Formatted string | def __vciFormatError(library_instance, function, HRESULT):
""" Format a VCI error and attach failed function and decoded HRESULT
:param CLibrary library_instance:
Mapped instance of IXXAT vcinpl library
:param callable function:
Failed function
:param HRESULT HRESULT:... |
Check the result of a vcinpl function call and raise appropriate exception in case of an error. Used as errcheck function when mapping C functions with ctypes.: param result: Function call numeric result: param callable function: Called function: param arguments: Arbitrary arguments tuple: raise:: class: VCITimeout: cl... | def __check_status(result, function, arguments):
"""
Check the result of a vcinpl function call and raise appropriate exception
in case of an error. Used as errcheck function when mapping C functions
with ctypes.
:param result:
Function call numeric result
:param callable fun... |
Read a message from IXXAT device. | def _recv_internal(self, timeout):
""" Read a message from IXXAT device. """
# TODO: handling CAN error messages?
data_received = False
if timeout == 0:
# Peek without waiting
try:
_canlib.canChannelPeekMessage(self._channel_handle, ctypes.byref(... |
Send a message using built - in cyclic transmit list functionality. | def _send_periodic_internal(self, msg, period, duration=None):
"""Send a message using built-in cyclic transmit list functionality."""
if self._scheduler is None:
self._scheduler = HANDLE()
_canlib.canSchedulerOpen(self._device_handle, self.channel,
... |
Unsupported. See note on: class: ~can. interfaces. ixxat. IXXATBus. | def set_filters(self, can_filers=None):
"""Unsupported. See note on :class:`~can.interfaces.ixxat.IXXATBus`.
"""
if self.__set_filters_has_been_called:
log.warn("using filters is not supported like this, see note on IXXATBus")
else:
# allow the constructor to call... |
Start transmitting message ( add to list if needed ). | def start(self):
"""Start transmitting message (add to list if needed)."""
if self._index is None:
self._index = ctypes.c_uint32()
_canlib.canSchedulerAddMessage(self._scheduler,
self._msg,
self... |
Stop transmitting message ( remove from list ). | def stop(self):
"""Stop transmitting message (remove from list)."""
# Remove it completely instead of just stopping it to avoid filling up
# the list with permanently stopped messages
_canlib.canSchedulerRemMessage(self._scheduler, self._index)
self._index = None |
Add an arbitrary message to the log file as a global marker. | def log_event(self, text, timestamp=None):
"""Add an arbitrary message to the log file as a global marker.
:param str text:
The group name of the marker.
:param float timestamp:
Absolute timestamp in Unix timestamp format. If not given, the
marker will be pla... |
Compresses and writes data in the cache to file. | def _flush(self):
"""Compresses and writes data in the cache to file."""
if self.file.closed:
return
cache = b"".join(self.cache)
if not cache:
# Nothing to write
return
uncompressed_data = cache[:self.MAX_CACHE_SIZE]
# Save data that c... |
Stops logging and closes the file. | def stop(self):
"""Stops logging and closes the file."""
self._flush()
filesize = self.file.tell()
super(BLFWriter, self).stop()
# Write header in the beginning of the file
header = [b"LOGG", FILE_HEADER_SIZE,
APPLICATION_ID, 0, 0, 0, 2, 6, 8, 1]
... |
Initializes a PCAN Channel | def Initialize(
self,
Channel,
Btr0Btr1,
HwType = TPCANType(0),
IOPort = c_uint(0),
Interrupt = c_ushort(0)):
"""
Initializes a PCAN Channel
Parameters:
Channel : A TPCANHandle representing a PCAN Channel
Btr0Btr1 : The spe... |
Initializes a FD capable PCAN Channel | def InitializeFD(
self,
Channel,
BitrateFD):
"""
Initializes a FD capable PCAN Channel
Parameters:
Channel : The handle of a FD capable PCAN Channel
BitrateFD : The speed for the communication (FD bit rate string)
Remarks:
See PCAN_BR_*... |
Uninitializes one or all PCAN Channels initialized by CAN_Initialize | def Uninitialize(
self,
Channel):
"""
Uninitializes one or all PCAN Channels initialized by CAN_Initialize
Remarks:
Giving the TPCANHandle value "PCAN_NONEBUS", uninitialize all initialized channels
Parameters:
Channel : A TPCANHandle representin... |
Resets the receive and transmit queues of the PCAN Channel | def Reset(
self,
Channel):
"""
Resets the receive and transmit queues of the PCAN Channel
Remarks:
A reset of the CAN controller is not performed
Parameters:
Channel : A TPCANHandle representing a PCAN Channel
Returns:
A TPCANS... |
Gets the current status of a PCAN Channel | def GetStatus(
self,
Channel):
"""
Gets the current status of a PCAN Channel
Parameters:
Channel : A TPCANHandle representing a PCAN Channel
Returns:
A TPCANStatus error code
"""
try:
res = self.__m_dllBasic.CAN_GetSta... |
Reads a CAN message from the receive queue of a PCAN Channel | def Read(
self,
Channel):
"""
Reads a CAN message from the receive queue of a PCAN Channel
Remarks:
The return value of this method is a 3-touple, where
the first value is the result (TPCANStatus) of the method.
The order of the values are:
... |
Reads a CAN message from the receive queue of a FD capable PCAN Channel | def ReadFD(
self,
Channel):
"""
Reads a CAN message from the receive queue of a FD capable PCAN Channel
Remarks:
The return value of this method is a 3-touple, where
the first value is the result (TPCANStatus) of the method.
The order of the valu... |
Transmits a CAN message | def Write(
self,
Channel,
MessageBuffer):
"""
Transmits a CAN message
Parameters:
Channel : A TPCANHandle representing a PCAN Channel
MessageBuffer: A TPCANMsg representing the CAN message to be sent
Returns:
A TPCANStatus e... |
Transmits a CAN message over a FD capable PCAN Channel | def WriteFD(
self,
Channel,
MessageBuffer):
"""
Transmits a CAN message over a FD capable PCAN Channel
Parameters:
Channel : The handle of a FD capable PCAN Channel
MessageBuffer: A TPCANMsgFD buffer with the message to be sent
Return... |
Configures the reception filter | def FilterMessages(
self,
Channel,
FromID,
ToID,
Mode):
"""
Configures the reception filter
Remarks:
The message filter will be expanded with every call to this function.
If it is desired to reset the filter, please use the 'SetValu... |
Retrieves a PCAN Channel value | def GetValue(
self,
Channel,
Parameter):
"""
Retrieves a PCAN Channel value
Remarks:
Parameters can be present or not according with the kind
of Hardware (PCAN Channel) being used. If a parameter is not available,
a PCAN_ERROR_ILLPARAMTYP... |
Returns a descriptive text of a given TPCANStatus error code in any desired language | def SetValue(
self,
Channel,
Parameter,
Buffer):
"""
Returns a descriptive text of a given TPCANStatus error
code, in any desired language
Remarks:
Parameters can be present or not according with the kind
of Hardware (PCAN Channel... |
Configures or sets a PCAN Channel value | def GetErrorText(
self,
Error,
Language = 0):
"""
Configures or sets a PCAN Channel value
Remarks:
The current languages available for translation are:
Neutral (0x00), German (0x07), English (0x09), Spanish (0x0A),
Italian (0x10) and Fre... |
Add a message to the log file. | def log_event(self, message, timestamp=None):
"""Add a message to the log file.
:param str message: an arbitrary message
:param float timestamp: the absolute timestamp of the event
"""
if not message: # if empty or None
logger.debug("ASCWriter: ignoring empty messag... |
Returns all currently used channels as well as one other currently unused channel. | def _detect_available_configs():
"""
Returns all currently used channels as well as
one other currently unused channel.
.. note::
This method will run into problems if thousands of
autodetected busses are used at once.
"""
with channels_lock:
... |
convert the message from the CANAL type to pythoncan type | def message_convert_rx(message_rx):
"""convert the message from the CANAL type to pythoncan type"""
is_extended_id = bool(message_rx.flags & IS_ID_TYPE)
is_remote_frame = bool(message_rx.flags & IS_REMOTE_FRAME)
is_error_frame = bool(message_rx.flags & IS_ERROR_FRAME)
return Message(timestamp=messa... |
Shuts down connection to the device safely. | def shutdown(self):
"""
Shuts down connection to the device safely.
:raise cam.CanError: is closing the connection did not work
"""
status = self.can.close(self.handle)
if status != CANAL_ERROR_SUCCESS:
raise CanError("could not shut down bus: status == {}".... |
Uses the Windows Management Instrumentation to identify serial devices. | def _detect_available_configs(serial_matcher=None):
"""
Uses the Windows Management Instrumentation to identify serial devices.
:param str serial_matcher (optional):
search string for automatic detection of the device serial
"""
if serial_matcher:
channel... |
Returns the main bus class for the given interface. | def _get_class_for_interface(interface):
"""
Returns the main bus class for the given interface.
:raises:
NotImplementedError if the interface is not known
:raises:
ImportError if there was a problem while importing the
interface or the bus class within that
... |
Detect all configurations/ channels that the interfaces could currently connect with. | def detect_available_configs(interfaces=None):
"""Detect all configurations/channels that the interfaces could
currently connect with.
This might be quite time consuming.
Automated configuration detection may not be implemented by
every interface on every platform. This method will not raise
a... |
Add a bus for notification. | def add_bus(self, bus):
"""Add a bus for notification.
:param can.BusABC bus:
CAN bus instance.
"""
if self._loop is not None and hasattr(bus, 'fileno') and bus.fileno() >= 0:
# Use file descriptor to watch for messages
reader = bus.fileno()
... |
Stop notifying Listeners when new: class: ~can. Message objects arrive and call: meth: ~can. Listener. stop on each Listener. | def stop(self, timeout=5):
"""Stop notifying Listeners when new :class:`~can.Message` objects arrive
and call :meth:`~can.Listener.stop` on each Listener.
:param float timeout:
Max time in seconds to wait for receive threads to finish.
Should be longer than timeout given... |
Send a message over the serial device. | def send(self, msg, timeout=None):
"""
Send a message over the serial device.
:param can.Message msg:
Message to send.
.. note:: Flags like ``extended_id``, ``is_remote_frame`` and
``is_error_frame`` will be ignored.
.. note:: If the t... |
Read a message from the serial device. | def _recv_internal(self, timeout):
"""
Read a message from the serial device.
:param timeout:
.. warning::
This parameter will be ignored. The timeout value of the channel is used.
:returns:
Received message and False (because not filtering as t... |
Sends a message every 20ms with no explicit timeout Sleeps for 2 seconds then stops the task. | def simple_periodic_send(bus):
"""
Sends a message every 20ms with no explicit timeout
Sleeps for 2 seconds then stops the task.
"""
print("Starting to send a message every 200ms for 2s")
msg = can.Message(arbitration_id=0x123, data=[1, 2, 3, 4, 5, 6], is_extended_id=False)
task = bus.send_p... |
Sends one CAN message. | def send(self, msg, timeout=None):
"""
Sends one CAN message.
When a transmission timeout is set the firmware tries to send
a message within this timeout. If it could not be sent the firmware sets
the "auto delete" state. Within this state all transmit CAN messages for
t... |
Flushes the transmit buffer. | def flush_tx_buffer(self):
"""
Flushes the transmit buffer.
:raises can.CanError:
If flushing of the transmit buffer failed.
"""
log.info('Flushing transmit buffer')
self._ucan.reset_can(self.channel, ResetFlags.RESET_ONLY_TX_BUFF) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.