lib.network

* ATTENTION: This is early work in progress. Interfaces are subject to change. *
* DO NOT USE IN PRODUCTION until you know what you are doing *

This library contains the future network classes for SmartHomeNG.

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

class lib.network.Network[Quellcode]

Bases: object

This Class has some usefull static methods that you can use in your projects

static is_mac(mac)[Quellcode]

Validates a MAC address

Parameter

mac – MAC address

Rückgabe

True if value is a MAC

Rückgabetyp

bool

static is_ip(string)[Quellcode]

Checks if a string is a valid ip-address (v4 or v6)

Parameter

string (str) – String to check

Rückgabe

True if an ip, false otherwise.

Rückgabetyp

bool

static is_ipv4(string)[Quellcode]

Checks if a string is a valid ip-address (v4)

Parameter

string (str) – String to check

Rückgabe

True if an ip, false otherwise.

Rückgabetyp

bool

static is_ipv6(string)[Quellcode]

Checks if a string is a valid ip-address (v6)

Parameter

string (str) – String to check

Rückgabe

True if an ipv6, false otherwise.

Rückgabetyp

bool

static is_hostname(string)[Quellcode]

Checks if a string is a valid hostname

The hostname has is checked to have a valid format

Parameter

string (str) – String to check

Rückgabe

True if a hostname, false otherwise.

Rückgabetyp

bool

static get_local_ipv4_address()[Quellcode]

Get’s local ipv4 address of the interface with the default gateway. Return ‚127.0.0.1‘ if no suitable interface is found

Rückgabe

IPv4 address as a string

Rückgabetyp

string

static get_local_ipv6_address()[Quellcode]

Get’s local ipv6 address of the interface with the default gateway. Return ‚::1‘ if no suitable interface is found

Rückgabe

IPv6 address as a string

Rückgabetyp

string

static ip_port_to_socket(ip, port)[Quellcode]

Returns an ip address plus port to a socket string. Format is ‚ip:port‘ for IPv4 or ‚[ip]:port‘ for IPv6

Rückgabe

Socket address / IPEndPoint as string

Rückgabetyp

string

static ipver_to_string(ipver)[Quellcode]

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

Parameter

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

Rückgabe

‚IPv4‘ or ‚IPv6‘

Rückgabetyp

string

static ping(ip)[Quellcode]

Tries to ICMP ping a host using external OS utilities. Currently 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]

Tries to reach a given TCP port. Currently IPv4 only.

Parameter
  • ip (string) – IPv4 address

  • port (int) – Port number

Rückgabe

True if a reachable, false otherwise.

Rückgabetyp

bool

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

Sends 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)

class lib.network.Http(baseurl='', timeout=10)[Quellcode]

Bases: object

Creates an instance of the Http class.

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

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

Creates 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]

Launches a POST request and returns 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]

Launches a GET request and returns 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]

Launches a GET request and returns 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]

Downloads 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]

Launches a GET request and returns answer as raw binary data or None on error. This is usefull 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]

Returns 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 = 0.

Rückgabe

Status code and text of last request

Rückgabetyp

(int, str)

response_headers()[Quellcode]

Returns a dictionary with the server return headers of the last executed request

Rückgabe

Headers returned by server

Rückgabetyp

dict

response_cookies()[Quellcode]

Returns 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]

Returns the raw response object for advanced ussage. Use if you know what you are doing. Maybe this lib can be extented to your needs instead ?

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, connect_retries=5, connect_cycle=5, retry_cycle=30, binary=False, terminator=False)[Quellcode]

Bases: object

Creates a new instance of the Tcp_client class

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)

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

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

  • retry_cycle (int) – Time between cycles if :param:autoreconnect is True

  • 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.

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

connect()[Quellcode]

Connects 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]

Returns the current connection state

Rückgabe

True if an active connection exists,else False.

Rückgabetyp

bool

send(message)[Quellcode]

Sends 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]

Closes the current client socket

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

Bases: object

Creates a new instance of the Tcp_server class

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

  • port (int) – Remote interface 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(listening=None, 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]

Returns 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
  • client (network.Client) – Client Object to send message to

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

Rückgabe

True if message has been queued successfully.

Rückgabetyp

bool

disconnect(client)[Quellcode]

Disconnects a specific client

Parameter

client (network.Client) – Client Object to disconnect

close()[Quellcode]

Closes running listening socket