SubModules§

libs.Camera§

class libs.Camera.Camera(identifier: str, config: dict = None, queue: collections.deque = None, noconf: bool = False, **kwargs)[source]§

Bases: threading.Thread

Base Camera class.

Variables:
  • accuracy (int) – 3: Number of seconds caputre should be accurate to.
  • default_width (int) – 1080: Default width of resized images.
  • default_height (int) – 720: Default height of resuzed images.
  • file_types (list) – [“CR2”, “RAW”, “NEF”, “JPG”, “JPEG”, “PPM”, “TIF”, “TIFF”]: Supported output image types.
  • output_types (list) – [“tif”, “jpg”]: Output image types, ignored by GPCamera.
  • communication_queue (collections.deque) – Reference to a deque, or a deque.
  • logger (logging.Logger) – Logger for each Camera.
  • stopper (threading.Event) – Stopper event object to allow thread stopping.
  • identifier (str) – Unique identifier for the camera. Used to distinguish cameras from one another.
  • failed (list) – List of failed capture timepoints.
  • config_filename (str) – Confuguration file path, unused if camera is instantiated with the noconf init parameter.
  • camera_name (str) – Human friendly name of the camera.
  • interval (int) – Capture interval (in seconds).
  • spool_directory (str) – Path to stream images into during the capture process.
  • upload_directory (str) – Path to move images to after the captre process.
  • begin_capture (datetime.time) – Naive start time for capture.
  • end_capture (datetime.time) – Naive end time for capture.
  • current_capture_time (datetime.datetime) – When the capture process began.
accuracy = 3§
capture(filename: str = None) → <built-in function array>[source]§

capture method, only extends functionality of Camera.capture() so that testing with can happen

Camera.capture = Camera.capture_monkey For extending the Camera class override the Camera.capture_image method, not this one.

Parameters:filename – image filename without extension
Returns:numpy.array() if filename not specified, otherwise list of files.
Return type:numpy.array
capture_image(filename: str = None) → <built-in function array>[source]§

Camera capture method. override this method when creating a new type of camera.

Behavior:
  • if filename is a string, write images to disk as filename.ext, and return the names of the images written sucessfully.
  • if filename is None, it will set the instance attribute _image to a numpy array of the image and return that.
Parameters:filename – image filename without extension
Returns:numpy.array() if filename not specified, otherwise list of files.
Return type:numpy.array or list(str)
capture_monkey(filename: str = None) → <built-in function array>[source]§

Simulates things going horribly wrong with the capture. Will sometimes return None, an empty list or an invalid filename. Sometimes will raise a generic Exception. The rest of the time it will capture a valid image.

Parameters:filename – image filename without extension
Returns:numpy.array() if filename not specified, otherwise list of files.
Return type:numpy.array
communicate_with_updater()[source]§

Inter-thread communication method. Communicates with this objects libs.Updater.Updater by keeping a reference to its member ‘communication_queue’ and appending this objects current state to the queue.

default_height = 720§
default_width = 1080§
encode_write_np_array(np_image_array: <built-in function array>, fn: str) → list[source]§

takes a RGB numpy image array like the ones from cv2 and writes it to disk as a tif and jpg converts from rgb to bgr for cv2 so that the images save correctly also tries to add exif data to the images

Parameters:
  • np_image_array (numpy.array) – 3 dimensional image array, x,y,rgb
  • fn (str) – filename
Returns:

files successfully written.

Return type:

list(str)

exif§

Gets the current exif data, sets the exif datetime field to now.

Returns:dictionary of exif fields and their values.
Return type:dict
file_types = ['CR2', 'RAW', 'NEF', 'JPG', 'JPEG', 'PPM', 'TIF', 'TIFF']§
focus()[source]§

AutoFocus trigger method. Unimplemented.

get_exif_fields() → dict[source]§

Get default fields for exif dict, this should be overriden and super-ed if you want to add custom exif tags.

Returns:exif fields
Return type:dict
get_frame() → bytes[source]§

Gets a frame from the a running stream_thread().

