Decoder

Decode a cuplcodec URL

The decoder extracts a timestamped list of samples from a cuplcodec URL.

wscodec.decoder.decoderfactory._get_decoder(formatcode: int)[source]
Parameters

formatcode – Value of the codec format field. Specifies which decoder shall be returned.

Returns

Return type

Decoder class for the given format code.

wscodec.decoder.decoderfactory.decode(secretkey: str, statb64: str, timeintb64: str, circb64: str, vfmtb64: str, usehmac: bool = True, scantimestamp: Optional[datetime.datetime] = None)wscodec.decoder.samples.SamplesURL[source]

Decode the version string and extract codec version and format code. An error is raised if the codec version does not match. A decoder object is returned based on the format code. An error is raised if no decoder is available for the code.

Parameters
  • secretkey (str) – HMAC secret key as a string. Normally 16 characters long.

  • statb64 (str) – Value of the URL parameter that holds status information (base64 encoded).

  • timeintb64 (str) – Value of the URL parameter that holds the time interval between samples in minutes (base64 encoded).

  • circb64 (str) – Value of the URL parameter that contains the circular buffer of base64 encoded samples.

  • vfmtb64 (str) – Value of the URL parameter that contains the version and format string (base64 encoded).

  • usehmac (bool) – True if the hash inside the circular buffer endstop is HMAC-MD5. False if it is MD5.

  • scantimestamp (datetime) – The time that the tag was scanned. All decoded samples will be timestamped relative to this.

Returns

An object containing a list of timestamped environmental sensor samples.

Return type

SamplesURL

Inheritance diagram of wscodec.decoder.hdc2021.TempRH_URL, wscodec.decoder.hdc2021.Temp_URL
class wscodec.decoder.hdc2021.TempRH_URL(*args, **kwargs)[source]
class wscodec.decoder.hdc2021.Temp_URL(*args, **kwargs)[source]
class wscodec.decoder.samples.SamplesURL(*args, timeintb64: str, scantimestamp: Optional[datetime.datetime] = None, **kwargs)[source]

This holds a list of decoded sensor samples. Each needs a timestamp, but this must be calculated. There are no absolute timestamps in the URL. First, all times are relative to scantimestamp (when the tag was scanned).

The URL does contain self.elapsedmins (the minutes elapsed since the newest sample was acquired). This makes it possible to calculate self.newest_timestamp, the timestamp of the newest sample.

Every subsequent sample is taken at a fixed time interval relative to self.newest_timestamp. This time interval is decoded from timeintb64 into self.timeinterval.

Parameters
  • *args – Variable length argument list

  • timeintb64 (str) – Time interval between samples in minutes, base64 encoded into a 4 character string.

  • scantimestamp (datetime) – Time the tag was scanned. It corresponds to the time the URL on the tag is requested from the web server.

  • **kwargs – Keyword arguments to be passed to parent class constructors.

generate_timestamp()[source]
Yields

A timestamp of a sample, calculated relative to that of the newest sample.

get_samples_list()[source]
Returns

Return type

Samples as a list of dictionaries. This is done for compatibility purposes.

class wscodec.decoder.pairs.PairsURL(*args, usehmac: bool = False, secretkey: Optional[str] = None, **kwargs)[source]

This takes the payload of the linearised buffer, which is a long string of base64 characters. It decodes this into a list of pairs. The hash (MD5 or HMAC-MD5) is taken and compared with that supplied in the URL by the encoder. If the hashes match then the decode has been successful. If not, an exception is raised.

Parameters
  • *args – Variable length argument list.

  • usehmac (bool) – True if the hash inside the circular buffer endstop is HMAC-MD5. False if it is MD5.

  • secretkey (str) – HMAC secret key as a string. Normally 16 characters long.

  • **kwargs – Keyword arguments to be passed to parent class constructors.

_decode_pairs()[source]

The payload string is converted into a list of 8-byte demis (see demi).

The first demi is the newest; its data have been written to the circular buffer most recently, so it closest to the left of the endstop. It can contain either one or two pairs. This is decoded first.

Subsequent (older) demis each contain 2 pairs. These are decoded. The final list of pairs is in chronological order with the newest first and the oldest last.

static _dividestring(source: str, n: int)[source]
Parameters
  • source (str) – The string to be divided.

  • n – The number of characters in each substring.

Returns

Return type

A list of substrings, each containing n characters.

static _gethash(message: bytearray, usehmac: bool, secretkey: str)[source]

Calculates the hash of a message.

Parameters
  • message (bytearray) – Input data to the hashing algorithm.

  • usehmac (bool) – When True the HMAC-MD5 algorithm is used. Otherwise MD5 is used (not recommended for production).

  • secretkey (str) – HMAC secret key as a string. Normally 16 characters long.

Returns

  • digest (str) – The message hash.

  • hashtype (HashType) – The hash algorithm used.

_pairsfromdemi(demi: str)List[wscodec.decoder.pairs.Pair][source]

Decode a demi into 2 pairs.

Parameters

demi (str) – A string containing 8 base64 characters.

Returns

Element 0 is the oldest pair, decoded from the first 4 demi characters. Element 1 is the newest pair, decoded from the last 4 demi characters.

