lib.network

This library contains the network classes for SmartHomeNG.

New network functions and utilities are going to be implemented in this library. These classes, functions and methods are mainly meant to be used by plugin developers

  • class Network provides utility methods for network-related tasks

  • class Html provides methods for communication with resp. requests to a HTTP server

  • class Tcp_client provides a two-way TCP client implementation

  • class Tcp_server provides a TCP listener with connection / data callbacks

  • class Udp_server provides a UDP listener with data callbacks

class lib.network.Network[Quellcode]

Bases: object

Provide useful static methods that you can use in your projects.

NOTE: Some format check routines were duplicate with lib.utils. As these primarily check string formats and are used for metadata parsing, they were removed here to prevent duplicates.

static ip_port_to_socket(ip, port)[Quellcode]

Return an ip address plus port to a socket string.

Format is ‚ip:port‘ for IPv4 or ‚[ip]:port‘ for IPv6

Rückgabe:

Socket address / IP endpoint as string

Rückgabetyp:

string

static family_to_string(family)[Quellcode]

Convert a socket address family to an ip version string ‚IPv4‘ or ‚IPv6‘.

Parameter:

family (socket.AF_INET or socket.AF_INET6) – Socket family

Rückgabe:

‚IPv4‘ or ‚IPv6‘

Rückgabetyp:

string

static ping(ip)[Quellcode]

Try to ICMP ping a host using external OS utilities. IPv4 only.

Parameter:

ip (string) – IPv4 address as a string

Rückgabe:

True if a reachable, false otherwise.

Rückgabetyp:

bool

static ping_port(ip, port=80)[Quellcode]

Try to reach a given TCP port. IPv4 only.

Parameter:
  • ip (string) – IPv4 address

  • port (int) – Port number

Rückgabe:

True if reachable, false otherwise.

Rückgabetyp:

bool

static send_wol(mac, ip='255.255.255.255')[Quellcode]

Send a wake on lan packet to the given mac address using ipv4 broadcast (or directed to specific ip).

Parameter:

mac (string) – Mac address to wake up (pure numbers or with any separator)

static validate_inet_addr(addr, port)[Quellcode]

Validate that addr:port resolve properly and return resolved IP address and port.

Parameter:
  • addr (str) – hostname or ip address under test

  • port (num) – port number under test

Rückgabe:

(ip_address, port, family) or (None, 0, None) if error occurs

Rückgabetyp:

tuple

static clean_uri(uri, mode='show')[Quellcode]