Returns:encoded image data as bytes.
image§

Gets the current image (last image taken and stored) as a numpy.array.

Returns:numpy array of the currently stored image.
Return type:numpy.array
init_stream()[source]§

Initialises a video stream class thread.

mqtt_on_connect(client, *args)[source]§
mqtt_on_message(client, userdata, msg)[source]§

handler for mqtt messages on a per camera basis.

Parameters:
  • client – mqtt client
  • userdata – mqtt userdata
  • msg – message to be decoded
output_types = ['tif', 'jpg']§
run()[source]§

Main method. continuously captures and stores images.

set_config(pdict)[source]§
setupmqtt()[source]§
stop()[source]§

Stops the capture thread, if self is an instance of threading.Thread.

classmethod stream_thread()[source]§

Boilerplate stream thread. Override this with the correct method of opening the camera, grabbing image data and closing the camera.

static time2seconds(t: datetime.datetime) → int[source]§

Converts a datetime to an integer of seconds since epoch

Returns:integer of seconds since 1970-01-01
Return type:int
time_to_capture§

Filters out times for capture.

returns True by default.

returns False if the conditions where the camera should capture are NOT met.

Returns:whether or not it is time to capture
Return type:bool
time_to_report§

Filters out times for reporting.

returns True by default.

returns False if the conditions where the camera should capture are NOT met.

Returns:whether or not it is time to capture
Return type:bool
static timestamp(tn: datetime.datetime) → str[source]§

Creates a properly formatted timestamp from a datetime object.

Parameters:tn – datetime to format to timestream timestamp string
Returns:formatted timestamp.
timestamped_imagename§

Builds a timestamped image basename without extension from Camera.current_capture_time()

Returns:image basename
Return type:str
updatemqtt(msg: bytes)[source]§
class libs.Camera.GPCamera(identifier: str, usb_address: tuple = None, lock=<unlocked _thread.lock object>, **kwargs)[source]§

Bases: libs.Camera.Camera

Camera class other cameras inherit from this class. identifier and usb_address are NOT OPTIONAL

capture_image(filename=None)[source]§

Gapture method for DSLRs. Some contention exists around this method, as its definitely not the easiest thing to have operate robustly. GPCamera._cffi_capture() is how it _should_ be done, however that method is unreliable and causes many crashes when in real world timelapse situations. This method calls gphoto2 directly, which makes us dependent on gphoto2 (not just libgphoto2 and gphoto2-cffi), and there is probably some issue with calling gphoto2 at the same time like 5 times, maybe dont push it.

Parameters:filename – filename without extension to capture to.
Returns:list of filenames (of captured images) if filename was specified, otherwise a numpy array of the image.
Return type:numpy.array or list
eos_serial_number§

returns the eosserialnumber of supported cameras, otherwise the normal serialnumber

focus()[source]§

this is meant to trigger the autofocus. currently not in use because it causes some distortion in the images.

get_exif_fields()[source]§

This is meant to get the exif fields for the image if we want to manually save them. This is incomplete.

Returns:dictionary of exif fields.
Return type:dict
serial_number§

returns the current serialnumber for the camera.

class libs.Camera.IPCamera(identifier=None, ip=None, config=None, queue=None, **kwargs)[source]§

Bases: libs.Camera.Camera

IPCamera, unfinished and untested.

TODO: needs work to support both yml config and normal configs

capture_image(filename=None) → <built-in function array>[source]§

Captures an image with the IP camera, uses requests.get to acqire the image.

Parameters:filename – filename without extension to capture to.
Returns:list of filenames (of captured images) if filename was specified, otherwise a numpy array of the image.
Return type:numpy.array or list
focus()[source]§

focuses the camera by cycling it through its autofocus modes.

focus_mode§

TODO: this is broken, returns the dict of key: value not value

Focus Mode

When setting, the mode provided must be in ‘focus_modes’

Getter:from camera.
Setter:to camera.
Return type:list
focus_position§

Focal position as an absolute value.

Getter:from camera.
Setter:to camera.
Return type:float
focus_range§

Information about the focus of the camera