Return type

A list of 2 pairs

_verify(usehmac: bool, secretkey: str)[source]

Calculate a hash from the list of pairs according to the same algorithm used by the encoder (see pairhist_hash). Besides pairs, data from the status URL parameter are included. This makes it very unlikely that the same data will be hashed twice, as well as ‘protecting’ the status parameter from modification by a 3rd party.

A fragment of the calculated hash is compared with that supplied by the encoder. If the hashes agree then verification is successful. If not, an exception is raised.

Parameters
  • usehmac (bool) – True if the hash inside the circular buffer endstop is HMAC-MD5. False if it is MD5.

  • secretkey (str) – HMAC secret key as a string. Normally 16 characters long.

Raises

MessageIntegrityError – If the hash calculated by this decoder does not match the hash provided by the encoder.:

class wscodec.decoder.circularbuffer.CircularBufferURL(statb64: str, circb64: Optional[str] = None)[source]

Base class for a cuplcodec URL.

This includes at least a circular buffer with a long string of base64 encoded sample data and a short status field.

Instantiation decodes the status string first. It contains error information from the microcontroller running the encoder.

Next it locates the ENDSTOP_BYTE in the circular buffer string. Characters to its left are the newest. Characters to its right are the oldest. The circular buffer is unwrapped into a string where ENDSTOP_BYTE is the last character and the oldest data is in the first.

The linearised buffer is further divided into two parts: The endstop string (including the endstop itself) are at the end. It contains metadata such as the number of samples in the payload. This is preceded by the payload string, which contains a list base64-encocded environmental sensor readings. These are in chronological order oldest-to-newest reading left-to-right.

The decoding of the payload string is handled elsewhere.

Parameters
statb64str

Base64 encoded status string extract from a URL parameter.

circb64str

A long string containing base64 encoded samples that are organised as a circular buffer.

ELAPSED_LEN_BYTES = 4

Length of the endstop elapsed minutes field in bytes (including the endstop itself).

ENDSTOP_BYTE = '~'

The last character in the endstop and the end of the circular buffer. Must be URL safe.

ENDSTOP_LEN_BYTES = 16

Length of the endstop in bytes.

_decode_endstop()[source]

Decode the circular buffer endstop. This can be over-ridden by a child of this class if the endstop data needs to change in future.

_decode_status()[source]

Instantiate a Status object. This can be over-ridden by a child of this class if the Status data needs to change in future.

_linearise()[source]

Linearise the circular buffer.

The circular buffer is made linear by concatenating the two parts of the buffer either side of the end stop.

Sample

Inheritance diagram of wscodec.decoder.hdc2021.TempSample, wscodec.decoder.hdc2021.TempRHSample
class wscodec.decoder.hdc2021.TempRHSample(rawtemp: int, rawrh: int, timestamp: datetime.datetime)[source]
static reading_to_rh(reading: int)float[source]
Parameters

reading – Integer Relative Humidity ADC reading from the HDC2021.

Returns

Relative Humidity in percent.

class wscodec.decoder.hdc2021.TempSample(rawtemp: int, timestamp: datetime.datetime)[source]
static reading_to_temp(reading: int)float[source]
Parameters

reading – Integer temperature ADC reading from the HDC2021.

Returns

Temperature in degrees C

class wscodec.decoder.samples.Sample(timestamp: datetime.datetime)[source]

Sample base class. All samples must contain a timestamp.

Pair

class wscodec.decoder.pairs.Pair(rd0MSB: int, rd1MSB: int, Lsb: int)[source]

Class representing a pair of 12-bit sensor readings.

In the URL each pair consists of a 4 byte (base64) string. These decode to 3 8-bit bytes. The last contains 4-bits from reading0 and 4-bits from reading 1.

When this class is instantiated, the 3 8-bit bytes are converted back into two 12-bit readings.

Parameters
  • rd0MSB (int) – Most Signficant Byte of environmental sensor reading0.

  • rd1MSB (int) – Most Significant Byte of environmental sensor reading1.

  • Lsb (int) – Upper 4-bits are the least significant bits of reading0. Lower 4-bits are the least significant bits of reading1.

classmethod from_b64(pairb64: str)[source]
Parameters

str4 (str) – A 4 character string that represents a base64 encoded pair. These are extracted from the circular buffer.

Returns

Return type

A pair instantiated from the 4 character string.

classmethod from_bytes(bytes: bytes)[source]
Parameters

bytes (bytes) – The 3 bytes that make up a pair rd0MSB, rd1MSB and Lsb.

Returns

Return type

A pair instantiated from the 3 byte input.

readings()[source]
Returns

Return type

A dictionary containing both 12-bit readings.

Status

class wscodec.decoder.status.Status(statb64: str)[source]

Decode the status string.

Parameters

statb64 – Value of the URL parameter that holds status information (after base64 encoding).

get_batvoltagemv()[source]
Returns

Battery voltage converted to mV.

get_batvoltageraw()[source]
Returns

Battery voltage as an 8-bit value.

get_resetcauseraw()[source]
Returns

Reset cause as an 8-bit value.