Check URIs for embedded http/https login data (http://user:pass@domain.tld…) and clean it.

Possible modes are:

  • ‚show‘: don’t change URI (default) -> http://user:pass@domain.tld...

  • ‚mask‘: replace login data with *** -> http://***:***@domain.tld...

  • ‚strip‘: remove login data part -> http://domain.tld...

Parameter:
  • uri (str) – full URI to check and process

  • mode (str) – handling mode, one of ‚show‘, ‚strip‘, ‚mask‘

Rückgabe:

resulting URI string

Rückgabetyp:

str

class lib.network.Connections[Quellcode]

Bases: object

Within SmartHome.py there is one instance of this class

The monitoring feature enables autoconnecting and auto- reconnecting by checking <plugin>.connected and calling <plugin>.connect()

monitor(obj)[Quellcode]
unmonitor(obj)[Quellcode]
check()[Quellcode]
class lib.network.Http(baseurl='', timeout=10, hide_login='show', name=None)[Quellcode]

Bases: object

Provide methods to simplify HTTP connections, especially to talk to HTTP servers.

Parameter:
  • baseurl (str) – base URL used everywhere in this instance (example: http://www.myserver.tld)

  • timeout (int) – Set a maximum amount of seconds the class should try to establish a connection

  • hide_login (str) – Hide or mask login data in logged http(s) requests (see Network.clean_uri())

HTTPDigestAuth(user=None, password=None)[Quellcode]

Create a HTTPDigestAuth instance and returns it to the caller.

Parameter:
  • user (str) – Username

  • password (str) – Password

Rückgabe:

HTTPDigestAuth object

Rückgabetyp:

HTTPDigestAuth

post_json(url=None, params=None, verify=True, auth=None, json=None, files={})[Quellcode]

Launch a POST request and return JSON answer as a dict or None on error.

Parameter:
  • url (str) – Optional URL to fetch from. If None (default) use baseurl given on init.

  • params (dict) – Optional dict of parameters to add to URL query string.

  • verify (bool) – Set to false to ignore SSL certificate verification errors (for self-signed for example)

  • auth (HTTPBasicAuth | HTTPDigestAuth | ...) – Optional authentication object

Rückgabe:

JSON answer decoded into a dict or None on whatever error occured

Rückgabetyp:

dict | None

get_json(url=None, params=None, verify=True, auth=None)[Quellcode]

Launch a GET request and return JSON answer as a dict or None on error.

Parameter:
  • url (str) – Optional URL to fetch from. If None (default) use baseurl given on init.

  • params (dict) – Optional dict of parameters to add to URL query string.

  • verify (bool) – Set to false to ignore SSL certificate verification errors (for self-signed for example)

  • auth (HTTPBasicAuth | HTTPDigestAuth | ...) – Optional authentication object

Rückgabe:

JSON answer decoded into a dict or None on whatever error occured

Rückgabetyp:

dict | None

get_text(url=None, params=None, encoding=None, timeout=None)[Quellcode]

Launch a GET request and return answer as string or None on error.

Parameter:
  • url (str) – Optional URL to fetch from. Default is to use baseurl given to constructor.

  • params (dict) – Optional dict of parameters to add to URL query string.

  • encoding (str) – Optional encoding of the received text. Default is to let the lib try to figure out the right encoding.

Rückgabe:

Answer decoded into a string or None on whatever error occured

Rückgabetyp:

str | None

download(url=None, local=None, params=None, verify=True, auth=None)[Quellcode]

Download a binary file to a local path.

Parameter:
  • url (str) – Remote file to download. Attention: Must be full url. ‚baseurl‘ is NOT prefixed here.

  • local (str) – Local file to save

  • params (dict) – Optional dict of parameters to add to URL query string.

  • verify (bool) – Set to false to ignore SSL certificate verification errors (for self-signed for example)

  • auth (HTTPBasicAuth | HTTPDigestAuth | ...) – Optional authentication object

Rückgabe:

Returns true on success, else false

Rückgabetyp:

bool

get_binary(url=None, params=None)[Quellcode]

Launch a GET request and return answer as raw binary data or None on error.

This is useful for downloading binary objects / files.

Parameter:
  • url (str) – Optional URL to fetch from. Default is to use baseurl given to constructor.

  • params (dict) – Optional dict of parameters to add to URL query string.

Rückgabe:

Answer as raw binary objector None on whatever error occured

Rückgabetyp:

bytes | None

response_status()[Quellcode]

Return the status code (200, 404, …) of the last executed request.

If GET request was not possible and thus no HTTP statuscode is available, the returned status code is 0.

Rückgabe:

Status code and text of last request

Rückgabetyp:

tuple(int, str)

response_headers()[Quellcode]

Return a dictionary with the server return headers of the last executed request.

Rückgabe:

Headers returned by server

Rückgabetyp:

dict

response_cookies()[Quellcode]

Return a dictionary with the cookies the server may have sent on the last executed request.

Rückgabe:

Cookies returned by server

Rückgabetyp:

dict

response_object()[Quellcode]

Return the raw response object for advanced ussage.

Rückgabe:

Reponse object as returned by underlying requests library

Rückgabetyp:

requests.Response

class lib.network.Tcp_client(host, port, name=None, autoreconnect=True, autoconnect=None, connect_retries=5, connect_cycle=5, retry_cycle=30, retry_abort=0, abort_callback=None, binary=False, terminator=False, timeout=1, rate_limit=1, max_rate_connects=10)[Quellcode]

Bases: object

Structured class to handle locally initiated TCP connections with two-way communication.

The callbacks need to be defined as follows:

def connected_callback(Tcp_client_instance) def receiving_callback(Tcp_client_instance) def disconnected_callback(Tcp_client_instance) def data_received_callback(Tcp_client_instance, message)

(Class members need the additional first self parameter)

Parameter:
  • host (str) – Remote host name or ip address (v4 or v6)

  • port (int) – Remote host port to connect to

  • name (str) – Name of this connection (mainly for logging purposes). Try to keep the name short.

  • autoreconnect (bool) – Should the socket try to reconnect on lost connection (or finished connect cycle)

  • autoconnect (bool) – automatically connect on send. Copies autoreconnect if None

  • connect_retries (int) – Number of connect retries per connect round

  • connect_cycle (int) – Time between retries inside a connect round

  • retry_cycle (int) – Time between connect rounds if autoreconnect is True

  • retry_abort (int) – abort connecting after this many failed connect rounds and call abort_callback, no action if set to 0 or callback not set

  • abort_callback (function) – callback function to be run on connection abort

  • binary (bool) – Switch between binary and text mode. Text will be encoded / decoded using encoding parameter.

  • terminator (int | bytes | str) – Terminator to use to split received data into chunks (split lines <cr> for example). If integer then split into n bytes. Default is None means process chunks as received.

  • timeout (int) – Timeout to set for connected socket. Don’t change without reason

set_callbacks(connected=None, receiving=None, data_received=None, disconnected=None)[Quellcode]

Set callbacks to caller for different socket events.

Parameter:
  • connected (function) – Called whenever a connection is established successfully

  • data_received (function) – Called when data is received

  • disconnected (function) – Called when a connection has been dropped for whatever reason

open()[Quellcode]
connect()[Quellcode]

Connect the socket.

Rückgabe:

False if an error prevented us from launching a connection thread. True if a connection thread has been started.

Rückgabetyp:

bool

connected()[Quellcode]

Return the current connection state.

Rückgabe:

True if an active connection exists,else False.

Rückgabetyp:

bool

send(message)[Quellcode]

Send a message to the server. Can be a string, bytes or a bytes array.

Rückgabe:

True if message has been successfully sent, else False.

Rückgabetyp:

bool

close()[Quellcode]

Close the current client socket.

class lib.network.ConnectionClient(server=None, socket=None, ip=None, port=None, name=None)[Quellcode]

Bases: object

Client object that represents a connected client returned by a Tcp_server instance on incoming connection.

This class should normally not be instantiated manually, but is provided by the Tcp_server via the callbacks

Parameter:
  • server (tcp_server) – The tcp_server passes a reference to itself to access parent methods

  • socket (function) – socket.Socket class used by the Client object

  • fd (int) – File descriptor of socket used by the Client object

property socket

Socket getter.

set_callbacks(data_received=None, will_close=None)[Quellcode]

Set callbacks for different socket events (client based).

Parameter:

data_received (function) – Called when data is received

send(message)[Quellcode]

Send a string to connected client.

Parameter:

msg (string | bytes | bytearray) – Message to send

Rückgabe:

True if message has been queued successfully.

Rückgabetyp:

bool

send_echo_off()[Quellcode]

Send an IAC telnet command to ask client to turn its echo off.

send_echo_on()[Quellcode]

Send an IAC telnet command to ask client to turn its echo on again.

close()[Quellcode]

Close client socket.

class lib.network.Tcp_server(port, host='', name=None, mode=3, terminator=None)[Quellcode]

Bases: object

Threaded TCP listener which dispatches connections (and possibly received data) via callbacks.

NOTE: The callbacks need to expect the following arguments:

  • incoming_connection(server, client) where server ist the Tcp_server instance and client is a ConnectionClient for the current connection

  • data_received(server, client, data) where server ist the Tcp_server instance, client is a ConnectionClient for the current connection, and data is a string containing received data

  • disconnected(server, client) where server ist the Tcp_server instance and client is a ConnectionClient for the closed connection

Parameter:
  • host (str) – Local host name or ip address (v4 or v6). Default is ‚::‘ which listens on all IPv4 and all IPv6 addresses available.

  • port (int) – Local port to connect to

  • name (str) – Name of this connection (mainly for logging purposes)

MODE_TEXT = 1
MODE_TEXT_LINE = 2
MODE_BINARY = 3
MODE_FIXED_LENGTH = 4
set_callbacks(incoming_connection=None, disconnected=None, data_received=None)[Quellcode]

Set callbacks to caller for different socket events.

Parameter:
  • connected (function) – Called whenever a connection is established successfully

  • data_received (function) – Called when data is received

  • disconnected (function) – Called when a connection has been dropped for whatever reason

start()[Quellcode]

Start the server socket.

Rückgabe:

False if an error prevented us from launching a connection thread. True if a connection thread has been started.

Rückgabetyp:

bool

listening()[Quellcode]

Return the current listening state.

Rückgabe:

True if the server socket is actually listening, else False.

Rückgabetyp:

bool

send(client, msg)[Quellcode]

Send a string to connected client.

Parameter:
Rückgabe:

True if message has been queued successfully.

Rückgabetyp:

bool

disconnect(client)[Quellcode]

Disconnect a specific client.

Parameter:

client (lib.network.ConnectionClient) – Client Object to disconnect

close()[Quellcode]

Close running listening socket.

class lib.network.Udp_server(port, host='', name=None)[Quellcode]

Bases: object

Threaded UDP listener which dispatches received data via callbacks.

NOTE: The callbacks need to expect the following arguments:

  • data_received(addr, data) where addr is a tuple with ('<remote_ip>', remote_port) and data is the received data as string

Parameter:
  • host (str) – Local hostname or ip address (v4 or v6). Default is ‚‘ which listens on all IPv4 addresses available.

  • port (int) – Local port to connect to

  • name (str) – Name of this connection (mainly for logging purposes)

start()[Quellcode]

Start the server socket.

Rückgabe:

False if an error prevented us from launching a connection thread. True if a connection thread has been started.

Rückgabetyp:

bool

set_callbacks(data_received=None)[Quellcode]

Set callbacks to caller for different socket events.

Parameter:

data_received (function) – Called when data is received

listening()[Quellcode]

Return the current listening state.

Rückgabe:

True if the server socket is actually listening, else False.

Rückgabetyp:

bool

close()[Quellcode]

Close running listening socket.