Returns:focus type, focus max, focus min
Return type:list [str, float, float]
static get_value_from_plaintext(message, *args)[source]§

gets float, int or string values from a xml string where the key is the tag of the first element with value as text.

Parameters:
  • message
  • args – list of keys to find values for.
Return type:

dict

Returns:

dict of arg: value pairs requested

get_value_from_stream(stream, *keys)[source]§

Gets a value from some text data (xml or plaintext = separated values) returns a dict of “key”:value pairs.

Parameters:
  • stream (str) – text data to search for values
  • keys (list) –
Returns:

dict of values

Return type:

dict

static get_value_from_xml(message_xml, *args)[source]§

gets float, int or string values from a xml string where the key is the tag of the first element with value as text.

Parameters:
  • message_xml – the xml to searach in.
  • args – list of keys to find values for.
Return type:

dict

Returns:

dict of arg: value pairs requested

hfov§

Horizontal FoV

Getter:calculated using cached zoom_position, zoom_list and hfov_list.
Setter:cache.
Rrtype:list(float)
hfov_list§

List of horizontal FoV values according to focus list.

Getter:cached.
Setter:cache.
Rrtype:list(float)
image_quality§

Image quality as a percentage.

Getter:cached.
Setter:to camera.
Return type:float
image_size§

Image resolution in pixels, tuple of (width, height)

Getter:from camera.
Setter:to camera.
Return type:tuple
status§

Helper property for a string of the current zoom/focus status.

Returns:informative string of zoom_pos zoom_range focus_pos focus_range
Return type:str
vfov§

Vertical FoV

Getter:calculated using cached zoom_position, zoom_list and vfov_list.
Setter:cache.
Rrtype:list(float)
vfov_list§

List of vertical FoV values according to focus list.

Getter:cached.
Setter:cache.
Rrtype:list(float)
class libs.Camera.IVPortCamera(identifier: str, gpio_group: tuple = ('B', ), camera_number: int = None, **kwargs)[source]§

Bases: libs.Camera.PiCamera

IVPort class for multiple capture. the 4 tags on the IVport are setout below.

TRUTH_TABLE = [[False, False, True], [True, False, True], [False, True, False], [True, True, False]]§
capture_image(filename: str = None) → list[source]§

capture method for IVPort iterates over the number of vameras

Returns:numpy.array() if filename not specified, otherwise list of files.
Return type:numpy.array or list
current_camera_index = 0§
enable_pins = {'A': [11, 12], 'B': [15, 16], 'C': [21, 22], 'D': [23, 24]}§
gpio_groups = ('B',)§
select = 7§
classmethod switch(idx: int = None)[source]§

switches the IVPort to a new camera with no index, switches to the next camera, looping around from the beginning

Parameters:idx (int) – index to switch the camera to (optional)
class libs.Camera.PiCamera(identifier: str, config: dict = None, queue: collections.deque = None, noconf: bool = False, **kwargs)[source]§

Bases: libs.Camera.Camera

Picamera extension to the Camera abstract class.

capture_image(filename: str = None) → <built-in function array>[source]§

Captures image using the Raspberry Pi Camera Module, at either max resolution, or resolution specified in the config file.

Writes images disk using encode_write_np_array(), so it should write out to all supported image formats automatically.

Parameters:filename – image filename without extension
Returns:numpy.array() if filename not specified, otherwise list of files.
Return type:numpy.array
set_camera_settings(camera)[source]§

Sets the camera resolution to the max resolution

if the config provides camera/height or camera/width attempts to set the resolution to that. if the config provides camera/isoattempts to set the iso to that. if the config provides camera/shutter_speed to set the shutterspeed to that.

Parameters:camera (picamera.PiCamera) – picamera camera instance to modify
classmethod stream_thread()[source]§

Streaming thread member.

uses picamera.PiCamera.capture_continuous() to stream data from the rpi camera video port.

time.sleep() added to rate limit a little bit.

class libs.Camera.TwentyFourHourTimeParserInfo(dayfirst=False, yearfirst=False)[source]§

