Commit 6904c0ba authored by Laurent Kislaire's avatar Laurent Kislaire
Browse files

NoMdns, Logs and script

parents c79aa84a af6983dd
......@@ -18,6 +18,7 @@ cache:
stage: build
- dev
- master
- python build
......@@ -26,6 +27,7 @@ job_build:
stage: test
- dev
- master
- job_build
......@@ -4,19 +4,71 @@
* Full API coverage
* Https and Mdns discovery
* Thin client wrapper (~150 lines)
* Thin client wrapper library (~250 lines)
* CLI script example to access any command
[![pipeline status](](
[![coverage report](](
## Usage
## Script
A script called pyfbx is installed and can be used like this:
To register the application:
pyfbx SuperAppId
Once registration is done on the device, write down the application token.
Using this app token, acquire a session token to execute a test command
pyfbx -t '<TOKEN>' SuperAppId
You can also store the token in a file (example token.txt) and also execute a specific command
pyfbx -t f:/home/foo/token.txt SuperAppId -c 'Contacts.Create_a_contact(post_data={"display_name": "Sandy Kilo", "first_name": "Sandy", "last_name":"Kilo"})'
{ 'birthday': '',
'company': '',
'display_name': 'Sandy Kilo',
'first_name': 'Sandy',
'id': 17,
'last_name': 'Kilo',
'last_update': 1554378898,
'notes': '',
'photo_url': ''}
_Note_ : Don't forget to escape token and command.
pyfbx -h
usage: pyfbx [-h] [-c COMMAND] [-t TOKEN] [-v] [-n] app_id
positional arguments:
app_id application identifier
optional arguments:
-h, --help show this help message and exit
-c COMMAND, --command COMMAND
command, defaults to
-t TOKEN, --token TOKEN
token (or f:<filename>)
-v, --verbose increase verbosity to INFO, use twice for DEBUG
-n, --http Disable MDNS and use http known address
## Library usage
The REST API is generated at runtime with the creation of class attributes for all Freebox subsystems.
>>> from pyfbx import Fbx
>>> f=Fbx()
>>> f=Fbx() # By default, this will perform MDNS discovery
>>> f=Fbx(nomdns=True) # Use faster http api discovery
>>> f.<TAB>
f.Airmedia f.Download_Config f.Lan f.Rrd f.Upnpav
f.Call f.Download_Feeds f.Lcd f.Share f.Vpn
......@@ -30,9 +82,9 @@ f.Freeplug.Reset_a_Freeplug(
# Register application to get app token. Physical access is required.
>>> token = f.register("Id_SuperAppli", "Une superbe appli", "python")
>>> token = f.register("AppId", "My App", "PC")
# Generate session token
>>> f.mksession(app_id="Id_SupperAppli", token=token)
>>> f.mksession(app_id="AppId", token=token)
>>> help(f.Lan.Update_the_current_Lan_configuration)
Help on method Update_the_current_Lan_configuration:
......@@ -60,7 +112,9 @@ Access_a_given_contact_entry(id) method of pyfbx.client.Contacts instance
>>> f.mksession()
## Testing
## Developpment
### Testing
You can run tests with
Console script
import os
import logging
import argparse
import pprint
from pyfbx import Fbx
log_level = (logging.WARNING, logging.INFO, logging.DEBUG)
def console(log, level):
formatter = logging.Formatter('%(asctime)s - %(name)14s - %(levelname)s - %(message)s')
stream_handler = logging.StreamHandler()
def main():
log = logging.getLogger("pyfbx")
parser = argparse.ArgumentParser()
parser.add_argument("app_id", type=str, help="application identifier")
parser.add_argument("-c", "--command", type=str,
help="command, defaults to System.Get_the_current_system_info()",
parser.add_argument("-t", "--token", type=str, help="token (or f:<filename>)")
parser.add_argument("-v", "--verbose", action="count", default=0,
help="increase verbosity to INFO, use twice for DEBUG")
parser.add_argument("-n", "--http", action="store_true",
help="Disable MDNS and use http known address")
args = parser.parse_args()
console(log, log_level[min(2, args.verbose)])
myfb = Fbx(nomdns=args.http)
token = args.token
if token:
if token.startswith('f:'):
with open(args.token[2:]) as tok_file:
token =
log.warning(f"Registering app {__name__}, id {args.app_id}, Press button")
token = myfb.register(app_id=args.app_id, app_name=__name__,
log.warning(f"Save your application token: {token}")
myfb.mksession(app_id=args.app_id, token=token)
pp = pprint.PrettyPrinter(indent=4)
except BaseException as err:
......@@ -3,9 +3,11 @@
Fbx Client
import os
import logging
import re
import hmac
import hashlib
import logging
import time
import requests
from . import api
......@@ -32,15 +34,18 @@ class FbxTransport():
Transport abstraction and context handling for all methods
def __init__(self, url=None, session=None):
def __init__(self, url=None, nomdns=False, session=None):
self.log = logging.getLogger("pyfbx.trans")
self._session = session or requests.session()
self._session.verify = os.path.join(os.path.dirname(__file__), 'fb.pem')
self.set_url(url, nomdns)
def set_url(self, url):
def set_url(self, url, nomdns):
if url is None:
# Detect using MDNS or fallback
self._url = mdns.FbxMDNS().search() or self.get_local_base()
if nomdns:
self._url = self.get_local_base()
self._url = mdns.FbxMDNS().search() or self.get_local_base()
if"https?://", url) is None:
url = "http://" + url
......@@ -54,18 +59,24 @@ class FbxTransport():
def api_exec(self, http_method, endpoint, post_data=None, **kwargs):
req_response = self._session.request(
http_method, self._url + "/" + endpoint.format(**kwargs), json=post_data)
self._url + "/" + endpoint.format(**kwargs), json=post_data)
self.log.debug(">> Sent %s %s/%s Post: %s", http_method, self._url,
endpoint.format(**kwargs), post_data)
response = req_response.json()
if response['success']:
if 'result' in response:
self.log.debug(f"<< Got {response['result']}")
return response['result']
raise FbxErrorResponse(response['error_code'], response['msg'])
def get_local_base(self, url=api._DISC_HTTP_URL):
response = self._session.get(f"{url}/api_version").json()
return "%s%sv%s" % (url, response['api_base_url'], response['api_version'][0])
self.log.debug(f"<< Detected api {response['api_version']}")
return "%s%sv%s" % (url, response['api_base_url'],
class Fbx():
......@@ -73,8 +84,9 @@ class Fbx():
Freebox object
def __init__(self, url=None, session=None):
self._trn = FbxTransport(url, session=session)
def __init__(self, url=None, nomdns=False, session=None):
self.log = logging.getLogger("pyfbx.fbx")
self._trn = FbxTransport(url, nomdns=nomdns, session=session)
# Create on the fly attributes to classes
_globals = globals()
......@@ -92,10 +104,12 @@ class Fbx():
res = self._trn.api_exec("POST", "login/authorize/", data)
trackid, self.token = res["track_id"], res["app_token"]
s = "pending""Press Ok on the freebox to register application")
while s == "pending":
s = self._trn.api_exec("GET", f"login/authorize/{trackid}")["status"]
if s == "pending":
self.log.debug(f"Registration returned: {s}")
return s == "granted" and self.token
def mksession(self, app_id=None, token=None):
......@@ -115,6 +129,7 @@ class Fbx():
session_token = resp["session_token"]
self.app_id = app_id
return resp["permissions"]
......@@ -127,7 +142,10 @@ class FbxErrorResponse(Exception):
return f'{self.msg} [{self.error_code}]'
log = logging.getLogger("pyfbx")
# All FB subsystems are classes deriving from FbxClass
for _classname in api.SYSTEMS:
log.debug(f"Adding class {_classname} to locals")
locals()[_classname] = type(_classname, (FbxClass, ), {})
......@@ -3,6 +3,7 @@ Search Freebox through MDNS
import time
import logging
from zeroconf import ServiceBrowser, Zeroconf
from . import api
......@@ -29,14 +30,17 @@ class FbxMDNS():
def __init__(self, timeout=1):
self.timeout = timeout
self.log = logging.getLogger("pyfbx.mdns")
def search(self, svc_name=api._DISC_MDNS_NAME, timeout=1):
self.log.debug("Searching with MDNS")
zeroconf = Zeroconf()
self._listener = FbxMDNS.MyListener()
browser = ServiceBrowser(zeroconf, svc_name, self._listener)
browser.cancel() # slow
zeroconf.close() # slow
self.log.debug("Closing MDNS")
browser.cancel() # slow but required to
zeroconf.close() # stop listener thread
if self.svc_info:
prop = self.svc_prop
base = "%sv%s" % (prop['api_base_url'], prop['api_version'][0])
......@@ -5,7 +5,7 @@ addopts = --cov --cov-report term-missing
branch = True
source = pyfbx
omit = tests/*
omit = tests/*, pyfbx/
universal = 0
......@@ -17,4 +17,5 @@ setup(
install_requires=["zeroconf", "requests"],
entry_points={'console_scripts': ['pyfbx = pyfbx.__main__:main', ]},
......@@ -21,4 +21,5 @@ def test_fbx_mdns():
with patch('', return_value=None):
f = Fbx()
f = Fbx(url="")
f = Fbx(nomdns=True)
f = Fbx(session=requests.Session())
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment