more logging, chang knxPython

This commit is contained in:
Thomas Kunze
2024-08-30 20:47:43 +02:00
parent a6563b0129
commit f9ba9acc3d
33 changed files with 524 additions and 612 deletions

View File

@@ -1,16 +1,16 @@
cmake_minimum_required(VERSION 3.16)
project(knx VERSION 1.5)
project(knxPython VERSION 1.5)
add_subdirectory(pybind11)
pybind11_add_module(knxPython
knxmodule.cpp
)
include_directories(src pybind11/include)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0")
#set(outdir ${CMAKE_LIBRARY_OUTPUT_DIRECTORY})
#set_target_properties(knx PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${outdir})
set_target_properties(knxPython PROPERTIES OUTPUT_NAME knx)
set_property(TARGET knxPython PROPERTY CXX_STANDARD 11)
#target_compile_definitions(knxPython PUBLIC -DMASK_VERSION=0x57B0)
target_link_libraries(knxPython PRIVATE knx)
target_link_libraries(knxPython PUBLIC knx)
install(TARGETS knxPython LIBRARY DESTINATION .)

View File

@@ -1,14 +0,0 @@
recursive-include external *
include ./*.py
include ./VERSION
include ./*.cmake
include ./*.cpp
include ./CMakeLists.txt
include README.md
global-exclude .git
graft pybind11/include
graft src

View File

@@ -1 +0,0 @@
0.1.6

View File

@@ -2,7 +2,7 @@
#include <pybind11/stl_bind.h>
#include <pybind11/functional.h>
#include <pybind11/stl.h>
namespace py = pybind11;
#include <Python.h>
@@ -18,6 +18,10 @@ namespace py = pybind11;
#include "knx/platform/linux_platform.h"
#include "knx/ip/bau57B0.h"
#include "knx/interface_object/group_object_table_object.h"
#include "knx/util/logger.h"
#define LOGGER Logger::logger("knxmodule")
using namespace Knx;
LinuxPlatform* platform = 0;
@@ -40,22 +44,33 @@ static std::vector<const char*> argv;
struct StdStringCStrFunctor
{
const char* operator() (const std::string& str) { return str.c_str(); }
const char* operator() (const std::string& str)
{
return str.c_str();
}
};
static void Prepare(std::vector<std::string> args)
static void init()
{
// copy args so we control the livetime of the char*
argsVector = args;
for(int i = 0; i < args.size(); i++)
printf("%s\n", args[i].c_str());
Logger::logLevel("knxmodule", Logger::Info);
Logger::logLevel("ApplicationLayer", Logger::Info);
Logger::logLevel("BauSystemBDevice", Logger::Info);
Logger::logLevel("GroupObject", Logger::Info);
argv = std::vector<const char*>(argsVector.size());
std::transform(argsVector.begin(), argsVector.end(), argv.begin(), StdStringCStrFunctor());
/*
// copy args so we control the livetime of the char*
argsVector = args;
for (int i = 0; i < args.size(); i++)
printf("%s\n", args[i].c_str());
argv = std::vector<const char*>(argsVector.size());
std::transform(argsVector.begin(), argsVector.end(), argv.begin(), StdStringCStrFunctor());
*/
platform = new LinuxPlatform();
platform->cmdLineArgs(argv.size(), const_cast<char**>(argv.data()));
bau = new Bau57B0(*platform);
}
static void Destroy()
@@ -69,7 +84,7 @@ static void Destroy()
static void ReadMemory()
{
if (!bau)
return;
init();
bau->readMemory();
}
@@ -78,12 +93,12 @@ static void Start()
{
if (running)
return;
if (!bau)
return;
init();
running = true;
bau->enabled(true);
workerThread = std::thread(loop);
@@ -94,19 +109,20 @@ static void Stop()
{
if (!running)
return;
running = false;
bau->writeMemory();
bau->enabled(false);
workerThread.join();
}
static bool ProgramMode(bool value)
{
if (!bau)
return false;
init();
LOGGER.info("ProgramMode %d", value);
bau->deviceObject().progMode(value);
return bau->deviceObject().progMode();
}
@@ -114,7 +130,7 @@ static bool ProgramMode(bool value)
static bool ProgramMode()
{
if (!bau)
return false;
init();
return bau->deviceObject().progMode();
}
@@ -122,71 +138,75 @@ static bool ProgramMode()
static bool Configured()
{
if (!bau)
return false;
init();
return bau->configured();
}
PYBIND11_MODULE(knx, m)
PYBIND11_MODULE(knx, m)
{
m.doc() = "wrapper for knx device lib"; // optional module docstring
m.def("Start", &Start, "Start knx handling thread.");
m.def("Stop", &Stop, "Stop knx handling thread.");
m.def("Prepare", &Prepare, "Allocated needed objects.");
m.def("Destroy", &Destroy, "Free object allocated by Prepare.");
m.def("Destroy", &Destroy, "Free object allocated objects.");
m.def("ProgramMode", (bool(*)())&ProgramMode, "get programing mode active.");
m.def("ProgramMode", (bool(*)(bool))&ProgramMode, "Activate / deactivate programing mode.");
m.def("Configured", (bool(*)())&Configured, "get configured status.");
m.def("Configured", (bool(*)())&Configured, "get configured status.");
m.def("ReadMemory", &ReadMemory, "read memory from flash file");
m.def("FlashFilePath", []()
{
if(!platform)
return std::string("");
m.def("FlashFilePath", []()
{
if (!platform)
init();
return platform->flashFilePath();
});
m.def("FlashFilePath", [](std::string path)
{
if(!platform)
return;
return platform->flashFilePath();
});
m.def("FlashFilePath", [](std::string path)
{
if (!platform)
init();
platform->flashFilePath(path);
});
m.def("GetGroupObject", [](uint16_t goNr)
{
if(!bau || goNr > bau->groupObjectTable().entryCount())
return (GroupObject*)nullptr;
platform->flashFilePath(path);
});
m.def("GetGroupObject", [](uint16_t goNr)
{
LOGGER.info("GetGroupObject arg %d", goNr);
LOGGER.info("GetGroupObject entrycount %d", bau->groupObjectTable().entryCount());
if (!bau)
init();
if (goNr > bau->groupObjectTable().entryCount())
return (GroupObject*)nullptr;
return &bau->groupObjectTable().get(goNr);
}, py::return_value_policy::reference);
m.def("Callback", [](GroupObjectUpdatedHandler handler)
{
GroupObject::classCallback(handler);
});
return &bau->groupObjectTable().get(goNr);
}, py::return_value_policy::reference);
py::class_<GroupObject>(m, "GroupObject", py::dynamic_attr())
.def(py::init())
.def("asap", &GroupObject::asap)
.def("size", &GroupObject::valueSize)
.def_property("value",
[](GroupObject& go) { return py::bytes((const char*)go.valueRef(), go.valueSize()); },
[](GroupObject& go, py::bytes bytesValue)
{
const auto value = static_cast<std::string>(bytesValue);
if (value.length() != go.valueSize())
throw std::length_error("bytesValue");
auto valueRef = go.valueRef();
memcpy(valueRef, value.c_str(), go.valueSize());
go.objectWritten();
})
.def_property("callback",
[](GroupObject& go)
{
return go.callback();
},
[](GroupObject& go, GroupObjectUpdatedHandler handler)
{
go.callback(handler);
}
)
.def("callBack", (void(GroupObject::*)(GroupObjectUpdatedHandler))&GroupObject::callback);
.def(py::init())
.def("asap", &GroupObject::asap)
.def("size", &GroupObject::valueSize)
.def_property("value",
[](GroupObject & go)
{
return py::bytes((const char*)go.valueRef(), go.valueSize());
},
[](GroupObject & go, py::bytes bytesValue)
{
const auto value = static_cast<std::string>(bytesValue);
if (value.length() != go.valueSize())
throw std::length_error("bytesValue");
auto valueRef = go.valueRef();
memcpy(valueRef, value.c_str(), go.valueSize());
go.objectWritten();
});
}

View File

@@ -1,81 +0,0 @@
import os
import re
import sys
import platform
import subprocess
from setuptools import setup, Extension, find_packages
from setuptools.command.build_ext import build_ext
from distutils.version import LooseVersion
from write_version_info import get_version_info
class CMakeExtension(Extension):
def __init__(self, name, sourcedir=''):
Extension.__init__(self, name, sources=[])
self.sourcedir = os.path.abspath(sourcedir)
class CMakeBuild(build_ext):
def run(self):
try:
out = subprocess.check_output(['cmake', '--version'])
except OSError:
raise RuntimeError("CMake must be installed to build the following extensions: " +
", ".join(e.name for e in self.extensions))
cmake_version = LooseVersion(re.search(r'version\s*([\d.]+)', out.decode()).group(1))
if cmake_version < LooseVersion('3.5.0'):
raise RuntimeError("CMake >= 3.5.0 is required")
for ext in self.extensions:
self.build_extension(ext)
def build_extension(self, ext):
extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))
cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir,
'-DPYTHON_EXECUTABLE=' + sys.executable]
build_type = os.environ.get("BUILD_TYPE", "Release")
build_args = ['--config', build_type]
# Pile all .so in one place and use $ORIGIN as RPATH
cmake_args += ["-DCMAKE_BUILD_WITH_INSTALL_RPATH=TRUE"]
cmake_args += ["-DCMAKE_INSTALL_RPATH={}".format("$ORIGIN")]
if platform.system() == "Windows":
cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(build_type.upper(), extdir)]
if sys.maxsize > 2**32:
cmake_args += ['-A', 'x64']
build_args += ['--', '/m']
else:
cmake_args += ['-DCMAKE_BUILD_TYPE=' + build_type]
build_args += ['--', '-j4']
env = os.environ.copy()
env['CXXFLAGS'] = '{} -DVERSION_INFO=\\"{}\\"'.format(env.get('CXXFLAGS', ''),
self.distribution.get_version())
if not os.path.exists(self.build_temp):
os.makedirs(self.build_temp)
subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env)
subprocess.check_call(['cmake',
'--build', '.',
'--target', ext.name
] + build_args,
cwd=self.build_temp)
setup(
name='knxPython',
version=get_version_info()[3],
author='Thomas Kunze',
author_email='thomas.kunze@gmx.com',
description='Lib to implement knx-devices',
long_description_content_type="text/markdown",
long_description=open("../../README.md").read(),
ext_modules=[CMakeExtension('knx')],
packages=find_packages(),
license="GPL3",
cmdclass=dict(build_ext=CMakeBuild),
url="https://github.com/thelsing/knx",
zip_safe=False
)

View File

@@ -1,49 +0,0 @@
import subprocess
import time
import sys
import socket
def get_version_info():
try:
git_revision = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode("utf-8") .split("\n")[0]
git_branch = subprocess.check_output(["git", "rev-parse","--abbrev-ref", "HEAD"]).decode("utf-8").split("\n")[0]
except (subprocess.CalledProcessError, OSError):
git_revision = ""
git_branch = "non-git"
def read_version():
with open("VERSION") as f:
return f.readline().strip()
build_datetime = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
version_number = read_version()
hostname = socket.gethostname()
return git_revision, git_branch, build_datetime, version_number, hostname
def print_version_number():
sys.stdout.write(get_version_info()[3])
if __name__ =="__main__":
output_file = sys.argv[1]
with open(output_file, "w") as fout:
fout.write("""#pragma once
namespace knx{{
namespace version{{
auto constexpr git_revision = u8"{0}";
auto constexpr git_branch = u8"{1}";
auto constexpr build_datetime = u8"{2}";
auto constexpr version_number = u8"{3}";
auto constexpr build_hostname = u8"{4}";
}}
}}
""".format(*get_version_info()))