Bases: dateutil.parser.parserinfo

validate(res)[source]§
class libs.Camera.USBCamera(identifier: str, sys_number: int, **kwargs)[source]§

Bases: libs.Camera.Camera

USB Camera Class

capture_image(filename=None)[source]§

captures an image from the usb webcam. Writes some limited exif data to the image if it can.

Parameters:filename – filename to output without excension
Returns:list of image filenames if filename was specified, otherwise a numpy array.
Return type:numpy.array or list
stop()[source]§

releases the video device and stops the camera thread

classmethod stream_thread()[source]§

usb camera stream thread. TODO: Needs to be aware of multiple cameras.

libs.Camera.nested_lookup(key, document)[source]§

nested document lookup, works on dicts and lists

Parameters:
  • key – string of key to lookup
  • document – dict or list to lookup
Returns:

yields item

libs.CryptUtil§

class libs.CryptUtil.SSHManager(path='/home/.ssh')[source]§

Bases: object

a manager of ssh keys, with the ability to sign messages using them.

get_new_key_from_server(token)[source]§

acquires an ssh key from the server with a token and writes the key to the current path.

Parameters:token – a string token to send to the server.
Returns:boolean indicating whether the operation was successful.
Return type:bool
paramiko_key§

property for a key usable by paramiko

Returns:agentKey for use by paramiko/pysftp
Return type:paramiko.rsakey.RSAKey
public_ssh_key_string§

property for the public ssh key string.

Returns:string of the ssh public key, encoded to be added to a authorized_keys file
Return type:str
sign_message(message) → str[source]§

signs a text message using the internal key

Parameters:message – utf-8 encoded string
Returns:signature for message.
Return type:str
sign_message_PKCS1v15(message) → bytes[source]§
sign_message_PSS(message) → bytes[source]§
ssh_key§

ssh key property sets the internal rsa key and the agentKey for use by paramiko.

write_key_to_path()[source]§

writes internally stored public and private keys to their respective paths

libs.CryptUtil.serialize_signature(signature: bytes) → str[source]§

formats the signature for the server, with the correct boundaries

Parameters:signature (bytes) – raw bytes signature.
Returns:str formatted signature for sending to the server.
libs.CryptUtil.ssh_public_key(keypair: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization) → str[source]§

converts an rsa keypair to openssh format public key

Parameters:keypair (cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization) – keypair.
Returns:string of public key

libs.Light§

class libs.Light.Controller(config_section: dict)[source]§

Bases: object

controller abstract that takes a dictionary config section and sets self attributes to it.

get_wavelength(wavelength: str)[source]§

gets the power of a specific wavelength :param wavelength: wavelength string to get the power of (eg 400nm) :return:

set_all(power: int = None, percent: int = None)[source]§

sets all wavelengths to either an absolute value or a percentage of the total

Parameters:
  • power – power to set all wavelengths to
  • percent – 0-100 percentage to set the lights to.
Returns:

true/false depending on whether the command was successful

set_all_wavelengths(values: dict, percent=True)[source]§

sets all wavelengths to specific values. only absolute values may be specified values should be specified as a dict of wavelength: value pairs

Parameters:
  • values – dict of wavelengths and their respective values
  • percent – whether the values are expressed as 0-100 or absolute.
set_wavelength(wl: str, power: int = None, percent: int = None)[source]§

sets a specific wavelength to a value either a power or a percent must be specified

Parameters:
  • wl – string of wavelength name (eg 400nm)
  • power – absolute power value
  • percent – percent value, calculated from min/max.
class libs.Light.HTTPController(config_section)[source]§

Bases: libs.Light.Controller

kill_schedule()[source]§

turns off all the heliospectras internal scheduling sysm :return:

class libs.Light.HelioSpectra(config)[source]§

Bases: object

Dumb runnner for a light, must be controlled by a chamber. automatically scales the power from 0-100 to the provided min-max (0-1000) by default

accuracy = 3§
s10wls = ['400nm', '420nm', '450nm', '530nm', '630nm', '660nm', '735nm']§
s20wls = ['370nm', '400nm', '420nm', '450nm', '530nm', '620nm', '660nm', '735nm', '850nm', '6500k']§
set(intensities: list) → dict[source]§

sets the lights wavelengths to the values in the list.

returns a dict of the wavelengths set and their values.

If the length of the list of intensities doesnt match the number of custom wavelengths, but does match the length of the list of s10 or s20 wavelengths, then they will be used.

If none of those conditions are met, returns an empty dict.

Parameters:intensities – intensities to set to
Returns:
class libs.Light.TelNetController(config_section)[source]§

Bases: libs.Light.Controller

controller for a Light.

libs.Light.clamp(v: float, minimum: float, maximum: float) → float[source]§

clamps a number to the minimum and maximum.

Parameters:
  • v
  • minimum
  • maximum
Returns:

libs.PanTilt§

class libs.PanTilt.PanTilt(ip=None, user=None, password=None, config=None, queue=None)[source]§

Bases: object

Control J-Systems PTZ

For new system or new firmware, the system needs calibration as follows: - Open URL of the PTZ on a web browser - Click on “Calibration” tab, enter username and password if necessary - On Calibration window, click on “Open-loop” and then “Set Mode” - Use joystick controller to rotate the pan axis to minimum position - Click on ‘Pan Axis Min’ line, enter ‘2.0’, and click “Set Calibration” - Use joystick controller to rotate the pan axis to maximum position - Click on ‘Pan Axis Max’ line, enter ‘358.0’, and click “Set Calibration” - Use joystick controller to rotate the tilt axis to minimum position - Click on ‘Tilt Axis Min’ line, enter ‘-90.0’, and click “Set Calibration” - Use joystick controller to rotate the tilt axis to maximum position - Click on ‘Tilt Axis Max’ line, enter ‘30.0’, and click “Set Calibration” - Click on “Closed-loop” and then “Set Mode” - Close Calibration window

PCCWLS§
PCWLS§
TDnLS§
TUpLS§
auto_patrol§
battery_voltage§
communicate_with_updater()[source]§

communication member. This is meant to send some metadata to the updater thread. :return:

control_mode§
dwell§
static get_value_from_plaintext(message, *args)[source]§

gets float, int or string values from a xml string where the key is the tag of the first element with value as text.

Parameters:
  • message
  • args – list of keys to find values for.
Return type:

dict

Returns:

dict of arg: value pairs requested

get_value_from_stream(stream, *keys)[source]§
static get_value_from_xml(message_xml, *args)[source]§

gets float, int or string values from a xml string where the key is the tag of the first element with value as text.

Parameters:
  • message_xml – the xml to searach in.
  • args – list of keys to find values for.
Return type:

dict

Returns:

dict of arg: value pairs requested

heater§
hold_pan_tilt(state)[source]§

unknown, presumably holds the pan-tilt in one place. doesnt work… :param state: ? beats me. :return:

list_index§
list_state§
pan§
pan_range§
pan_step(direction, n_steps)[source]§

pans by step, steps must be less than or equal to 127 :type n_steps: int :type direction: str :param direction: :param n_steps: integer <= 127. number of steps :return:

position§

gets the current pan/tilt position. :return: tuple (pan, tilt)

scale§
temp_f§
tilt§
tilt_range§
tilt_step(direction, n_steps)[source]§

tilts by step, steps must be less than or equal to 127 :type n_steps: int :type direction: str :param direction: :param n_steps: integer <= 127. number of steps :return:

zoom_list§

List of zoom value intervals.

Setting this also affects the state of other related variables.

Getter:cached.
Setter:recalculates, recalculates fov lists, resets zoom_position.
Return type:list
zoom_position§

Zoom Position.

Getter:from camera.
Setter:to camera.
Return type:tuple
zoom_range§

Range of zoom for the camera.

Getter:from camera.
Setter:cached.
Return type:tuple
class libs.PanTilt.ThreadedPTZ(*args, **kwargs)[source]§

Bases: threading.Thread

class libs.PanTilt.ThreadedPanTilt(*args, **kwargs)[source]§

Bases: libs.PanTilt.ThreadedPTZ, libs.PanTilt.PanTilt

run()[source]§

libs.Sensor§

class libs.Sensor.ConvironChamberSensor(identifier, config, *args, **kwargs)[source]§

Bases: libs.Sensor.Sensor

data_headers = ('temp_set', 'humidity_set', 'temp_recorded', 'humidity_recorded', 'par')§
get_measurement()[source]§
class libs.Sensor.DHTMonitor(identifier, pin: int = 14, sensor_type='AM2302', **kwargs)[source]§

Bases: libs.Sensor.Sensor

Data logger class for DHT11, DHT22 & AM2302 GPIO temperature & humidity sensors from Adafruit.

supply the identifier and the gpio pi that the sensor is connected to, along with the type of sensor. defaults to pin 14, DHT22

data_headers = ('humidity', 'temperature')§
get_measurement() → dict[source]§

gets data from the DHT22

class libs.Sensor.SenseHatMonitor(identifier: str = None, *args, **kwargs)[source]§

Bases: libs.Sensor.Sensor

Data logger class for Astro Pi Sensehat No need to supply anything except the identifier as the SenseHad uses some kind of black sorcery to work it out.

data_headers = ('temperature', 'humidity', 'pressure')§
get_measurement() → dict[source]§

get measurements for sensehat :return:

show_data(measurement)[source]§

displays the data on the osd.

Parameters:measurement – meausrement to display
Returns:
class libs.Sensor.Sensor(identifier: str, config: dict = None, queue: collections.deque = None, write_out: bool = True, interval: int = 60, **kwargs)[source]§

Bases: threading.Thread

Sensor base. To use this class you need to override ‘get_measurement()’ so that it returns a tuple of the measurements that match the headers defined in the data_headers classvar. by default it will write 5 files, rolling 24 hour files (csv, tsv & json) and all time files that are appended to (csv & tsv only)

accuracy = 1§
append_to_alltime(measurement: tuple)[source]§

appends the measurement to the csv and tsv files.

Parameters:measurement
Returns:
communicate_with_updater()[source]§

communication member. This is meant to send some metadata to the updater thread. :return:

data_headers = ()§
get_measurement() → dict[source]§

override this method with the method of collecting measurements from the sensor should return a dict

Returns:dict of measurements and their names
Return type:dict
rotate(csvf, tsvf)[source]§
run()[source]§

run method. used for threaded sensors :return:

stop()[source]§

stops the thread. :return:

static time2seconds(t: <module 'datetime' from '/usr/lib/python3.6/datetime.py'>) → int[source]§

converts a datetime to an integer of seconds since epoch

time_to_measure§

filters out times for mesauring, returns True by default returns False if the conditions where the sensor should NOT capture are met. :return:

static timestamp(tn: datetime.datetime) → str[source]§

creates a properly formatted timestamp. :param tn: datetime to format to timestream timestamp string :return:

timestamp_format = '%Y-%m-%dT%H:%M:%S'§
timestamped_filename§

builds a timestamped image basename without extension from a datetime. :param time_now: :return: string image basename

write_daily_rolling()[source]§

writes full rolling daily daita files. :param rows: :return:

libs.Sensor.round_to_1dp(n)[source]§

libs.SysUtil§

class libs.SysUtil.LazySolarCalcReader(fn)[source]§

Bases: object

class libs.SysUtil.SysUtil[source]§

Bases: object

System utility class. Helper class to cache various things like the hostname, machine-id, amount of space in the filesystem.

a_statvfs = os.statvfs_result(f_bsize=4096, f_frsize=4096, f_blocks=29173873, f_bfree=17249075, f_bavail=17026786, f_files=0, f_ffree=0, f_favail=0, f_flag=3072, f_namemax=255)§
classmethod add_watch(path: str, callback)[source]§

adds a watch that calls the callback on file change

Parameters:
  • path (str) – path of the file to watch
  • callback – function signature to call when the file is changed
classmethod clear_files(filenames: list)[source]§

removes all files in the list provided, skipping and logging on an error removing todo: Do different things based on whether is a directory.

Parameters:filenames (list or tuple) – list of directories or files
classmethod configs_from_identifiers(identifiers: set) → dict[source]§

given a set of identifiers, returns a dictionary of the data contained in those config files with the key for each config file data being the identifier

Parameters:identifiers (list(str)) –
Returns:dictionary of configuration datas
Return type:dict(str: dict)
static default_identifier(prefix=None)[source]§

returns an identifier, If no prefix available, generates something.

Parameters:prefix
Returns:string of the itentifier.
Return type:str
classmethod ensure_config(identifier)[source]§

ensures a configuration file exists for this identifier. if a config file doesnt exist then it will create a default one.

Parameters:identifier (str) – identifier to create or find a configuration file for.
Returns:the configuration file dict or configparser object.
Return type:dict or configparser.ConfigParser
static get_checksum(fp: str) → str[source]§

gets the string checksum for a file, or returns random if the file doesnt exist

Parameters:fp – file path of the file.
Returns:crc32 checksum of the file at fp, or random letters
static get_checksum_from_str(input_data) → str[source]§

gets the string checksum for some bytes (or a string).

coerces strings using utf-8

Parameters:input_data – file path of the file.
Returns:crc32 checksum of the bytes
classmethod get_external_ip()[source]§

returns the external IP address of the raspberry pi through api.ipify.org

Returns:the external ip address
Return type:str
classmethod get_fs_space() → tuple[source]§

returns free/total space of root filesystem as bytes(?)

Returns:tuple of free/total space
Return type:tuple[int, int]
classmethod get_fs_space_mb() → tuple[source]§

returns the filesystems free space in mebibytes. see get_fs_space()

Returns:tuple of free/total space

:rtype:tuple[int, int]

classmethod get_hostname() → str[source]§

gets the current hostname. if there is no /etc/hostname file, sets the hostname randomly.

Returns:the current hostname or the hostname it was set to
Return type:str
classmethod get_identifier_from_filename(file_name)[source]§

returns either the identifier (from the file name) or the name filled with the machine id

Parameters:file_name (str) – filename
Returns:string identifier,
Return type:str
classmethod get_identifier_from_name(name)[source]§

returns either the identifier (from name) or the name filled with the machine id clamps to 32 characters.

Parameters:name (str) – name to fill
Returns:filled name
Return type:str
classmethod get_internal_ip()[source]§

gets the internal ip by attempting to connect to googles DNS

Returns:the current internal ip
Return type:str
classmethod get_isonow()[source]§

gets the current time as an iso8601 string

Returns:the current time as iso8601
Return type:str
classmethod get_log_files() → list[source]§

returns the spc-eyepi log files that have been rotated.

Returns:list of filenames
Return type:list(str)
classmethod get_machineid() → str[source]§

gets the machine id, or initialises the machine id if it doesnt exist.

Returns:string of the machine-id
Return type:str
classmethod get_tor_host() → tuple[source]§

gets a tuple of the current tor host.

Returns:tuple of hostname(onion address), client key, client name
Return type:tuple[str, str, str]
classmethod get_version() → str[source]§

gets the “describe” version of the current git repo as a string.

Returns:the current version
Return type:str
classmethod identifier_to_ini(identifier: str, prefix='configs_byserial') → str[source]§

gets a valid .ini path for an identifier.

Parameters:identifier – identifier to find an ini for.
Returns:file path for identifier
Return type:str
classmethod identifier_to_yml(identifier: str) → str[source]§

the same as identifier_to_ini but for yml files

Parameters:identifier (str) – identifier for a matching yml file.
Returns:string filepath for the yml file.
Return type:str
classmethod load_or_fix_solarcalc(fp: str) → libs.SysUtil.LazySolarCalcReader[source]§

function to either load an existing fixed up solarcalc file or to coerce one into the fixed format.

Parameters:identifier (str) – identifier of the light for which the solarcalc file exists.
Returns:light timing data as a list of lists.
Return type:list(list())
logger = <Logger SysUtil (DEBUG)>§
classmethod open_yaml(filename)[source]§

opens a yaml file using yaml.load

Parameters:filename – yaml file to load
Returns:dictionary of values in yaml file
Return type:dict
static reboot()[source]§
static reset_usb_device(bus: int, dev: int) → bool[source]§

resets a usb device.

Parameters:
  • bus (int) – bus number
  • dev (int) – device number of the device on the bus above
classmethod set_hostname(hostname: str)[source]§

sets the machines hosname, in /etc/hosts and /etc/hostname

Parameters:hostname – the string of which to set the hostname to.
static sizeof_fmt(num, suffix='B') → str[source]§

formats a number of bytes in to a human readable string. returns in SI units eg sizeof_fmt(1234) returns ‘1.2KiB’

Parameters:
  • num – number of bytes to format
  • suffix – the suffix to use
Returns:

human formattted string.

Return type:

str

stop = False§
thread = None§
classmethod update_from_git()[source]§

updates spc-eyepi from git.

classmethod write_config(config: configparser.ConfigParser, identifier: str, prefix='configs_byserial')[source]§

writes a configuration file to an correct config file path.

Parameters:
  • config – configuration file (configparser object)
  • identifier (str) – identifier to user as the raget file name.
Returns:

configparser object

static write_global_config(data: dict, path_override=None)[source]§

Writes a global configuration to the global_config.yml

Parameters:data – dict of data to write to the config
libs.SysUtil.get_generator(fh)[source]§
libs.SysUtil.recursive_update(d, u)[source]§
libs.SysUtil.sizeof_fmt(num, suffix='B')[source]§

libs.Updater§

class libs.Updater.Updater[source]§

Bases: threading.Thread

add_to_identifiers(identifier: str)[source]§

adds an identifier to the set of identifiers. :param identifier: identifier to add :return:

add_to_temp_identifiers(temp_identifier: str)[source]§

adds an identifier to the set of temporary identifiers. that may disappear :param temp_identifier: identifier to add :return:

gather_data()[source]§
go()[source]§
mqtt_on_connect(client, *args)[source]§
mqtt_on_message(*args)[source]§
process_deque(cameras=None)[source]§
run()[source]§
setupmqtt()[source]§
stop()[source]§
updatemqtt(parameter: str, message: bytes)[source]§
upload_logs()[source]§

uploads rotated logs to the server. :return:

libs.Uploader§

class libs.Uploader.GenericUploader(identifier: str, source_dir: str = None, host: str = None, config: dict = None, queue: collections.deque = None)[source]§

Bases: libs.Uploader.Uploader

Generic uploader for uploading logs sensor data, etc.

fill_me(dict_of_values: dict)[source]§

fills self with values from a dict.

Parameters:dict_of_values (dict) – dictionary of key: values
re_init()[source]§

Your config is in another castle.

remove_source_files = True§
class libs.Uploader.Uploader(identifier: str, config: dict = None, queue: collections.deque = None)[source]§

Bases: threading.Thread

Uploader class, used to upload,

communicate_with_updater()[source]§

communication member. This is meant to send some metadata to the updater thread.

mkdir_recursive(link, remote_directory, mkdir=None, chdir=None)[source]§

Creates directories recursively on the remote server

Parameters:
  • link – ftp/sftp connection object
  • remote_directory
  • chdir – method used to change to a directory
  • mkdir – method used to make a directory
mqtt_on_connect(client, *args)[source]§
mqtt_on_message(client, userdata, msg)[source]§

handler for mqtt messages on a per camera basis.

Parameters:
  • client – mqtt client
  • userdata – mqtt userdata
  • msg – message to be decoded
remove_source_files = True§
run()[source]§

run method. main loop for Uploaders.

setupmqtt()[source]§
stop()[source]§

stopper method

updatemqtt(msg: bytes)[source]§
upload(file_names)[source]§

uploads files via sftp. deletes the files as they are uploaded, creates new directories if needed.

Parameters:file_names – filenames to upload
upload_interval = 120§