import 2.4.1.0

This commit is contained in:
shaozhimin 2024-03-30 17:00:04 +08:00 committed by szm-min
parent 5f61f15e78
commit 8efa3057ac
146 changed files with 19798 additions and 2012 deletions

15
debian/changelog vendored
View File

@ -1,3 +1,18 @@
libkysdk-system (2.4.1.0-0k0.0) nile; urgency=medium
* BUG
* 需求号:#28159 【好用工程】实现Win32API中电池管理和usb管理模块的平替
#28160 【好用工程】实现Win32API中应用信息获取和网络管理模块的平替
#28507 GuestOS支持第三方管控的单点登录功能对接
#28509 【接口定制】建行银行安全管控新增接口定制需求
#25201 桌面注销状态查询接口
* 其他改动说明:部分接口提权
修改自测内存泄漏
新增磁盘信息、系统信息、硬件信息中的显卡信息、主板信息、网络信息和瞬时信息获取的dbus接口
ocr增加i386架构编译
* 其他改动影响域:无
-- szm-min <shaozhimin@kylinos.cn> Mon, 01 Apr 2024 10:12:40 +0800
libkysdk-system (2.4.0.0-0k1.2) nile; urgency=medium
* BUG:无

213
debian/control vendored
View File

@ -31,49 +31,55 @@ Build-Depends: debhelper-compat (= 12),
libpci-dev,
libbluetooth-dev,
libsensors4-dev,
libleptonica-dev,
libusb-1.0-0-dev,
libnl-3-dev,
libnl-route-3-dev
libnl-genl-3-dev,
libnl-route-3-dev,
libpolkit-gobject-1-dev
Standards-Version: 4.4.1
Homepage: http://gitlab2.kylin.com/kysdk/kysdk-system
Package: libkysdk-system
Architecture: any
Section: utils
Depends: libkysdk-disk,
libkysdk-sysinfo,
libkysdk-systime,
libkysdk-filesystem,
libkysdk-proc,
libkysdk-hardware,
libkysdk-package,
libkysdk-powermanagement,
Depends: libkysdk-disk (= ${binary:Version}),
libkysdk-sysinfo (= ${binary:Version}),
libkysdk-systime (= ${binary:Version}),
libkysdk-filesystem (= ${binary:Version}),
libkysdk-proc (= ${binary:Version}),
libkysdk-hardware (= ${binary:Version}),
libkysdk-package (= ${binary:Version}),
libkysdk-powermanagement (= ${binary:Version}),
systemd,
libglib2.0-0,
libkysdk-systemcommon,
libkysdk-location,
libkysdk-net,
libkysdk-realtime,
libkysdk-imageproc
libkysdk-systemcommon (= ${binary:Version}),
libkysdk-location (= ${binary:Version}),
libkysdk-net (= ${binary:Version}),
libkysdk-realtime (= ${binary:Version}),
libkysdk-imageproc (= ${binary:Version}),
libkysdk-accounts (= ${binary:Version})
Multi-Arch: same
Description: 麒麟开发者套件 - 系统层套件提供系统信息、磁盘信息、系统时间等API与服务
Package: libkysdk-system-dev
Architecture: all
Section: utils
Depends: libkysdk-system,
libkysdk-disk-dev,
libkysdk-sysinfo-dev,
libkysdk-systime-dev,
libkysdk-sysinfo-dev,
libkysdk-filesystem-dev,
libkysdk-proc-dev,
libkysdk-hardware-dev,
libkysdk-package-dev,
libkysdk-powermanagement-dev,
libkysdk-location-dev,
libkysdk-net-dev,
libkysdk-realtime-dev,
libkysdk-imageproc-dev
Depends: libkysdk-system (= ${binary:Version}),
libkysdk-disk-dev (= ${binary:Version}),
libkysdk-sysinfo-dev (= ${binary:Version}),
libkysdk-systime-dev (= ${binary:Version}),
libkysdk-sysinfo-dev (= ${binary:Version}),
libkysdk-filesystem-dev (= ${binary:Version}),
libkysdk-proc-dev (= ${binary:Version}),
libkysdk-hardware-dev (= ${binary:Version}),
libkysdk-package-dev (= ${binary:Version}),
libkysdk-powermanagement-dev (= ${binary:Version}),
libkysdk-location-dev (= ${binary:Version}),
libkysdk-net-dev (= ${binary:Version}),
libkysdk-realtime-dev (= ${binary:Version}),
libkysdk-imageproc-dev (= ${binary:Version}),
libkysdk-accounts-dev (= ${binary:Version})
Multi-Arch: foreign
Description: 麒麟开发者套件 - 系统层套件 - 开发库提供系统信息、磁盘信息、系统时间等API与服务
@ -81,24 +87,21 @@ Package: libkysdk-disk
Architecture: any
Section: utils
Depends: libkysdk-log(>=1.2.0),
libkysdk-systemcommon,
libkysdk-systemcommon (= ${binary:Version}),
libhd21,
libblkid1,
libc6,
libkysdk-config(>=1.2.0),
libsystemd0,
libudev1
libudev1,
libdbus-1-3
Multi-Arch: same
Description: 系统磁盘信息获取库
Package: libkysdk-disk-dev
Architecture: all
Section: utils
Depends: libkysdk-disk,
libkysdk-log-dev(>=1.2.0),
libkysdk-utils-dev(>=1.2.0),
libblkid-dev,
libudev-dev
Depends: libkysdk-disk (= ${binary:Version})
Multi-Arch: foreign
Description: 系统磁盘信息获取库 - 开发库
@ -111,7 +114,7 @@ Depends: libkysdk-log(>=1.2.0),
libglib2.0-0,
libkysdk-timer(>=1.2.0),
libkysdk-config(>=1.2.0),
libkysdk-systemcommon,
libkysdk-systemcommon (= ${binary:Version}),
libc6,
libdbus-1-3,
libdbus-glib-1-2
@ -121,10 +124,7 @@ Description: 系统时间相关操作库
Package: libkysdk-systime-dev
Architecture: all
Section: utils
Depends: libkysdk-systime,
libglib2.0-dev,
libkysdk-timer-dev(>=1.2.0),
libkysdk-config-dev(>=1.2.0)
Depends: libkysdk-systime (= ${binary:Version})
Multi-Arch: foreign
Description: 系统时间相关操作库 - 开发库
@ -139,7 +139,7 @@ Depends: libkysdk-log(>=1.2.0),
libxrandr2,
libpci3,
libkmod2,
libkysdk-systemcommon,
libkysdk-systemcommon (= ${binary:Version}),
libc6,
libdbus-1-3,
libdbus-glib-1-2,
@ -154,15 +154,7 @@ Description: 系统信息获取库
Package: libkysdk-sysinfo-dev
Architecture: all
Section: utils
Depends: libkysdk-sysinfo,
libkysdk-log-dev(>=1.2.0),
libkysdk-utils-dev(>=1.2.0),
libsystemd-dev,
libcjson-dev,
libdbus-1-dev,
libdbus-glib-1-dev,
libglib2.0-dev,
libxrandr-dev
Depends: libkysdk-sysinfo (= ${binary:Version})
Multi-Arch: foreign
Description: 系统信息获取库 - 开发库
@ -173,7 +165,7 @@ Depends: libkysdk-log(>=1.2.0),
libqt5core5a,
libkysdk-config(>=1.2.0),
systemd,
libkysdk-systemcommon,
libkysdk-systemcommon (= ${binary:Version}),
libc6,
libgcc-s1 | libgcc1,
libstdc++6,
@ -184,11 +176,7 @@ Description: 文件系统库
Package: libkysdk-filesystem-dev
Architecture: all
Section: utils
Depends: libkysdk-filesystem,
libkysdk-log-dev(>=1.2.0),
libkysdk-config-dev(>=1.2.0),
libsystemd-dev,
qtbase5-dev
Depends: libkysdk-filesystem (= ${binary:Version})
Multi-Arch: foreign
Description: 文件系统库 - 开发库
@ -198,7 +186,7 @@ Section: utils
Depends: libkysdk-log(>=1.2.0),
libkysdk-config(>=1.2.0),
systemd,
libkysdk-systemcommon,
libkysdk-systemcommon (= ${binary:Version}),
libcups2,
libcurl4,
libudev1,
@ -212,7 +200,9 @@ Depends: libkysdk-log(>=1.2.0),
libc6,
libsystemd0,
libx11-6,
libdbus-1-3,
libnl-3-200,
libnl-genl-3-200,
libnl-route-3-200
Multi-Arch: same
Description: 硬件信息获取库
@ -220,21 +210,14 @@ Description: 硬件信息获取库
Package: libkysdk-hardware-dev
Architecture: all
Section: utils
Depends: libkysdk-hardware,
libkysdk-log-dev(>=1.2.0),
libkysdk-config-dev(>=1.2.0),
libsystemd-dev,
libcups2-dev,
libcurl4-openssl-dev,
libudev-dev,
libxrandr-dev
Depends: libkysdk-hardware (= ${binary:Version})
Multi-Arch: foreign
Description: 硬件信息获取库 - 开发库
Package: libkysdk-package
Architecture: any
Section: utils
Depends: libkysdk-systemcommon,
Depends: libkysdk-systemcommon (= ${binary:Version}),
libc6
Multi-Arch: same
Description: 包管理库
@ -242,7 +225,7 @@ Description: 包管理库
Package: libkysdk-package-dev
Architecture: all
Section: utils
Depends: libkysdk-package
Depends: libkysdk-package (= ${binary:Version})
Multi-Arch: foreign
Description: 包管理库 - 开发库
@ -250,7 +233,7 @@ Package: libkysdk-proc
Architecture: any
Section: utils
Depends: libkysdk-log(>=1.2.0),
libkysdk-systemcommon,
libkysdk-systemcommon (= ${binary:Version}),
libc6
Multi-Arch: same
Description: 运行时信息获取库
@ -258,9 +241,7 @@ Description: 运行时信息获取库
Package: libkysdk-proc-dev
Architecture: all
Section: utils
Depends: libkysdk-log-dev(>=1.2.0),
libkysdk-utils-dev(>=1.2.0),
libkysdk-proc
Depends: libkysdk-proc (= ${binary:Version})
Multi-Arch: foreign
Description: 运行时信息获取库 - 开发库
@ -268,7 +249,7 @@ Package: libkysdk-powermanagement
Architecture: any
Section: utils
Depends: libkysdk-log(>=1.2.0),
libkysdk-systemcommon,
libkysdk-systemcommon (= ${binary:Version}),
libc6,
libdbus-1-3,
libgcc-s1 | libgcc1,
@ -282,8 +263,7 @@ Description: 电源管理库
Package: libkysdk-powermanagement-dev
Architecture: all
Section: utils
Depends: libkysdk-log-dev(>=1.2.0),
libkysdk-powermanagement
Depends: libkysdk-powermanagement (= ${binary:Version})
Multi-Arch: foreign
Description: 电源管理 - 开发库
@ -297,7 +277,7 @@ Depends: libopencv-core4.2,
liblept5,
libarchive13,
libtesseract4,
libkysdk-systemcommon,
libkysdk-systemcommon (= ${binary:Version}),
libc6,
libgcc-s1 | libgcc1,
libstdc++6
@ -306,7 +286,7 @@ Description: AI文字识别功能
Package: libkysdk-ocr-dev
Architecture: all
Multi-Arch: foreign
Depends: libkysdk-ocr,
Depends: libkysdk-ocr (= ${binary:Version}),
libleptonica-dev,
libopencv-dev,
libarchive-dev,
@ -323,64 +303,65 @@ Description: kysdk-system层公用数据包
Package: libkysdk-location
Architecture: any
Section: utils
Depends: libkysdk-systemcommon,
Depends: libkysdk-systemcommon (= ${binary:Version}),
libglib2.0-0,
libc6,
python3-requests
libc6
Multi-Arch: same
Description: 地理位置库
Package: libkysdk-location-dev
Architecture: all
Section: utils
Depends: libkysdk-location
Depends: libkysdk-location (= ${binary:Version})
Multi-Arch: foreign
Description: 地理位置库 - 开发库
Package: libkysdk-net
Architecture: any
Section: utils
Depends: libkysdk-systemcommon,
libc6
Depends: libkysdk-systemcommon (= ${binary:Version}),
libc6,
libdbus-1-3
Multi-Arch: same
Description: 网络信息库
Package: libkysdk-net-dev
Architecture: all
Section: utils
Depends: libkysdk-net
Depends: libkysdk-net (= ${binary:Version})
Multi-Arch: foreign
Description: 网络信息库 - 开发库
Package: libkysdk-realtime
Architecture: any
Section: utils
Depends: libkysdk-systemcommon,
Depends: libkysdk-systemcommon (= ${binary:Version}),
libc6,
libgcc-s1 | libgcc1,
libstdc++6,
lm-sensors
lm-sensors,
libdbus-1-3
Multi-Arch: same
Description: 运行时信息库
Package: libkysdk-realtime-dev
Architecture: all
Section: utils
Depends: libkysdk-realtime
Depends: libkysdk-realtime (= ${binary:Version})
Multi-Arch: foreign
Description: 运行时信息库 - 开发库
Package: libkysdk-system-java
Architecture: any
Section: utils
Depends: libkysdk-system-dbus
Depends: libkysdk-system-dbus (= ${binary:Version})
Multi-Arch: same
Description: 多语言支持 - java
Package: libkysdk-system-python
Architecture: any
Depends: python3-dbus,
libkysdk-system-dbus
libkysdk-system-dbus (= ${binary:Version})
Multi-Arch: same
Description: 多语言支持 - python
@ -388,14 +369,14 @@ Package: libkysdk-system-dbus
Architecture: any
Section: utils
Depends: libqt5dbus5,
libkysdk-disk,
libkysdk-hardware,
libkysdk-location,
libkysdk-net,
libkysdk-package,
libkysdk-proc,
libkysdk-realtime,
libkysdk-sysinfo,
libkysdk-disk (= ${binary:Version}),
libkysdk-hardware (= ${binary:Version}),
libkysdk-location (= ${binary:Version}),
libkysdk-net (= ${binary:Version}),
libkysdk-package (= ${binary:Version}),
libkysdk-proc (= ${binary:Version}),
libkysdk-realtime (= ${binary:Version}),
libkysdk-sysinfo (= ${binary:Version}),
libblkid1,
libbluetooth3,
libc6,
@ -457,22 +438,21 @@ Description: 多语言支持 - javascript
Package: libkysdk-logrotate
Architecture: any
Section: utils
Depends: libkysdk-systemcommon,
Depends: libkysdk-systemcommon (= ${binary:Version}),
libqt5core5a,
libqt5dbus5,
libkysdk-log(>=1.2.0),
logrotate,
libc6,
libgcc-s1 | libgcc1,
libstdc++6,
cron
libstdc++6
Multi-Arch: same
Description: 日志转储服务
Package: libkysdk-imageproc
Architecture: any
Section: utils
Depends: libkysdk-systemcommon,
Depends: libkysdk-systemcommon (= ${binary:Version}),
libc6,
libkysdk-log(>=1.2.0),
libkysdk-config(>=1.2.0),
@ -483,6 +463,37 @@ Description: 运行时信息库
Package: libkysdk-imageproc-dev
Architecture: all
Section: utils
Depends: libkysdk-imageproc
Depends: libkysdk-imageproc (= ${binary:Version})
Description: 运行时信息库 - 开发库
Package: libkysdk-battery
Architecture: any
Section: utils
Depends: libkysdk-systemcommon (= ${binary:Version}),
libc6,
libkysdk-log (>=1.2.0),
libdbus-glib-1-2
Description: 电池管理信息库
Package: libkysdk-battery-dev
Architecture: all
Section: utils
Depends: libkysdk-battery (= ${binary:Version})
Description: 电池管理信息库 - 开发库
Package: libkysdk-accounts
Architecture: any
Depends: libdbus-1-3,
libkysdk-log(>=1.2.0),
libc6,
libdbus-glib-1-2,
libglib2.0-0,
libpolkit-gobject-1-0
Description: 系统设置
Package: libkysdk-accounts-dev
Architecture: all
Section: utils
Depends: libkysdk-accounts
Multi-Arch: foreign
Description: 系统设置库 - 开发库

2
debian/libkysdk-accounts-dev.install vendored Normal file
View File

@ -0,0 +1,2 @@
usr/include/kysdk/kysdk-system/libkyaccounts.h
development-files/kysdk-accounts.pc usr/share/pkgconfig/

2
debian/libkysdk-accounts.install vendored Normal file
View File

@ -0,0 +1,2 @@
usr/lib/*/libkysdk-accounts.so*
usr/share/polkit-1/actions/org.kylin.kysdk.accounts.policy

8
debian/libkysdk-accounts.symbols vendored Normal file
View File

@ -0,0 +1,8 @@
# SymbolsHelper-Confirmed: 2.4.1.0 amd64
libkysdk-accounts.so.1 libkysdk-accounts #MINVER#
kdk_authority_check_by_polkit@Base 2.4.1.0
kdk_login_get_public_encrypt@Base 2.4.1.0
kdk_login_send_password@Base 2.4.1.0
kdk_system_change_password@Base 2.4.1.0
kdk_system_check_has_user@Base 2.4.1.0
kdk_system_create_user@Base 2.4.1.0

2
debian/libkysdk-battery-dev.install vendored Normal file
View File

@ -0,0 +1,2 @@
usr/include/kysdk/kysdk-system/libkybattery.h
development-files/kysdk-battery.pc usr/share/pkgconfig/

1
debian/libkysdk-battery.install vendored Normal file
View File

@ -0,0 +1 @@
usr/lib/*/libkybattery.so*

11
debian/libkysdk-battery.symbols vendored Normal file
View File

@ -0,0 +1,11 @@
# SymbolsHelper-Confirmed: 2.4.1.0 amd64
libkybattery.so.1 libkysdk-battery #MINVER#
kdk_battery_get_capacity_level@Base 2.4.1.0
kdk_battery_get_charge_state@Base 2.4.1.0
kdk_battery_get_health_state@Base 2.4.1.0
kdk_battery_get_plugged_type@Base 2.4.1.0
kdk_battery_get_soc@Base 2.4.1.0
kdk_battery_get_technology@Base 2.4.1.0
kdk_battery_get_temperature@Base 2.4.1.0
kdk_battery_get_voltage@Base 2.4.1.0
kdk_battery_is_present@Base 2.4.1.0

6
debian/libkysdk-disk.postinst vendored Normal file
View File

@ -0,0 +1,6 @@
if systemctl is-active --quiet kysdk-dbus.service; then
echo "kysdk-dbus.service is active, restarting..."
systemctl restart kysdk-dbus.service
else
echo "kysdk-dbus.service is not active"
fi

6
debian/libkysdk-hardware.postinst vendored Normal file
View File

@ -0,0 +1,6 @@
if systemctl is-active --quiet kysdk-dbus.service; then
echo "kysdk-dbus.service is active, restarting..."
systemctl restart kysdk-dbus.service
else
echo "kysdk-dbus.service is not active"
fi

View File

@ -13,10 +13,6 @@ libkybluetooth.so.1 libkysdk-hardware #MINVER#
kdk_bluetooth_get_packettype@Base 2.2.3.5
kdk_bluetooth_get_scomtu@Base 2.2.3.5
libkyedid.so.1 libkysdk-hardware #MINVER#
cmd_exec@Base 2.2.3.5
detailed_block@Base 2.2.3.5
extract_string@Base 2.2.3.5
kdk_edid@Base 2.2.3.5
kdk_edid_freeall@Base 2.2.3.5
kdk_edid_get_character@Base 2.2.3.5
kdk_edid_get_gamma@Base 2.2.3.5

6
debian/libkysdk-net.postinst vendored Normal file
View File

@ -0,0 +1,6 @@
if systemctl is-active --quiet kysdk-dbus.service; then
echo "kysdk-dbus.service is active, restarting..."
systemctl restart kysdk-dbus.service
else
echo "kysdk-dbus.service is not active"
fi

View File

@ -3,7 +3,6 @@ libkyocr.so.1 libkysdk-ocr #MINVER#
_ZN3kdk10TOcrResult5resetEv@Base 1.2.1
_ZN3kdk10TOcrResultC1Ev@Base 1.2.1
_ZN3kdk10TOcrResultC2Ev@Base 1.2.1
_ZN3kdk6kdkOCR11handleImageERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE@Base 2.0.0.0
_ZN3kdk6kdkOCR6getClsERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEi@Base 1.2.1
_ZN3kdk6kdkOCR7getRectERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE@Base 1.2.1
_ZN3kdk6kdkOCRC1Ev@Base 1.2.1

6
debian/libkysdk-realtime.postinst vendored Normal file
View File

@ -0,0 +1,6 @@
if systemctl is-active --quiet kysdk-dbus.service; then
echo "kysdk-dbus.service is active, restarting..."
systemctl restart kysdk-dbus.service
else
echo "kysdk-dbus.service is not active"
fi

View File

@ -7,4 +7,11 @@ mv /usr/share/locale/ky/LC_MESSAGES/kysdk-sysinfo_ky.mo /usr/share/locale/ky/LC_
mv /usr/share/locale/de/LC_MESSAGES/kysdk-sysinfo_de.mo /usr/share/locale/de/LC_MESSAGES/kysdk-sysinfo.mo
mv /usr/share/locale/es/LC_MESSAGES/kysdk-sysinfo_es.mo /usr/share/locale/es/LC_MESSAGES/kysdk-sysinfo.mo
mv /usr/share/locale/fr/LC_MESSAGES/kysdk-sysinfo_fr.mo /usr/share/locale/fr/LC_MESSAGES/kysdk-sysinfo.mo
mv /usr/share/locale/ug/LC_MESSAGES/kysdk-sysinfo_ug.mo /usr/share/locale/ug/LC_MESSAGES/kysdk-sysinfo.mo
mv /usr/share/locale/ug/LC_MESSAGES/kysdk-sysinfo_ug.mo /usr/share/locale/ug/LC_MESSAGES/kysdk-sysinfo.mo
if systemctl is-active --quiet kysdk-dbus.service; then
echo "kysdk-dbus.service is active, restarting..."
systemctl restart kysdk-dbus.service
else
echo "kysdk-dbus.service is not active"
fi

View File

@ -2,13 +2,6 @@
libkysysinfo.so.1 libkysdk-sysinfo #MINVER#
GetIniKeyString@Base 2.0.0.0
PutIniKeyString@Base 2.0.0.0
_ZN10KDK_SYSTEM13getSystemNameB5cxx11Ev@Base 1.2.1
_ZN10KDK_SYSTEM16getKernelVersionB5cxx11Ev@Base 1.2.1
_ZN10KDK_SYSTEM16getSystemVersionB5cxx11Eb@Base 1.2.1
_ZN10KDK_SYSTEM18getCurrentUserNameB5cxx11Ev@Base 1.2.1
_ZN10KDK_SYSTEM21getSystemArchitectureB5cxx11Ev@Base 1.2.1
_ZN10KDK_SYSTEM21getSystemSerialNumberB5cxx11Ev@Base 1.2.1
_ZN10KDK_SYSTEM25getSystemActivationStatusEv@Base 1.2.1
_callback@Base 2.3.0.0
config_fetch@Base 2.2.3.5
dbus_listener_thread@Base 2.3.0.0

View File

@ -33,5 +33,3 @@ libkydate.so.1 libkysdk-systime #MINVER#
kdk_system_tran_absolute_date@Base 2.3.0.0
kdk_system_tran_dateformat@Base 2.0.0.0
path@Base 2.0.0.0
strtok_date@Base 2.0.0.0
strtok_short_date@Base 2.2.3.5

View File

@ -0,0 +1,5 @@
Name: libkysdk-accounts
Description: kysdk system layer accounts component
Version: 2.4.0
Libs: -lkysdk-accounts
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -0,0 +1,6 @@
Name: libkysdk-battery
Description: kysdk system layer battery component
Requires:
Version: 2.4.0
Libs: -lkybattery
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,6 +1,6 @@
Name: libkysdk-disk
Description: kysdk system layer disk component
Requires: kysdk-log kysdk-utils libudev blkid
Version: 2.3.0
Version: 2.4.0
Libs: -lkydiskinfo
Cflags: -I/usr/include/kysdk/kysdk-system/
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,6 +1,6 @@
Name: libkysdk-filesystem
Description: kysdk system layer filesystem component
Requires: kysdk-log kysdk-config libsystemd Qt5Core
Version: 2.3.0
Version: 2.4.0
Libs: -lkyfilewatcher
Cflags: -I/usr/include/kysdk/kysdk-system/
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,6 +1,6 @@
Name: libkysdk-hardware
Description: kysdk system layer hardware component
Requires: kysdk-log kysdk-config libsystemd libudev
Version: 2.3.0
Version: 2.4.0
Libs: -lkyhw -lkybluetooth -lkyedid -lkyfan -lkyhwinfo
Cflags: -I/usr/include/kysdk/kysdk-system/
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,5 +1,5 @@
Name: libkysdk-imageproc
Description: kysdk system layer image processment component
Version: 2.3.0
Version: 2.4.0
Libs: -lkyimageproc
Cflags: -I/usr/include/kysdk/kysdk-system/
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,6 +1,6 @@
Name: libkysdk-location
Description: kysdk system layer location
Requires:glib-2.0
Version: 2.3.0
Version: 2.4.0
Libs: -lkylocation
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,5 +1,5 @@
Name: libkysdk-net
Description: kysdk system layer netinfo
Version: 2.3.0
Version: 2.4.0
Libs: -lkynetinfo
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,5 +1,5 @@
Name: libkysdk-ocr
Description: kysdk system ocr package component
Version: 2.3.0
Version: 2.4.0
Libs: -lkyocr
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,5 +1,5 @@
Name: libkysdk-package
Description: kysdk system layer package component
Version: 2.3.0
Version: 2.4.0
Libs: -lkypackage
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,6 +1,6 @@
Name: libkysdk-powermanagement
Description: kysdk system layer powermanagement component
Requires: kysdk-log
Version: 2.3.0
Version: 2.4.0
Libs: -lkypowermanagement
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,5 +1,5 @@
Name: libkysdk-proc
Description: kysdk system layer process component
Version: 2.3.0
Version: 2.4.0
Libs: -lkyrtinfo
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,5 +1,5 @@
Name: libkysdk-realtime
Description: kysdk system layer realtime
Version: 2.3.0
Version: 2.4.0
Libs: -lkyrealtime
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,6 +1,6 @@
Name: libkysdk-sysinfo
Description: kysdk system layer sysinfo component
Requires: kysdk-log kysdk-utils libsystemd dbus-1 dbus-glib-1 gio-2.0 gio-unix-2.0 glib-2.0 gmodule-2.0 gmodule-export-2.0 gmodule-no-export-2.0 gobject-2.0 gthread-2.0
Version: 2.3.0
Version: 2.4.0
Libs: -lkysysinfo
Cflags: -I/usr/include/kysdk/kysdk-system/
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,6 +1,6 @@
Name: libkysdk-system
Description: kysdk system layer
Requires: kysdk-disk kysdk-filesystem kysdk-hardware kysdk-package kysdk-proc kysdk-sysinfo kysdk-location kysdk-net kysdk-realtime kysdk-imageproc
Version: 2.3.0
Libs: -L/usr/lib/*/ -lkydiskinfo -lkyfilewatcher -lkyhw -lkypackage -lkysysinfo -lkyrtinfo -lkylocation -lkynetinfo -lkyrealtime -lkybluetooth -lkyedid -lkyfan -lkyhwinfo -lkyimageproc -Wl,-rpath=/usr/lib/*/
Cflags: -I/usr/include/kysdk/kysdk-system/
Requires: kysdk-disk kysdk-filesystem kysdk-hardware kysdk-package kysdk-proc kysdk-sysinfo kysdk-location kysdk-net kysdk-realtime kysdk-imageproc kysdk-battery kysdk-accounts
Version: 2.4.0
Libs: -lkydiskinfo -lkyfilewatcher -lkyhw -lkypackage -lkysysinfo -lkyrtinfo -lkylocation -lkynetinfo -lkyrealtime -lkybluetooth -lkyedid -lkyfan -lkyhwinfo -lkyimageproc -lkysdk-accounts -lkybattery
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -1,6 +1,6 @@
Name: libkysdk-systime
Description: kysdk system layer date component
Requires: kysdk-config glib-2.0
Version: 2.3.0
Version: 2.4.0
Libs: -lkydate
Cflags: -I/usr/include/kysdk/kysdk-system/
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -22,3 +22,5 @@ add_subdirectory(kysdkdbus)
add_subdirectory(libkysdk-system-javascript-http)
add_subdirectory(libkysdk-system-javascript-websocket)
add_subdirectory(image)
add_subdirectory(battery)
add_subdirectory(accounts)

View File

@ -0,0 +1,37 @@
aux_source_directory(. SOURCESCODE)
include_directories(.)
find_library(GLIBC_LIB glib-2.0)
find_library(DBUS_LIB dbus-1)
find_library(DBUS_GLIB_LIB dbus-glib-1)
find_package(PkgConfig)
add_library(kysdk-accounts SHARED ${SOURCESCODE})
set_target_properties(kysdk-accounts PROPERTIES VERSION 2.4.0 SOVERSION 1)
add_executable(kyaccounts-test test/kyaccounts_test.c)
pkg_check_modules(PKGS REQUIRED polkit-gobject-1)
include_directories(${PKGS_INCLUDE_DIRS})
target_link_libraries(kysdk-accounts kylog polkit-gobject-1 ${GLIBC_LIB} ${DBUS_LIB} ${DBUS_GLIB_LIB})
target_link_libraries(kyaccounts-test kysdk-accounts)
# GNU
include(GNUInstallDirs)
# CMAKE_INSTALL_LIBDIR
if(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "armv8l")
set(CMAKE_INSTALL_LIBDIR "/usr/lib/arm-linux-gnueabihf")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "mips64")
set(CMAKE_INSTALL_LIBDIR "/usr/lib/mips64el-linux-gnuabi64")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "i686")
set(CMAKE_INSTALL_LIBDIR "/usr/lib/i386-linux-gnu")
else()
set(CMAKE_INSTALL_LIBDIR "/usr/lib/${CMAKE_HOST_SYSTEM_PROCESSOR}-linux-gnu")
endif()
#
install(TARGETS kysdk-accounts
DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(FILES libkyaccounts.h
DESTINATION include/kysdk/kysdk-system)
install(FILES org.kylin.kysdk.accounts.policy
DESTINATION share/polkit-1/actions/)

View File

@ -0,0 +1,488 @@
#include "libkyaccounts.h"
#include <dbus-1.0/dbus/dbus.h>
#include <libkylog.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <glib.h>
#include <gio/gio.h>
#include <polkit/polkit.h>
#include <syslog.h>
char *kdk_system_create_user(char *name, char *fullName, int accountType)
{
if (kdk_system_check_has_user(name) == 1)
{
klog_err("用户已存在 !\n");
return NULL;
}
char *userpath = (char *)malloc(sizeof(char) * 256);
if (!userpath)
{
return NULL;
}
memset(userpath, 0, 256);
DBusConnection *conn;
DBusError err;
dbus_error_init(&err);
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (NULL == conn)
{
goto err_out;
}
DBusMessage *info_msg = NULL;
DBusPendingCall *sendMsgPending = NULL;
DBusMessage *replyMsg = NULL;
//创建用户
info_msg = dbus_message_new_method_call("org.freedesktop.Accounts", // target for the method call
"/org/freedesktop/Accounts", // object to call on
"org.freedesktop.Accounts", // interface to call on
"CreateUser"); // method name
if (!info_msg)
{ // -1 is default timeout
klog_err("status_msgdbus_message_new_method_call调用失败\n");
goto err_out;
}
if (!dbus_message_append_args(info_msg, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &fullName, DBUS_TYPE_INT32, &accountType, DBUS_TYPE_INVALID))
{
klog_err("kdk : d-bus append args fail !\n");
goto err_out;
}
if (!dbus_connection_send_with_reply(conn, info_msg, &sendMsgPending, -1))
{
klog_err("kdk : d-bus send message fail !\n");
goto err_out;
}
if (sendMsgPending == NULL)
{
klog_err("kdk : d-bus pending message is NULL !\n");
goto err_out;
}
dbus_connection_flush(conn);
if (info_msg)
{
dbus_message_unref(info_msg);
}
dbus_pending_call_block(sendMsgPending);
replyMsg = dbus_pending_call_steal_reply(sendMsgPending);
if (replyMsg == NULL)
{
klog_err("kdk : get reply message fail !\n");
goto err_out;
}
if (sendMsgPending)
{
dbus_pending_call_unref(sendMsgPending);
}
DBusMessageIter args;
char *ret = NULL;
if (!dbus_message_iter_init(replyMsg, &args))
{
dbus_message_unref(replyMsg);
klog_err("kdk : d-bus reply message fail !\n");
goto err_out;
}
else
{
dbus_message_iter_get_basic(&args, &ret);
}
if (replyMsg)
{
dbus_message_unref(replyMsg);
}
if (!strstr(ret, "/org/freedesktop/Accounts/User"))
{
klog_err("用户名命名不规范 !\n");
goto err_out;
}
sprintf(userpath, "/home/%s", name);
if (!userpath)
{
goto err_out;
}
return userpath;
err_out:
free(userpath);
return NULL;
}
int kdk_authority_check_by_polkit()
{
PolkitAuthority *pAuthority = NULL;
GError *error = NULL;
pid_t pid_of_caller;
PolkitSubject *subject;
PolkitCheckAuthorizationFlags flags;
PolkitAuthorizationResult *polkit_ret = NULL;
pid_of_caller = getppid();
// if (pid_of_caller == 1)
// {
// g_printerr("Refusing to render service to dead parents.\n");
// return 0;
// }
subject = polkit_unix_process_new_for_owner(pid_of_caller,
0,
getuid());
gchar *actid = "org.kylin.kysdk.chpasswd";
flags = POLKIT_CHECK_AUTHORIZATION_FLAGS_NONE;
flags |= POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION;
pAuthority = polkit_authority_get_sync(NULL, &error);
polkit_ret = polkit_authority_check_authorization_sync(pAuthority,
subject,
actid,
NULL,
flags,
NULL,
NULL);
if (polkit_authorization_result_get_is_authorized(polkit_ret))
{
syslog(LOG_ERR,"polkit_ret is failed !");
g_object_unref(polkit_ret);
g_object_unref(subject);
return 1;
};
g_object_unref(polkit_ret);
g_object_unref(subject);
return 0;
}
bool kdk_system_change_password(char *username, char *password, unsigned int *err_num)
{
if (geteuid() != 0) // 非root 用户
{
int result = kdk_authority_check_by_polkit();
if (result != 1)
{
klog_err("身份认证失败!错误码:%d\n");
syslog(LOG_ERR,"身份认证失败!");
*err_num = 0x01;
return false;
}
}
if (!username && !password)
{
*err_num = 0x04;
return false;
}
if (kdk_system_check_has_user(username) != 1)
{
klog_err("用户不存在 !\n");
syslog(LOG_ERR,"用户不存在!");
*err_num = 0x02;
return false;
}
char command[2048] = "\0";
int len = strlen(password);
if (len < 8)
{
klog_err("密码少于 8 个字符!\n");
syslog(LOG_ERR,"密码少于 8 个字符!");
*err_num = 0x03;
return false;
}
if(len > 1024)
{
klog_err("密码大于 1024 个字符!\n");
syslog(LOG_ERR,"密码大于 1024 个字符!");
*err_num = 0x03;
return false;
}
if(strstr(password, "$") || strstr(password, "\""))
{
char str[1024] = "\0";
strncpy(str, password, sizeof(password));
int i, j;
int lenght = strlen(str);
char tmp[1024] = "\0";
for (i = 0, j = 0; i < lenght; i++) {
if (str[i] == '$') {
tmp[j] = '\\';
j++;
tmp[j] = '$';
}
else if(str[i] == '\"') {
tmp[j] = '\\';
j++;
tmp[j] = '\"';
}
else {
tmp[j] = str[i];
}
j++;
}
tmp[j] = '\0';
sprintf(command, "echo \"%s:%s\" | chpasswd", username, tmp);
}
else{
sprintf(command, "echo \"%s:%s\" | chpasswd", username, password);
}
int ret = system(command);
if (ret != 0)
{
klog_err("无效的密码,密码不规范!\n");
syslog(LOG_ERR,"无效的密码,密码不规范!");
*err_num = 0x03;
return false;
}
*err_num = 0;
return true;
}
bool kdk_system_check_has_user(char *username)
{
if (!username)
{
return false;
}
char path[256] = "\0";
struct stat buff;
sprintf(path, "/home/%s", username);
if (access(path, F_OK) != -1)
{
int result = stat(path, &buff);
if (__S_IFDIR & buff.st_mode)
{
return true;
}
}
return false;
}
char *kdk_login_get_public_encrypt()
{
char *pencrypt = NULL;
DBusConnection *conn;
DBusError err;
dbus_error_init(&err);
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (NULL == conn)
{
return NULL;
}
DBusMessage *info_msg = NULL;
DBusPendingCall *sendMsgPending = NULL;
DBusMessage *replyMsg = NULL;
//创建用户
info_msg = dbus_message_new_method_call("org.ukui.UniauthBackend", // target for the method call
"/org/ukui/UniauthBackend", // object to call on
"org.ukui.UniauthBackend", // interface to call on
"getPublicEncrypt"); // method name
if (!info_msg)
{ // -1 is default timeout
klog_err("status_msgdbus_message_new_method_call调用失败\n");
return NULL;
}
// if (!dbus_message_append_args(info_msg, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &fullName, DBUS_TYPE_INT32, &accountType, DBUS_TYPE_INVALID)) {
// klog_err("kdk : d-bus append args fail !\n");
// goto err_out;
// }
if (!dbus_connection_send_with_reply(conn, info_msg, &sendMsgPending, -1))
{
klog_err("kdk : d-bus send message fail !\n");
return NULL;
}
if (sendMsgPending == NULL)
{
klog_err("kdk : d-bus pending message is NULL !\n");
return NULL;
}
dbus_connection_flush(conn);
if (info_msg)
{
dbus_message_unref(info_msg);
}
dbus_pending_call_block(sendMsgPending);
replyMsg = dbus_pending_call_steal_reply(sendMsgPending);
if (replyMsg == NULL)
{
klog_err("kdk : get reply message fail !\n");
return NULL;
}
if (sendMsgPending)
{
dbus_pending_call_unref(sendMsgPending);
}
DBusMessageIter args;
if (!dbus_message_iter_init(replyMsg, &args))
{
dbus_message_unref(replyMsg);
klog_err("kdk : d-bus reply message fail !\n");
return NULL;
}
else
{
dbus_message_iter_get_basic(&args, &pencrypt);
}
if (replyMsg)
{
dbus_message_unref(replyMsg);
}
if (!pencrypt)
{
return NULL;
}
return pencrypt;
}
bool kdk_login_send_password(const char *username, unsigned char *password, int length)
{
if (!username && !password)
{
return false;
}
unsigned char *passwd = password;
bool result;
DBusConnection *conn;
DBusError err;
dbus_error_init(&err);
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (NULL == conn)
{
return false;
}
DBusMessage *info_msg = NULL;
DBusPendingCall *sendMsgPending = NULL;
DBusMessage *replyMsg = NULL;
DBusMessageIter datatoSendIter, subArrayIter;
//创建用户s
info_msg = dbus_message_new_method_call("org.ukui.UniauthBackend", // target for the method call
"/org/ukui/UniauthBackend", // object to call on
"org.ukui.UniauthBackend", // interface to call on
"sendPassword"); // method name
if (!info_msg)
{ // -1 is default timeout
klog_err("status_msgdbus_message_new_method_call调用失败\n");
return false;
}
dbus_message_iter_init_append(info_msg, &datatoSendIter);
dbus_message_iter_append_basic(&datatoSendIter, DBUS_TYPE_STRING, &username);
dbus_message_iter_open_container(&datatoSendIter, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE_AS_STRING, &subArrayIter);
dbus_message_iter_append_fixed_array(&subArrayIter, DBUS_TYPE_BYTE, &passwd, length + 1);
dbus_message_iter_close_container(&datatoSendIter, &subArrayIter);
if (!dbus_connection_send_with_reply(conn, info_msg, &sendMsgPending, -1))
{
klog_err("kdk : d-bus send message fail !\n");
return false;
}
if (sendMsgPending == NULL)
{
klog_err("kdk : d-bus pending message is NULL !\n");
return false;
}
dbus_connection_flush(conn);
if (info_msg)
{
dbus_message_unref(info_msg);
}
dbus_pending_call_block(sendMsgPending);
replyMsg = dbus_pending_call_steal_reply(sendMsgPending);
if (replyMsg == NULL)
{
klog_err("kdk : get reply message fail !\n");
return false;
}
if (sendMsgPending)
{
dbus_pending_call_unref(sendMsgPending);
}
DBusMessageIter args;
if (!dbus_message_iter_init(replyMsg, &args))
{
dbus_message_unref(replyMsg);
klog_err("kdk : d-bus reply message fail !\n");
return false;
}
else
{
dbus_message_iter_get_basic(&args, &result);
}
if (replyMsg)
{
dbus_message_unref(replyMsg);
}
return result;
}

View File

@ -0,0 +1,75 @@
#ifndef KYSDK_SYSTEM_SETTINGS_H__
#define KYSDK_SYSTEM_SETTINGS_H__
/**
* @file libkysystemsettings.h
* @brief
* @author shaozhimin (shaozhimin@kylinos.cn)
* @version 0.1
* @date 2023-10-07
* @copyright Copyright (c) 2023
*
*/
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief
* @param name
* @param fullName
* @param accountType 01
*
* @return char* NULL free
*/
char* kdk_system_create_user(char* name, char* fullName, int accountType);
/**
* @brief
* @param username
* @param password
* @param err_num 0,1,2,3,4,
*
* @return bool false代表修改失败true代表修改成功
*/
bool kdk_system_change_password(char* username, char* password, unsigned int *err_num);
/**
* @brief
* @param username
*
* @return bool false代表不存在true代表存在
*/
bool kdk_system_check_has_user(char *username);
/**
* @brief 使
*
* @return char* 使使rsa算法
*/
char* kdk_login_get_public_encrypt();
/**
* @brief
*
* @param username
* @param password
* @param length
*
* @return bool true表示开始拉起桌面会话false表示未能开始拉起桌面会话
*/
bool kdk_login_send_password(const char* username, unsigned char* password, int length);
#ifdef __cplusplus
}
#endif
#endif // KYSDK_SYSTEM_SETTINGS_H__
/**
* @}
*/

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">
<policyconfig>
<vendor>KYLINOS</vendor>
<vendor_url>http://www.kylinos.cn</vendor_url>
<icon_name>ues</icon_name>
<action id="org.kylin.kysdk.chpasswd">
<description>change the password</description>
<description xml:lang="zh">修改密码</description>
<description xml:lang="bo">བཟོ་བཅོས་ཨང་ཡིག། </description>
<message>Authorization required to modify user password.</message>
<message xml:lang="zh">需要授权以修改用户密码</message>
<message xml:lang="bo">དགོས་མཁོ་འི་དབང་ཆ་ར་བརྟེན་ནས་བཟོ་བཅོས་སྤྱོད་མཁན་ཨང་ཡིག། </message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>auth_self</allow_active>
</defaults>
</action>
</policyconfig>

View File

@ -0,0 +1,40 @@
#include <stdio.h>
#include "../libkyaccounts.h"
#include <stdlib.h>
#include <string.h>
int main()
{
char* ret = kdk_system_create_user("test", "test-pc", 0);
printf("ret = %s\n", ret);
free(ret);
unsigned int err_num;
bool pass = kdk_system_change_password("test", "qwer$\"1234\"", &err_num);
printf("pass = %d err_num = %d\n", pass, err_num);
bool user = kdk_system_check_has_user("test");
printf("user = %d\n", user);
// char *pencrypt = kdk_login_get_public_encrypt();
// printf("pencrypt = %s\n", pencrypt);
// char *password = "hhhkkkkjjuojk1234";
// int len = strlen(password);
// unsigned char *byte_array = (unsigned char *)malloc(len + 1);
// if (!byte_array)
// {
// return false;
// }
// for (int i = 0; i < len; i++) {
// byte_array[i] = (unsigned char)password[i];
// printf("byte_array[i] = %d\n", byte_array[i]);
// }
// byte_array[len] = '\0';
// bool result = kdk_login_send_password("test", byte_array, len);
// printf("result = %d\n", result);
}

View File

@ -0,0 +1,29 @@
aux_source_directory(. SOURCESCODE)
include_directories(.)
add_library(kybattery SHARED ${SOURCESCODE})
set_target_properties(kybattery PROPERTIES VERSION 2.4.0 SOVERSION 1)
add_executable(kybattery-test test/kybattery-test.c)
target_link_libraries(kybattery dbus-glib-1 kylog)
target_link_libraries(kybattery-test kybattery)
# GNU
include(GNUInstallDirs)
# CMAKE_INSTALL_LIBDIR
if(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "armv8l")
set(CMAKE_INSTALL_LIBDIR "/usr/lib/arm-linux-gnueabihf")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "mips64")
set(CMAKE_INSTALL_LIBDIR "/usr/lib/mips64el-linux-gnuabi64")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "i686")
set(CMAKE_INSTALL_LIBDIR "/usr/lib/i386-linux-gnu")
else()
set(CMAKE_INSTALL_LIBDIR "/usr/lib/${CMAKE_HOST_SYSTEM_PROCESSOR}-linux-gnu")
endif()
#
install(TARGETS kybattery
DESTINATION ${CMAKE_INSTALL_LIBDIR})
# install(TARGETS kybattery
# DESTINATION lib/kysdk/kysdk-system)
install(FILES libkybattery.h
DESTINATION include/kysdk/kysdk-system)

818
src/battery/libkybattery.c Normal file
View File

@ -0,0 +1,818 @@
#include "libkybattery.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <kysdk/kysdk-base/cstring-extension.h>
#include "dbus/dbus-glib.h"
#include "libkylog.h"
#define SERVERNAME "org.freedesktop.UPower"
#define PROPERTIES_FACE "org.freedesktop.DBus.Properties"
#define DEVICEINTERFACE "org.freedesktop.UPower.Device"
struct power_device
{
char name[256]; //设备名
char native_path[32];
bool power_supply;
char updated[64];
bool has_history;
bool has_statistics;
bool is_persent;
bool is_rechargeable;
char state[32];
char warning_level[32];
double energy;
double energy_empty;
double energy_full;
double energy_full_design;
double energy_rate;
double voltage;
long time_to_empty;
long time_to_full;
double percentage;
double temperature;
double capacity;
char technology[32];
bool online;
char icon_name[64];
char model[64];
int battery_level;
int type;
struct power_device *next;
};
struct Power
{
char daemon_version[32]; //版本
bool on_battery; //是否存在电池
bool lid_is_closed;
bool lid_is_present;
char critical_action[32];
struct power_device *devices;
};
static void kdk_hw_free_power_info(struct Power *info)
{
if (info)
{
struct power_device *tmp = NULL;
while (info->devices)
{
tmp = info->devices;
info->devices = info->devices->next;
free(tmp);
}
free(info);
}
}
static void _write_info(struct power_device *node, GHashTable *info_hash)
{
GValue *attr = (GValue *)g_hash_table_lookup(info_hash, "NativePath");
strcpy(node->native_path, attr ? g_value_get_string(attr) : "None");
attr = (GValue *)g_hash_table_lookup(info_hash, "PowerSupply");
node->power_supply = attr ? g_value_get_boolean(attr) : false;
struct tm *time_tm;
attr = (GValue *)g_hash_table_lookup(info_hash, "UpdateTime");
time_t t = (time_t)g_value_get_uint64(attr);
time_tm = localtime(&t);
strftime(node->updated, sizeof node->updated, "%c", time_tm);
attr = (GValue *)g_hash_table_lookup(info_hash, "HasHistory");
node->has_history = attr ? g_value_get_boolean(attr) : false;
attr = (GValue *)g_hash_table_lookup(info_hash, "HasStatistics");
node->has_statistics = attr ? g_value_get_boolean(attr) : false;
attr = (GValue *)g_hash_table_lookup(info_hash, "IsPresent");
node->is_persent = attr ? g_value_get_boolean(attr) : false;
attr = (GValue *)g_hash_table_lookup(info_hash, "IsRechargeable");
node->is_rechargeable = attr ? g_value_get_boolean(attr) : false;
attr = (GValue *)g_hash_table_lookup(info_hash, "State");
switch (g_value_get_uint(attr))
{
case 1:
strcpy(node->state, "charging");
break;
case 2:
strcpy(node->state, "discharging");
break;
case 3:
strcpy(node->state, "empty");
break;
case 4:
strcpy(node->state, "fully-charged");
break;
case 5:
strcpy(node->state, "pending-charge");
break;
case 6:
strcpy(node->state, "pending-discharge");
break;
default:
strcpy(node->state, "unknown");
break;
}
attr = (GValue *)g_hash_table_lookup(info_hash, "WarningLevel");
switch (g_value_get_uint(attr))
{
case 1:
strcpy(node->warning_level, "none");
break;
case 2:
strcpy(node->warning_level, "discharging");
break;
case 3:
strcpy(node->warning_level, "low");
break;
case 4:
strcpy(node->warning_level, "critical");
break;
case 5:
strcpy(node->warning_level, "action");
break;
case 6:
strcpy(node->warning_level, "normal");
break;
case 7:
strcpy(node->warning_level, "high");
break;
case 8:
strcpy(node->warning_level, "full");
break;
default:
strcpy(node->warning_level, "unknown");
break;
}
attr = (GValue *)g_hash_table_lookup(info_hash, "Energy");
node->energy = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "EnergyEmpty");
node->energy_empty = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "EnergyFull");
node->energy_full = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "EnergyFullDesign");
node->energy_full_design = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "EnergyRate");
node->energy_rate = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "Voltage");
node->voltage = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "TimeToEmpty");
node->time_to_empty = attr ? g_value_get_int64(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "TimeToFull");
node->time_to_full = attr ? g_value_get_int64(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "Percentage");
node->percentage = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "Temperature");
node->temperature = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "Capacity");
node->capacity = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "Technology");
switch (g_value_get_uint(attr))
{
case 1:
strcpy(node->technology, "lithium-ion");
break;
case 2:
strcpy(node->technology, "lithium-polymer");
break;
case 3:
strcpy(node->technology, "lithium-iron-phosphate");
break;
case 4:
strcpy(node->technology, "lead-acid");
break;
case 5:
strcpy(node->technology, "nickel-cadmium");
break;
case 6:
strcpy(node->technology, "nickel-metal-hydride");
break;
default:
strcpy(node->technology, "unknown");
break;
}
attr = (GValue *)g_hash_table_lookup(info_hash, "Online");
node->online = attr ? g_value_get_boolean(attr) : false;
attr = (GValue *)g_hash_table_lookup(info_hash, "IconName");
strcpy(node->icon_name, attr ? g_value_get_string(attr) : "None");
attr = (GValue *)g_hash_table_lookup(info_hash, "Model");
strcpy(node->model, attr ? g_value_get_string(attr) : "None");
attr = (GValue *)g_hash_table_lookup(info_hash, "BatteryLevel");
node->battery_level = g_value_get_uint(attr);
attr = (GValue *)g_hash_table_lookup(info_hash, "Type");
node->type = g_value_get_uint(attr);
}
static void _daemon_forech(gpointer key, gpointer value, gpointer user_data)
{
char *tmp = (char *)key;
GValue *data = (GValue *)value;
struct Power *result = (struct Power *)user_data;
if (0 == strcmp(tmp, "DaemonVersion"))
strcpy(result->daemon_version, g_value_get_string(data));
if (0 == strcmp(tmp, "LidIsClosed"))
result->lid_is_closed = g_value_get_boolean(data);
if (0 == strcmp(tmp, "LidIsPresent"))
result->lid_is_present = g_value_get_boolean(data);
if (0 == strcmp(tmp, "OnBattery"))
result->on_battery = g_value_get_boolean(data);
}
static bool get_daemon_info(DBusGConnection *bus, GError **error, struct Power *result, DBusGProxy **upower_proxy)
{
bool success = true;
char *critical_action = NULL;
DBusGProxy *properties_porxy = NULL;
GHashTable *info_hash = NULL;
do
{
properties_porxy = dbus_g_proxy_new_for_name(bus,
SERVERNAME, // server
"/org/freedesktop/UPower", // path
PROPERTIES_FACE); // interface
if (!dbus_g_proxy_call(properties_porxy, "GetAll", error,
G_TYPE_STRING, SERVERNAME,
G_TYPE_INVALID,
dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE), &info_hash,
G_TYPE_INVALID))
{
klog_err("Failed to call GetAll in path %s : %s\n", "/org/freedesktop/UPower", (*error)->message);
success = false;
break;
}
// 轮询哈希表
g_hash_table_foreach(info_hash, _daemon_forech, result);
// 创建UPower代理
*upower_proxy = dbus_g_proxy_new_for_name(bus,
SERVERNAME, // server
"/org/freedesktop/UPower", // path
SERVERNAME); // interface
// 获取CriticalAction
if (!dbus_g_proxy_call(*upower_proxy, "GetCriticalAction", error,
G_TYPE_INVALID,
G_TYPE_STRING, &critical_action,
G_TYPE_INVALID))
{
klog_err("Failed to call GetCriticalAction in path %s : %s\n", "/org/freedesktop/UPower", (*error)->message);
success = false;
break;
}
strcpy(result->critical_action, critical_action);
} while (0);
if (properties_porxy)
g_object_unref((properties_porxy));
if (info_hash)
g_hash_table_unref(info_hash);
if (critical_action)
free(critical_action);
return success;
}
static bool get_display_info(DBusGConnection *bus, DBusGProxy *upower_proxy, GError **error, struct Power *result)
{
bool success = true;
DBusGProxy *display_proxy = NULL;
GHashTable *info_hash = NULL;
char *display_path = NULL;
// 获取displaydevice
do
{
if (!dbus_g_proxy_call(upower_proxy, "GetDisplayDevice", error,
G_TYPE_INVALID,
DBUS_TYPE_G_OBJECT_PATH, &display_path,
G_TYPE_INVALID))
{
klog_err("Failed to call GetDisplayDevice in path %s : %s\n",
"/org/freedesktop/UPower",
(*error)->message);
success = false;
break;
}
display_proxy = dbus_g_proxy_new_for_name(bus,
SERVERNAME, // server
display_path, // path
PROPERTIES_FACE); // interface
if (!dbus_g_proxy_call(display_proxy, "GetAll", error,
G_TYPE_STRING, DEVICEINTERFACE,
G_TYPE_INVALID,
dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE), &info_hash,
G_TYPE_INVALID))
{
klog_err("Failed to call GetAll in path %s : %s\n", display_path, (*error)->message);
success = false;
break;
}
struct power_device *node = (struct power_device *)calloc(1, sizeof *node);
if (!node)
{
klog_err("Failed to request memory %s\n", display_path);
success = false;
break;
}
// 写入display device数据
result->devices = node;
strcpy(node->name, display_path);
_write_info(node, info_hash);
} while (0);
if (display_proxy)
g_object_unref(display_proxy);
if (display_path)
free(display_path);
if (info_hash)
g_hash_table_unref(info_hash);
return success;
}
static bool get_device_info(DBusGConnection *bus, GError **error, const char *p, struct Power *result)
{
bool success = true;
DBusGProxy *device_proxy = NULL;
GHashTable *info_hash;
do
{
device_proxy = dbus_g_proxy_new_for_name(bus,
SERVERNAME, // server
p, // path
PROPERTIES_FACE); // interface
if (!dbus_g_proxy_call(device_proxy, "GetAll", error,
G_TYPE_STRING, DEVICEINTERFACE,
G_TYPE_INVALID,
dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE), &info_hash,
G_TYPE_INVALID))
{
klog_err("Failed to call GetAll in path %s : %s\n", p, (*error)->message);
success = false;
break;
}
struct power_device *node = (struct power_device *)calloc(1, sizeof *node);
if (!node)
{
klog_err("Failed to request memory %s\n", p);
success = false;
break;
}
// 前插
node->next = result->devices;
result->devices = node;
// 写入device device数据
strcpy(node->name, p);
_write_info(node, info_hash);
} while (0);
if (device_proxy)
g_object_unref(device_proxy);
if (info_hash)
g_hash_table_unref(info_hash);
return success;
}
static struct Power *kdk_hw_get_powerinfo()
{
bool success = true;
DBusGProxy *upower_proxy = NULL;
GError *error = NULL;
DBusGConnection *bus = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
if (!bus)
{
klog_err("Couldn't connect to system bus : %s\n", error->message);
return NULL;
}
struct Power *result = (struct Power *)calloc(1, sizeof *result);
if (!result)
{
klog_err("Failed to request memory Power");
dbus_g_connection_unref(bus);
return NULL;
}
if (!(success = get_daemon_info(bus, &error, result, &upower_proxy)))
goto out;
if (!(success = get_display_info(bus, upower_proxy, &error, result)))
goto out;
// 获取Device列表
GPtrArray *devices = NULL;
if (!dbus_g_proxy_call(upower_proxy, "EnumerateDevices", &error,
G_TYPE_INVALID,
dbus_g_type_get_collection("GPtrArray", DBUS_TYPE_G_OBJECT_PATH), &devices,
G_TYPE_INVALID))
{
klog_err("Failed to call EnumerateDevices in path %s : %s\n", "/org/freedesktop/UPower", error->message);
success = false;
goto out;
}
for (guint i = 0; i < devices->len; i++)
{
if (!(success = get_device_info(bus, &error, (char *)g_ptr_array_index(devices, i), result)))
goto out;
}
out:
if (!success)
{
kdk_hw_free_power_info(result);
result = NULL;
}
if (error)
g_error_free(error);
if (devices)
g_ptr_array_unref(devices);
if (upower_proxy)
g_object_unref(upower_proxy);
if (bus)
dbus_g_connection_unref(bus);
return result;
}
float kdk_battery_get_soc()
{
float percentage = 0.0;
struct Power * power = kdk_hw_get_powerinfo();
struct power_device *tmp = power->devices;
while (tmp)
{
if(strstr(tmp->name, "battery"))
{
percentage = tmp->percentage;
}
tmp = tmp->next;
}
kdk_hw_free_power_info(power);
return percentage;
}
BatteryChargeState kdk_battery_get_charge_state()
{
char *path = NULL;
char charge_path[128] = "\0";
char state[64] = "\0";
struct Power * power = kdk_hw_get_powerinfo();
struct power_device *tmp = power->devices;
while (tmp)
{
if(strstr(tmp->name, "battery"))
{
if(tmp->native_path)
{
path = malloc(strlen(tmp->native_path) + 1);
strcpy(path, tmp->native_path);
}
}
tmp = tmp->next;
}
kdk_hw_free_power_info(power);
if(path)
{
sprintf(charge_path, "/sys/class/power_supply/%s/status", path);
free(path);
}
FILE *fp = NULL;
fp = fopen(charge_path, "r");
if (fp)
{
fgets(state, 64, fp);
}
strstripspace(state);
if(strcmp(state, "Charging") == 0)
{
return ENABLE;
}
else if(strcmp(state, "Discharging") == 0)
{
return DISABLE;
}
else if(strcmp(state, "Full") == 0)
{
return FULL;
}
else if(strcmp(state, "Not charging") == 0)
{
return NOT_CHARGING;
}
else if(strcmp(state, "Unknown") == 0)
{
return NONE;
}
else
{
return NONE;
}
}
BatteryHealthState kdk_battery_get_health_state()
{
char *path = NULL;
char health_path[128] = "\0";
char state[64] = "\0";
struct Power * power = kdk_hw_get_powerinfo();
struct power_device *tmp = power->devices;
while (tmp)
{
if(strstr(tmp->name, "battery"))
{
if(tmp->native_path)
{
path = malloc(strlen(tmp->native_path) + 1);
strcpy(path, tmp->native_path);
}
}
tmp = tmp->next;
}
kdk_hw_free_power_info(power);
if(path)
{
sprintf(health_path, "/sys/class/power_supply/%s/health", path);
free(path);
}
FILE *fp = NULL;
fp = fopen(health_path, "r");
if (fp)
{
fgets(state, 64, fp);
}
strstripspace(state);
if(strcmp(state, "Good") == 0)
{
return GOOD;
}
else if(strcmp(state, "Overheat") == 0)
{
return OVERHEAT;
}
else if(strcmp(state, "Over voltage") == 0)
{
return OVERVOLTAGE;
}
else if(strcmp(state, "Cold") == 0)
{
return COLD;
}
else if(strcmp(state, "Dead") == 0)
{
return DEAD;
}
else if(strcmp(state, "Unspecified failure") == 0)
{
return UNSPEC_FAILURE;
}
else if(strcmp(state, "Watchdog timer expire") == 0)
{
return WATCHDOG_TIMER_EXPIRE;
}
else if(strcmp(state, "Safety timer expire") == 0)
{
return SAFETY_TIMER_EXPIRE;
}
else if(strcmp(state, "Over current") == 0)
{
return OVERCURRENT;
}
else if(strcmp(state, "Calibration required") == 0)
{
return CALIBRATION_REQUIRED;
}
else if(strcmp(state, "Warm") == 0)
{
return WARM;
}
else if(strcmp(state, "Cool") == 0)
{
return COOL;
}
else if(strcmp(state, "Unknown") == 0)
{
return UNKNOWN;
}
else
{
return UNKNOWN;
}
}
BatteryPluggedType kdk_battery_get_plugged_type()
{
char *path = NULL;
char type_path[128] = "\0";
char state[64] = "\0";
struct Power * power = kdk_hw_get_powerinfo();
struct power_device *tmp = power->devices;
while (tmp)
{
if(strstr(tmp->name, "battery"))
{
if(tmp->native_path)
{
path = malloc(strlen(tmp->native_path) + 1);
strcpy(path, tmp->native_path);
}
}
tmp = tmp->next;
}
kdk_hw_free_power_info(power);
if(path)
{
sprintf(type_path, "/sys/class/power_supply/%s/type", path);
free(path);
}
FILE *fp = NULL;
fp = fopen(type_path, "r");
if (fp)
{
fgets(state, 64, fp);
}
strstripspace(state);
if(strcmp(state, "Mains") == 0)
{
return MAINS;
}
else if(strcmp(state, "Battery") == 0)
{
return BATTERY;
}
else if(strcmp(state, "USB_DCP") == 0)
{
return USB_DCP;
}
else if(strcmp(state, "USB_CDP") == 0)
{
return USB_CDP;
}
else if(strcmp(state, "USB_ACA") == 0)
{
return USB_ACA;
}
else if(strcmp(state, "UPS") == 0)
{
return UPS;
}
else if(strcmp(state, "USB") == 0)
{
return USB;
}
else if(strcmp(state, "USB_C") == 0)
{
return USB_TYPE_C;
}
else if(strcmp(state, "USB_PD") == 0)
{
return USB_PD;
}
else if(strcmp(state, "USB_PD_DRP") == 0)
{
return USB_PD_DRP;
}
else if(strcmp(state, "BrickID") == 0)
{
return APPLE_BRICK_ID;
}
else if(strcmp(state, "Wireless") == 0)
{
return WIRELESS;
}
else if(strcmp(state, "Unknown") == 0)
{
return TYPE_NONE;
}
else{
return TYPE_NONE;
}
}
float kdk_battery_get_voltage()
{
float voltage = 0.0;
struct Power * power = kdk_hw_get_powerinfo();
struct power_device *tmp = power->devices;
while (tmp)
{
if(strstr(tmp->name, "battery"))
{
voltage = tmp->voltage;
}
tmp = tmp->next;
}
kdk_hw_free_power_info(power);
return voltage;
}
char* kdk_battery_get_technology()
{
char *model = NULL;
struct Power * power = kdk_hw_get_powerinfo();
struct power_device *tmp = power->devices;
while (tmp)
{
if(strstr(tmp->name, "battery"))
{
if(tmp->model)
{
model = malloc(strlen(tmp->model) + 1);
strcpy(model, tmp->model);
}
}
tmp = tmp->next;
}
kdk_hw_free_power_info(power);
return model;
}
float kdk_battery_get_temperature()
{
float temperature = 0.0;
struct Power * power = kdk_hw_get_powerinfo();
struct power_device *tmp = power->devices;
while (tmp)
{
if(strstr(tmp->name, "battery"))
{
temperature = tmp->temperature;
}
tmp = tmp->next;
}
kdk_hw_free_power_info(power);
return temperature;
}
bool kdk_battery_is_present()
{
bool on_battery = false;
struct Power * power = kdk_hw_get_powerinfo();
struct power_device *tmp = power->devices;
while (tmp)
{
if(strstr(tmp->name, "battery"))
{
on_battery = tmp->is_persent;
}
tmp = tmp->next;
}
kdk_hw_free_power_info(power);
return on_battery;
}
int kdk_battery_get_capacity_level()
{
int level = 0;
struct Power * power = kdk_hw_get_powerinfo();
struct power_device *tmp = power->devices;
while (tmp)
{
if(strstr(tmp->name, "battery"))
{
level = tmp->battery_level;
}
tmp = tmp->next;
}
kdk_hw_free_power_info(power);
return level;
}

141
src/battery/libkybattery.h Normal file
View File

@ -0,0 +1,141 @@
#ifndef LIBKYBATTERY_H
#define LIBKYBATTERY_H
/**
* @file libkybattery.h
* @author liuyunhe (liuyunhe@kylinos.cn)
* @brief
* @version 0.1
* @date 2024-2-20
*
* @copyright Copyright (c) 2021
* @defgroup libkysdk-hardware
* @{
*
*/
#include <stdbool.h>
#ifdef __cplusplus
extern "C"
{
#endif
typedef enum _BatteryChargeState
{
NONE = 0, //电池充电状态未知
ENABLE, //电池充电状态为使能状态(充电)
DISABLE, //电池充电状态为停止状态(放电)
FULL, //电池充电状态为已充满状态
NOT_CHARGING //电池充电状态为未充电
}BatteryChargeState;
typedef enum _BatteryHealthState
{
UNKNOWN = 0, //电池健康状态未知
GOOD, //电池健康状态为正常
OVERHEAT, //电池健康状态为过热
OVERVOLTAGE, //电池健康状态为过压
COLD, //电池健康状态为低温
DEAD, //电池健康状态为僵死状态
UNSPEC_FAILURE, //电池的健康状态为未指定的故障
WATCHDOG_TIMER_EXPIRE, //看门狗定时器到期
SAFETY_TIMER_EXPIRE, //安全定时器到期
OVERCURRENT, //过电流
CALIBRATION_REQUIRED, //需要校准
WARM, //电池的健康状态为温暖;正常状态
COOL //电池的健康状态为凉爽;正常状态
}BatteryHealthState;
typedef enum _BatteryPluggedType
{
TYPE_NONE = 0, //连接充电器类型未知
BATTERY, //连接的充电器类型为电池
UPS, //连接的充电器类型为不间断电源
MAINS, //连接的充电器类型为交流电源
USB, //连接的充电器类型为USB
USB_DCP, //连接的充电器类型为专用于充电的USB端口提供更大的电流
USB_CDP, //通过USB接口连接的可用于下游设备充电的端口
USB_ACA, //USB附件充电适配器
USB_TYPE_C, //USB Type-C接口
USB_PD, //USB Type-C接口快充
USB_PD_DRP, //USB Type-C接口的工作模式可以充当主机或设备的角色具有双重作用
APPLE_BRICK_ID, //苹果充电方式
WIRELESS //连接的充电器类型为无线充电器
}BatteryPluggedType;
/**
* @brief
*
* @return float
*/
extern float kdk_battery_get_soc();
/**
* @brief
*
* @return BatteryChargeState
*/
extern BatteryChargeState kdk_battery_get_charge_state();
/**
* @brief
*
* @return BatteryHealthState
*/
extern BatteryHealthState kdk_battery_get_health_state();
/**
* @brief ()
*
* @return BatteryPluggedType
*/
extern BatteryPluggedType kdk_battery_get_plugged_type();
/**
* @brief
*
* @return float ,
*/
extern float kdk_battery_get_voltage();
/**
* @brief
*
* @return char* NULL
*/
extern char* kdk_battery_get_technology();
/**
* @brief
*
* @return float ,
*/
extern float kdk_battery_get_temperature();
/**
* @brief
*
* @return bool true-false-
*/
extern bool kdk_battery_is_present();
/**
* @brief
*
* @return int
*/
extern int kdk_battery_get_capacity_level();
#ifdef __cplusplus
}
#endif
#endif
/**
* \example kysdk-system/src/hardware/test/kybios-test.c
*
*/

View File

@ -0,0 +1,34 @@
#include "stdio.h"
#include "../libkybattery.h"
#include <stdlib.h>
int main()
{
float percentage = kdk_battery_get_soc();
printf("percentage = %0.2f\n", percentage);
BatteryChargeState state = kdk_battery_get_charge_state();
printf("state = %d\n", state);
BatteryHealthState health_state = kdk_battery_get_health_state();
printf("health state = %d\n", health_state);
BatteryPluggedType type = kdk_battery_get_plugged_type();
printf("type = %d\n", type);
float voltage = kdk_battery_get_voltage();
printf("voltage = %0.3f\n", voltage);
char* model = kdk_battery_get_technology();
printf("model = %s\n", model);
float temperature = kdk_battery_get_temperature();
printf("temperature = %0.1f\n", temperature);
bool is_present = kdk_battery_is_present();
printf("is_present : %s\n", is_present ? "true" : "false");
int level = kdk_battery_get_capacity_level();
printf("level = %d\n", level);
return 0;
}

View File

@ -1,9 +1,10 @@
aux_source_directory(. SOURCESCODE)
add_library(kydiskinfo SHARED ${SOURCESCODE})
set_target_properties(kydiskinfo PROPERTIES VERSION 2.3.0 SOVERSION 1)
set_target_properties(kydiskinfo PROPERTIES VERSION 2.4.0 SOVERSION 1)
add_executable(test-getdiskinfo test/getdiskinfo.c)
add_executable(test-getdisklist test/getdisklist.c)
find_library(UDEV_LIB udev)
find_library(DBUS_LIB dbus-1)
target_link_libraries(kydiskinfo blkid kylog pthread systemd kyconf hd ${UDEV_LIB})
target_link_libraries(test-getdiskinfo kydiskinfo)
target_link_libraries(test-getdisklist kydiskinfo)

File diff suppressed because it is too large Load Diff

View File

@ -196,6 +196,14 @@ extern char* kdk_get_hard_vendor(const char *hardname);
*/
extern void kdk_free_diskinfo(kdk_diskinfo *disk);
/**
* @brief
*
* @param hardname /dev/sda这种绝对路径
* @return int
*/
extern int kdk_get_hard_running_time(const char *hardname);
#ifdef __cplusplus
}
#endif

View File

@ -63,6 +63,9 @@ int main()
display_disk_info(sdainfo);
kdk_free_diskinfo(sdainfo);
int time = kdk_get_hard_running_time(disklist[i]);
printf("运行时长 = %d\n", time);
}
kdk_free_disklist(disklist);

View File

@ -5,7 +5,7 @@ aux_source_directory(. SOURCECODE)
find_package(Qt5Core)
include_directories(${Qt5Core_INCLUDE_DIRS})
add_library(kyfilewatcher SHARED ${SOURCECODE})
set_target_properties(kyfilewatcher PROPERTIES VERSION 2.3.0 SOVERSION 1)
set_target_properties(kyfilewatcher PROPERTIES VERSION 2.4.0 SOVERSION 1)
add_executable(kyfilewatcher-test test/kyfilewatcher-test.cpp)
target_link_libraries(kyfilewatcher kylog kyconf systemd pthread ${Qt5Core_LIBRARIES})
target_link_libraries(kyfilewatcher-test kyfilewatcher)

View File

@ -1,11 +1,9 @@
include(FindPkgConfig)
pkg_check_modules(GLIB REQUIRED glib-2.0)
pkg_check_modules(GLIB REQUIRED glib-2.0 libnl-3.0)
include_directories(${GLIB_INCLUDE_DIRS})
pkg_search_module(LIB_NL3 REQUIRED libnl-3.0)
pkg_search_module(LIB_NL3_ROUTE REQUIRED libnl-route-3.0)
include_directories(${LIB_NL3_INCLUDE_DIRS})
include_directories(${LIB_NL3_ROUTE_INCLUDE_DIRS})
pkg_check_modules(LIBNL REQUIRED libnl-3.0 libnl-genl-3.0 libnl-route-3.0)
include_directories(${LIBNL_INCLUDE_DIRS})
set(HARDWARE_TOP_DIR ${CMAKE_CURRENT_LIST_DIR})
set(hwcode
@ -41,21 +39,20 @@ set(hwinfocode
"${HARDWARE_TOP_DIR}/libkyhw.h"
"${HARDWARE_TOP_DIR}/libkyhw.c")
add_library(kyhw SHARED ${hwcode})
set_target_properties(kyhw PROPERTIES VERSION 2.3.0 SOVERSION 1)
set_target_properties(kyhw PROPERTIES VERSION 2.4.0 SOVERSION 1)
add_library(kybluetooth SHARED ${bluetoothcode})
set_target_properties(kybluetooth PROPERTIES VERSION 2.3.0 SOVERSION 1)
set_target_properties(kybluetooth PROPERTIES VERSION 2.4.0 SOVERSION 1)
add_library(kyedid SHARED ${edidcode})
set_target_properties(kyedid PROPERTIES VERSION 2.3.0 SOVERSION 1)
set_target_properties(kyedid PROPERTIES VERSION 2.4.0 SOVERSION 1)
add_library(kyfan SHARED ${fancode})
set_target_properties(kyfan PROPERTIES VERSION 2.3.0 SOVERSION 1)
set_target_properties(kyfan PROPERTIES VERSION 2.4.0 SOVERSION 1)
add_library(kyhwinfo SHARED ${hwinfocode})
set_target_properties(kyhwinfo PROPERTIES VERSION 2.3.0 SOVERSION 1)
set_target_properties(kyhwinfo PROPERTIES VERSION 2.4.0 SOVERSION 1)
add_executable(kync-test test/kync-test.c)
add_executable(kycpu-test test/kycpu-test.c)
@ -70,7 +67,8 @@ add_executable(kybluetooth-test test/kybluetooth-test.c)
add_executable(kyfan-test test/kyfan-test.c)
add_executable(kyhw-test test/kyhw-test.c)
#
target_link_libraries(kyhw kylog kyconf pthread systemd cups curl udev ${GLIB_LIBRARIES} ${LIB_NL3_LIBRARIES} ${LIB_NL3_ROUTE_LIBRARIES})
find_library(DBUS_LIB dbus-1)
target_link_libraries(kyhw kylog kyconf pthread systemd cups curl udev usb-1.0 ${GLIB_LIBRARIES} ${DBUS_LIB} ${LIBNL_LIBRARIES})
target_link_libraries(kybluetooth bluetooth hd gobject-2.0)
target_link_libraries(kyedid kylog m X11 Xrandr hd)
target_link_libraries(kyfan sensors)

View File

@ -34,7 +34,7 @@
int** kdk_bluetooth_get_device_id()
{
static struct hci_dev_info di;
int **id = (int *)malloc(sizeof(int) * 16);
int **id = (int **)calloc(16, sizeof(int*));
if(!id)
{
return 0;
@ -79,19 +79,12 @@ int** kdk_bluetooth_get_device_id()
char *kdk_bluetooth_get_manufacturer(int id)
{
char *manufacturer = (char *)malloc(64 * sizeof(char));
if (!manufacturer)
{
return NULL;
}
char name[64] = "\0";
hd_data_t *hd_data;
hd_data = (hd_data_t *)calloc(1, sizeof *hd_data);
if (!hd_data)
{
free(manufacturer);
hd_free_hd_data(hd_data);
return NULL;
}
@ -100,6 +93,11 @@ char *kdk_bluetooth_get_manufacturer(int id)
int i = 0;
hd_t *hd, *hd0;
hd0 = hd_list(hd_data, hw_bluetooth, 1, NULL);
if(!hd0)
{
goto out;
}
for (hd = hd0; hd; hd = hd->next)
{
if(i == id)
@ -113,30 +111,29 @@ char *kdk_bluetooth_get_manufacturer(int id)
}
if(name[0] == '\0')
{
free(manufacturer);
hd_free_hd_data(hd_data);
hd_free_hd_list(hd0);
return NULL;
goto out;
}
char *manufacturer = (char *)malloc(64 * sizeof(char));
if (!manufacturer)
{
goto out;
}
strcpy(manufacturer, name);
return manufacturer;
return manufacturer;
out:
hd_free_hd_data(hd_data);
hd_free_hd_list(hd0);
return NULL;
}
char *kdk_bluetooth_get_dev_version(int id)
{
char *version = (char *)malloc(12 * sizeof(char));
if (!version)
{
return NULL;
}
char name[64] = "\0";
hd_data_t *hd_data;
hd_data = (hd_data_t *)calloc(1, sizeof *hd_data);
if (!hd_data)
{
free(version);
hd_free_hd_data(hd_data);
return NULL;
}
@ -146,6 +143,11 @@ char *kdk_bluetooth_get_dev_version(int id)
int i = 0;
hd_t *hd, *hd0;
hd0 = hd_list(hd_data, hw_bluetooth, 1, NULL);
if(!hd0)
{
return NULL;
}
for (hd = hd0; hd; hd = hd->next)
{
if(i == id)
@ -157,6 +159,9 @@ char *kdk_bluetooth_get_dev_version(int id)
}
i++;
}
hd_free_hd_data(hd_data);
hd_free_hd_list(hd0);
if(name[0] == '\0')
{
int ctl;
@ -167,48 +172,38 @@ char *kdk_bluetooth_get_dev_version(int id)
if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0)
{
free(version);
hd_free_hd_data(hd_data);
hd_free_hd_list(hd0);
return NULL;
}
if (ioctl(ctl, HCIGETDEVINFO, (void *)&di))
{
free(version);
hd_free_hd_data(hd_data);
hd_free_hd_list(hd0);
return NULL;
}
// print_dev_info(ctl, &di);
dd = hci_open_dev(di.dev_id);
if (dd < 0)
{
free(version);
hd_free_hd_data(hd_data);
hd_free_hd_list(hd0);
return NULL;
}
if (hci_read_local_version(dd, &ver, 1000) < 0)
{
free(version);
hd_free_hd_data(hd_data);
hd_free_hd_list(hd0);
return NULL;
}
if(ver.hci_rev)
{
sprintf(tmp, "0x%x", ver.hci_rev);
strcpy(version, tmp);
}
strcpy(name, tmp);
}
hci_close_dev(dd);
}
else{
strcpy(version, name);
}
char *version = (char *)malloc(12 * sizeof(char));
if (!version)
{
return NULL;
}
strcpy(version, name);
return version;
}
@ -219,33 +214,24 @@ char* kdk_bluetooth_get_name(int id)
int dd;
char name[249];
int i;
char *version = (char *)malloc(sizeof(char) * 64);
if(!version)
{
return NULL;
}
if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0)
{
free(version);
return NULL;
}
di.dev_id = id;
if (ioctl(ctl, HCIGETDEVINFO, (void *)&di))
{
free(version);
return NULL;
}
dd = hci_open_dev(di.dev_id);
if (dd < 0) {
free(version);
return NULL;
}
if (hci_read_local_name(dd, sizeof(name), name, 1000) < 0) {
free(version);
return NULL;
}
@ -254,9 +240,15 @@ char* kdk_bluetooth_get_name(int id)
name[i] = '.';
}
name[248] = '\0';
strcpy(version, name);
hci_close_dev(dd);
name[248] = '\0';
char *version = (char *)malloc(sizeof(char) * 64);
if(!version)
{
return NULL;
}
strcpy(version, name);
return version;
}
@ -265,11 +257,9 @@ char* kdk_bluetooth_get_address(int id)
int ctl;
static struct hci_dev_info di;
char addr[18] = "\0";
char *address = (char *)malloc(sizeof(char) * 64);
if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0)
{
free(address);
return NULL;
}
@ -277,11 +267,15 @@ char* kdk_bluetooth_get_address(int id)
if (ioctl(ctl, HCIGETDEVINFO, (void *)&di))
{
free(address);
return NULL;
}
ba2str(&di.bdaddr, addr);
char *address = (char *)malloc(sizeof(char) * 64);
if (!address)
{
return NULL;
}
if(addr[0] != '\0')
{
strcpy(address, addr);
@ -298,15 +292,9 @@ char* kdk_bluetooth_get_link_mode(int id)
char *str = NULL;
int ctl;
static struct hci_dev_info di;
char *link_mode = (char *)malloc(sizeof(char) * 64);
if(!link_mode)
{
return NULL;
}
if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0)
{
free(link_mode);
return NULL;
}
@ -314,13 +302,17 @@ char* kdk_bluetooth_get_link_mode(int id)
if (ioctl(ctl, HCIGETDEVINFO, (void *)&di))
{
free(link_mode);
return NULL;
}
str = hci_lmtostr(di.link_mode);
char *link_mode = (char *)malloc(sizeof(char) * 64);
if(!link_mode)
{
return NULL;
}
if(str)
{
strcpy(link_mode, str);
strcpy(link_mode, str);
bt_free(str);
return link_mode;
}
@ -334,15 +326,9 @@ char* kdk_bluetooth_get_link_policy(int id)
{
int ctl;
static struct hci_dev_info di;
char *link_policy = (char *)malloc(sizeof(char) * 64);
if(!link_policy)
{
return NULL;
}
if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0)
{
free(link_policy);
return NULL;
}
@ -350,10 +336,14 @@ char* kdk_bluetooth_get_link_policy(int id)
if (ioctl(ctl, HCIGETDEVINFO, (void *)&di))
{
free(link_policy);
return NULL;
}
char *link_policy = (char *)malloc(sizeof(char) * 64);
if(!link_policy)
{
return NULL;
}
strcpy(link_policy, hci_lptostr(di.link_policy));
return link_policy;
}
@ -362,15 +352,9 @@ char* kdk_bluetooth_get_bus(int id)
{
int ctl;
static struct hci_dev_info di;
char *bus = (char *)malloc(sizeof(char) * 64);
if(!bus)
{
return NULL;
}
if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0)
{
free(bus);
return NULL;
}
@ -378,10 +362,14 @@ char* kdk_bluetooth_get_bus(int id)
if (ioctl(ctl, HCIGETDEVINFO, (void *)&di))
{
free(bus);
return NULL;
}
char *bus = (char *)malloc(sizeof(char) * 64);
if(!bus)
{
return NULL;
}
strcpy(bus, hci_bustostr(di.type & 0x0f));
return bus;
}
@ -392,15 +380,9 @@ char* kdk_bluetooth_get_scomtu(int id)
static struct hci_dev_info di;
char addr[18];
char tmp[20] = "\0";
char *scomtu = (char *)malloc(sizeof(char) * 64);
if(!scomtu)
{
return NULL;
}
if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0)
{
free(scomtu);
return NULL;
}
@ -408,12 +390,16 @@ char* kdk_bluetooth_get_scomtu(int id)
if (ioctl(ctl, HCIGETDEVINFO, (void *)&di))
{
free(scomtu);
return NULL;
}
ba2str(&di.bdaddr, addr);
sprintf(tmp, "%d:%d", di.sco_mtu, di.sco_pkts);
char *scomtu = (char *)malloc(sizeof(char) * 64);
if(!scomtu)
{
return NULL;
}
strcpy(scomtu, tmp);
return scomtu;
}
@ -454,13 +440,8 @@ char* kdk_bluetooth_get_packettype(int id)
int ctl;
static struct hci_dev_info di;
char *packettype = (char *)malloc(sizeof(char) * 64);
if(!packettype)
return NULL;
if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0)
{
free(packettype);
return NULL;
}
@ -468,10 +449,14 @@ char* kdk_bluetooth_get_packettype(int id)
if (ioctl(ctl, HCIGETDEVINFO, (void *)&di))
{
free(packettype);
return NULL;
}
str = hci_ptypetostr(di.pkt_type);
char *packettype = (char *)malloc(sizeof(char) * 64);
if(!packettype)
{
return NULL;
}
strcpy(packettype, str);
bt_free(str);
return packettype;

View File

@ -24,6 +24,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dbus-1.0/dbus/dbus.h>
const char *kdk_board_get_name()
{
@ -49,7 +50,7 @@ const char *kdk_board_get_date()
return date;
}
const char *kdk_board_get_serial()
const char *_kdk_board_get_serial()
{
char *serial = (char *)calloc(64,sizeof(char));
FILE *fd = fopen("/sys/class/dmi/id/board_serial","r");
@ -61,6 +62,111 @@ const char *kdk_board_get_serial()
return serial;
}
const char *kdk_board_get_serial()
{
char *ret = NULL;
DBusConnection *conn;
DBusError err;
dbus_error_init(&err);
conn = dbus_bus_get_private(DBUS_BUS_SYSTEM, &err);
if (NULL == conn)
{
ret = NULL;
}
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
DBusMessage *info_msg = NULL;
DBusPendingCall *sendMsgPending = NULL;
DBusMessage *replyMsg = NULL;
//创建用户
info_msg = dbus_message_new_method_call("com.kylin.kysdk.service", // target for the method call
"/com/kylin/kysdk/mainboard", // object to call on
"com.kylin.kysdk.mainboard", // interface to call on
"getMainboardSerial"); // method name
if (!info_msg)
{ // -1 is default timeout
ret = NULL;
}
// if (!dbus_message_append_args(info_msg, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &fullName, DBUS_TYPE_INT32, &accountType, DBUS_TYPE_INVALID))
// {
// klog_err("kdk : d-bus append args fail !\n");
// goto err_out;
// }
if (!dbus_connection_send_with_reply(conn, info_msg, &sendMsgPending, -1))
{
ret = NULL;
}
if (sendMsgPending == NULL)
{
ret = NULL;
}
dbus_connection_flush(conn);
if (info_msg)
{
dbus_message_unref(info_msg);
}
dbus_pending_call_block(sendMsgPending);
replyMsg = dbus_pending_call_steal_reply(sendMsgPending);
if (replyMsg == NULL)
{
ret = NULL;
}
if (sendMsgPending)
{
dbus_pending_call_unref(sendMsgPending);
}
DBusMessageIter args;
if (!dbus_message_iter_init(replyMsg, &args))
{
dbus_message_unref(replyMsg);
ret = NULL;
}
else
{
dbus_message_iter_get_basic(&args, &ret);
}
if (replyMsg)
{
dbus_message_unref(replyMsg);
}
dbus_connection_close(conn);
if(ret == NULL)
{
ret = _kdk_board_get_serial();
}
char *serial = NULL;
if(ret != NULL)
{
serial = (char *)malloc(sizeof(char) * 512);
if(!serial)
{
serial = NULL;
}
strcpy(serial, ret);
}
return serial;
}
const char *kdk_board_get_vendor()
{
char *vendor = (char *)calloc(64,sizeof(char));

View File

@ -29,6 +29,7 @@
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include "sys/sysinfo.h"
#include "unistd.h"
#ifdef __linux__
#include <sys/utsname.h>

File diff suppressed because it is too large Load Diff

View File

@ -44,77 +44,77 @@ extern "C"
/**
* @brief
*
* @return char* free
* @return char* NULL free
*/
extern char* kdk_display_get_vendor();
/**
* @brief
*
* @return char* free
* @return char* NULL free
*/
extern char* kdk_display_get_product();
/**
* @brief
*
* @return char* free
* @return char* NULL free
*/
extern char* kdk_display_get_description();
/**
* @brief id
*
* @return char* id free
* @return char* idNULL free
*/
extern char* kdk_display_get_physical_id();
/**
* @brief 线
*
* @return char* 线 free
* @return char* 线NULL free
*/
extern char* kdk_display_get_bus_info();
/**
* @brief
*
* @return char* free
* @return char* NULL free
*/
extern char* kdk_display_get_version();
/**
* @brief
*
* @return char* free
* @return char* NULL free
*/
extern char* kdk_display_get_width();
/**
* @brief
*
* @return char* free
* @return char* NULL free
*/
extern char* kdk_display_get_clock();
/**
* @brief
*
* @return char* free
* @return char* NULL free
*/
extern char* kdk_display_get_capabilities();
/**
* @brief
*
* @return char* free
* @return char* NULL free
*/
extern char* kdk_display_get_configuration();
/**
* @brief
*
* @return char* free
* @return char* NULL free
*/
extern char* kdk_display_get_resources();

View File

@ -65,7 +65,7 @@ static char* get_val_from_file(FILE *fp, const char *key)
return val;
}
static verify_file(char *pFileName)
static int verify_file(char *pFileName)
{
if(!strncmp(pFileName, "/sys", strlen("/sys")))
{
@ -80,19 +80,16 @@ static verify_file(char *pFileName)
}
}
char *cmd_exec(char *file)
static char *cmd_exec(char *file)
{
char *res = (char *)malloc(sizeof(char) * 128);
memset(res, 0, 128);
char *res = NULL;
int fd[2];
if (pipe(fd) == -1) {
free(res);
return NULL;
}
pid_t pid = fork();
if (pid == -1) {
free(res);
return NULL;
}
@ -113,6 +110,7 @@ char *cmd_exec(char *file)
const char* targetLine1 = "Display Product Name"; // 要匹配的目标行
const char* targetLine2 = "Alphanumeric Data String"; // 要匹配的目标行
res = (char *)malloc(sizeof(char) * 128);
FILE* fp = fdopen(fd[0], "r"); // 将读取端转换为文件指针
char *val = get_val_from_file(fp, targetLine1);
if(!val)
@ -123,10 +121,8 @@ char *cmd_exec(char *file)
free(res);
return NULL;
}
else{
strcpy(res, value);
free(value);
}
strcpy(res, value);
free(value);
}
else{
strcpy(res, val);
@ -136,13 +132,13 @@ char *cmd_exec(char *file)
fclose(fp); // 关闭文件指针
// 等待子进程退出并获取退出状态
int status;
waitpid(pid, &status, 0);
// int status;
// waitpid(pid, &status, 0);
}
return res;
}
void kdk_edid(char *name)
static void kdk_edid(char *name)
{
char edid_text[2048] = "\0";
char *edid_character = (char *)malloc(sizeof(char) * 1024);
@ -212,7 +208,7 @@ char **kdk_edid_get_interface()
char **res = NULL;
int count = 0;
char test[100] = {0};
disp = XOpenDisplay(0);
screen = XRRGetScreenResources(disp, DefaultRootWindow(disp));
for (iscres = screen->noutput; iscres > 0;)
@ -237,13 +233,13 @@ char **kdk_edid_get_interface()
--icrtc;
}
res = realloc(res, (count + 1) * sizeof(char *));
res = realloc(res, (count + 2) * sizeof(char *));
if (!res)
{
klog_err("内存申请失败:%s\n", strerror(errno));
goto err_out;
}
res[count] = malloc(512 * sizeof(char) + 1);
res[count] = calloc(strlen(tmp) + 1, sizeof(char));
if (!res[count])
{
klog_err("内存申请失败:%s\n", strerror(errno));
@ -252,10 +248,11 @@ char **kdk_edid_get_interface()
strcpy(res[count], tmp);
count++;
}
}
}
XRRFreeOutputInfo(info);
}
XRRFreeScreenResources(screen);
XCloseDisplay(disp);
res[count] = NULL;
goto out;
@ -660,49 +657,66 @@ float kdk_edid_get_size(char *name)
sprintf(path, "/sys/class/drm/%s/edid", direfd->d_name);
}
}
closedir(dirfd);
free(fg);
if (!realpath(path, canonical_filename) || !verify_file(canonical_filename) \
|| (fd = open(canonical_filename, O_RDONLY)) == -1)
{
// close(fd);
kdk_edid(name);
if (!realpath("/tmp/sdk-edid", filename) || !verify_file(filename))
{
closedir(dirfd);
return 0.00;
}
FILE *fs = fopen(filename, "r");
if(!fs)
{
closedir(dirfd);
return 0.00;
}
fclose(fs);
fp = popen("edid-decode /tmp/sdk-edid", "r");
if(!fp)
{
closedir(dirfd);
return 0.00;
}
}
else{
char repath[527] = "\0";
sprintf(repath, "edid-decode %s", path);
fp = popen(repath, "r");
if(!fp)
{
closedir(dirfd);
int fd_pipe[2];
if (pipe(fd_pipe) == -1) {
return 0.00;
}
pid_t pid = fork();
if (pid == -1) {
return 0.00;
}
if (pid == 0) {
close(fd_pipe[0]); // 关闭读取端
dup2(fd_pipe[1], STDOUT_FILENO); // 将管道写入端连接到标准输出
// 使用execve执行所需的命令例如
char* args[] = {"edid-decode", path, NULL};
execve("/bin/edid-decode", args, NULL);
// 如果execve执行失败需要打印错误信息并退出
perror("Failed to execute command");
exit(1);
} else {
close(fd_pipe[1]); // 关闭写入端
fp = fdopen(fd_pipe[0], "r"); // 将读取端转换为文件指针
if(!fp)
{
return 0.00;
}
}
}
char xsize[16] = "\0";
char ysize[16] = "\0";
char *tmp = get_val_from_file(fp, "Maximum image size");
if(!tmp)
{
printf("test\n");
closedir(dirfd);
pclose(fp);
return 0.00;
}
@ -724,21 +738,25 @@ float kdk_edid_get_size(char *name)
size = sqrt(pow(num1, 2) + pow(num2, 2)) / 2.54;
free(tmp);
}
closedir(dirfd);
pclose(fp);
char *model = kdk_edid_get_model(name);
if(!model)
{
return size;
}
// greatwall
if(!strcmp("24AL60", kdk_edid_get_model(name)))
if(!strcmp("24AL60", model))
{
size = 23.8;
}
// X100
if(!strcmp("LM133LF-8L02", kdk_edid_get_model(name)))
if(!strcmp("LM133LF-8L02", model))
{
size = 13.3;
}
free(model);
return size;
}
@ -791,7 +809,7 @@ char *kdk_edid_get_max_resolution(char *name)
}
/* extract a string from a detailed subblock, checking for termination */
char *extract_string(const unsigned char *x, unsigned len)
static char *extract_string(const unsigned char *x, unsigned len)
{
static char s[50];
int seen_newline = 0;
@ -836,7 +854,7 @@ char *extract_string(const unsigned char *x, unsigned len)
return s;
}
char *detailed_block(const unsigned char *x)
static char *detailed_block(const unsigned char *x)
{
static const unsigned char zero_descr[18] = {0};
@ -866,24 +884,16 @@ char *kdk_edid_get_model(char *name)
char canonical_filename[100] = "\0";
char filename[100] = "\0";
char *edid_text = NULL;
char *model = (char *) malloc(128 *sizeof(char));
if(!model)
{
return NULL;
}
memset(model, 0, 128);
char str_name[32] = "\0";
strcpy(str_name, name);
dirfd = opendir("/sys/class/drm");
if (!dirfd)
{
free(model);
return NULL;
}
char **fg = strsplit(str_name, '-');
if (!fg)
{
free(model);
closedir(dirfd);
return NULL;
}
@ -897,54 +907,49 @@ char *kdk_edid_get_model(char *name)
}
free(fg);
closedir(dirfd);
if (!realpath(path, canonical_filename) || !verify_file(canonical_filename) \
|| (fd = open(canonical_filename, O_RDONLY)) == -1)
{
kdk_edid(name);
if (!realpath("/tmp/sdk-edid", filename) || !verify_file(filename))
{
free(model);
return NULL;
goto err_out;
}
FILE *fs = fopen(filename, "r");
if(!fs)
{
free(model);
return NULL;
goto err_out;
}
fclose(fs);
FILE *fp = popen("edid-decode /tmp/sdk-edid", "r");
if(!fp)
{
free(model);
return NULL;
goto err_out;
}
edid_text = get_val_from_file(fp, "Display Product Name");
if(!edid_text)
{
fp = popen("edid-decode /tmp/sdk-edid", "r");
if(!fp)
{
goto err_out;
}
char *str_model = get_val_from_file(fp, "Alphanumeric Data String");
if(!str_model)
{
free(edid_text);
goto err_out;
}
else{
strcpy(model, str_model);
}
free(str_model);
pclose(fp);
strstripspace(str_model);
return str_model;
}
else{
strcpy(model, edid_text);
pclose(fp);
strstripspace(edid_text);
return edid_text;
}
free(edid_text);
if(strlen(model) == 0)
{
goto err_out;
}
strstripspace(model);
pclose(fp);
return model;
}
char *cmd_val = cmd_exec(path);
@ -971,27 +976,24 @@ char *kdk_edid_get_model(char *name)
strcpy(src_model, hd->model);
}
}
free(hd_data);
hd_free_hd_data(hd_data);
hd_free_hd_list(hd0);
if(strlen(src_model) == 0)
{
goto err_out;
}
else{
char *model = (char *)malloc(sizeof(char) * 128);
strcpy(model, src_model);
return model;
}
}
else{
strcpy(model, cmd_val);
free(cmd_val);
strstripspace(cmd_val);
return cmd_val;
}
if(strlen(model) == 0)
{
goto err_out;
}
strstripspace(model);
return model;
err_out:
free(model);
return NULL;
}
@ -1007,29 +1009,22 @@ char *kdk_edid_get_visible_area(char *name)
DIR *dirfd = NULL;
struct dirent *direfd = NULL;
char canonical_filename[100] = "\0";
char tmp[20] = "\0";
char filename[100] = "\0";
// char edid_text[24] = "\0";
char str_name[32] = "\0";
strcpy(str_name, name);
char *area = (char *)malloc(sizeof(char) * 32);
if (!area)
{
klog_err("内存申请失败:%s\n", strerror(errno));
return NULL;
}
FILE *fp = NULL;
float num1 = 0.0;
float num2 = 0.0;
dirfd = opendir("/sys/class/drm");
if (!dirfd)
{
free(area);
return NULL;
}
char **fg = strsplit(str_name, '-');
if (!fg)
{
free(area);
closedir(dirfd);
return NULL;
}
@ -1042,98 +1037,94 @@ char *kdk_edid_get_visible_area(char *name)
}
}
free(fg);
closedir(dirfd);
if (!realpath(path, canonical_filename) || !verify_file(canonical_filename) \
|| (fd = open(canonical_filename, O_RDONLY)) == -1)
|| (fd = open(canonical_filename, O_RDONLY)) == -1)
{
// close(fd);
kdk_edid(name);
if (!realpath("/tmp/sdk-edid", filename) || !verify_file(filename))
{
closedir(dirfd);
free(area);
return NULL;
}
FILE *fs = fopen(filename, "r");
if(!fs)
{
closedir(dirfd);
free(area);
return NULL;
}
fclose(fs);
FILE *fp = popen("edid-decode /tmp/sdk-edid", "r");
fp = popen("edid-decode /tmp/sdk-edid", "r");
if(!fp)
{
closedir(dirfd);
free(area);
return NULL;
}
char *msize = get_val_from_file(fp, "Maximum image size");
if(!msize)
{
closedir(dirfd);
pclose(fp);
free(area);
}
else{
int fd_pipe[2];
if (pipe(fd_pipe) == -1) {
return NULL;
}
char *buf[3];
int i = 0;
char *p = strtok(msize, "x");
while (p)
{
buf[i] = p;
i++;
p = strtok(NULL, "x");
}
char fs1[12] = "\0";
char fs2[12] = "\0";
strcpy(fs1, buf[0]);
strcpy(fs2, buf[1]);
strskipspace(fs1);
strskipspace(fs2);
int num1 = 0;
int num2 = 0;
sscanf(fs1, "%d", &num1);
sscanf(fs2, "%d", &num2);
sprintf(tmp, "%u X %u cm", num1, num2);
strcpy(area, tmp);
closedir(dirfd);
pid_t pid = fork();
if (pid == -1) {
return NULL;
}
if (pid == 0) {
close(fd_pipe[0]); // 关闭读取端
dup2(fd_pipe[1], STDOUT_FILENO); // 将管道写入端连接到标准输出
// 使用execve执行所需的命令例如
char* args[] = {"edid-decode", path, NULL};
execve("/bin/edid-decode", args, NULL);
// 如果execve执行失败需要打印错误信息并退出
perror("Failed to execute command");
exit(1);
} else {
close(fd_pipe[1]); // 关闭写入端
fp = fdopen(fd_pipe[0], "r"); // 将读取端转换为文件指针
if(!fp)
{
return NULL;
}
}
}
char xsize[16] = "\0";
char ysize[16] = "\0";
char *tmp = get_val_from_file(fp, "Maximum image size");
if(!tmp)
{
pclose(fp);
return NULL;
}
char *area = (char *)malloc(sizeof(char) * 32);
if (!area)
{
klog_err("内存申请失败:%s\n", strerror(errno));
pclose(fp);
return NULL;
}
char *msize = get_val_from_file(fp, "Detailed mode");
if(msize)
{
sscanf(msize, "%*s %*s %*s %s %*s %*s %s", xsize, ysize);
num1 = atoi(xsize);
num2 = atoi(ysize);
sprintf(area, "%0.1f X %0.1f mm", num1, num2);
free(msize);
return area;
free(tmp);
}
edid = extract_edid(fd);
if (!edid)
else if(tmp)
{
goto err_out;
sscanf(tmp, "%s %*s %*s %s", xsize, ysize);
num1 = atoi(xsize);
num2 = atoi(ysize);
sprintf(area, "%0.1f X %0.1f cm", num1, num2);
free(tmp);
}
if (!edid || memcmp(edid, "\x00\xFF\xFF\xFF\xFF\xFF\xFF\x00", 8))
{
goto err_out;
}
close(fd);
closedir(dirfd);
if (edid[0x15] && edid[0x16])
{
sprintf(tmp, "%u X %u cm", edid[0x15], edid[0x16]);
}
strcpy(area, tmp);
free(edid);
pclose(fp);
return area;
err_out:
free(area);
close(fd);
closedir(dirfd);
if(edid)
{
free(edid);
}
return NULL;
}
static char *manufacturer_name(const unsigned char *x)
@ -1543,10 +1534,12 @@ int kdk_edid_get_primary(char *name)
return -1;
}
int primary = 0;
Display *display = XOpenDisplay(NULL);
if (!display)
{
return -1;
primary = -1;
goto out;
}
Window root = DefaultRootWindow(display);
@ -1580,6 +1573,7 @@ int kdk_edid_get_primary(char *name)
XRRFreeScreenResources(screen);
XCloseDisplay(display);
out:
return primary;
}
@ -1595,13 +1589,8 @@ char *kdk_edid_get_resolution(char *name)
XRRCrtcInfo *crtc_info;
int iscres;
int icrtc;
char tmp[20];
char *resolution = (char *)malloc(sizeof(char) * 20);
if(!resolution)
{
return NULL;
}
memset(resolution, 0, 20);
char *resolution = NULL;
char tmp[128];
disp = XOpenDisplay(0);
screen = XRRGetScreenResources(disp, DefaultRootWindow(disp));
@ -1622,21 +1611,34 @@ char *kdk_edid_get_resolution(char *name)
if (strstr(info->name, name))
{
sprintf(tmp, "%dx%d", crtc_info->width, crtc_info->height);
resolution = (char *)calloc(strlen(tmp) + 1, sizeof(char));
if (!resolution)
{
XRRFreeCrtcInfo(crtc_info);
goto err_out;
}
strcpy(resolution, tmp);
}
XRRFreeCrtcInfo(crtc_info);
}
XRRFreeCrtcInfo(crtc_info);
}
}
XRRFreeOutputInfo(info);
}
XRRFreeScreenResources(screen);
XCloseDisplay(disp);
if(strlen(resolution) == 0)
{
free(resolution);
return NULL;
}
return resolution;
err_out:
XRRFreeOutputInfo(info);
XRRFreeScreenResources(screen);
XCloseDisplay(disp);
return NULL;
}
char* kdk_edid_get_ratio(char *name)
@ -1686,13 +1688,15 @@ char* kdk_edid_get_ratio(char *name)
else if (ret == 177)
strcpy(tmp, "16:9");
}
XRRFreeCrtcInfo(crtc_info);
}
XRRFreeCrtcInfo(crtc_info);
}
}
XRRFreeOutputInfo(info);
}
XRRFreeScreenResources(screen);
XCloseDisplay(disp);
if(tmp[0] == "\0")
{
free(ratio);

View File

@ -57,36 +57,32 @@ static char* print_chip_fan(const sensors_chip_name *name,
const sensors_subfeature *sf;
double val;
char *label;
char tmp[20] = "\0";
char *fan = (char *)malloc(sizeof(char) * 64);
if(!fan)
{
return NULL;
}
char tmp[64] = "\0";
if (!(label = sensors_get_label(name, feature)))
{
free(fan);
return NULL;
}
char *ret = print_label(label, label_size);
free(label);
sf = sensors_get_subfeature(name, feature,
SENSORS_SUBFEATURE_FAN_FAULT);
sf = sensors_get_subfeature(name, feature,
SENSORS_SUBFEATURE_FAN_INPUT);
sf = sensors_get_subfeature(name, feature, SENSORS_SUBFEATURE_FAN_FAULT);
sf = sensors_get_subfeature(name, feature, SENSORS_SUBFEATURE_FAN_INPUT);
if (sf && get_input_value(name, sf, &val) == 0)
{
sprintf(tmp, "%s%4.0f RPM", ret, val);
free(ret);
char *fan = (char *)malloc(strlen(tmp) + 1);
if(!fan)
{
return NULL;
}
strcpy(fan, tmp);
return fan;
}
else
{
free(ret);
free(fan);
return NULL;
}
}
@ -101,8 +97,7 @@ static int get_label_size(const sensors_chip_name *name)
i = 0;
while ((iter = sensors_get_features(name, &i)))
{
if ((label = sensors_get_label(name, iter)) &&
strlen(label) > max_size)
if ((label = sensors_get_label(name, iter)) && strlen(label) > max_size)
max_size = strlen(label);
free(label);
}
@ -115,34 +110,42 @@ static int get_label_size(const sensors_chip_name *name)
char** print_chip(const sensors_chip_name *name)
{
const sensors_feature *feature;
int i, label_size;
int label_size;
char *ret = NULL;
char **fan = NULL;
fan = realloc(fan, sizeof(char *) * 50);
label_size = get_label_size(name);
i = 0;
int j = 0;
while ((feature = sensors_get_features(name, &i)))
int nr = 0;
int count = 0;
while ((feature = sensors_get_features(name, &nr)))
count++;
nr = 0;
while ((feature = sensors_get_features(name, &nr)))
{
switch (feature->type)
{
case SENSORS_FEATURE_FAN:
{
fan = calloc(count + 1, sizeof(char *));
if (NULL == fan)
goto out;
ret = print_chip_fan(name, feature, label_size);
fan[j] = malloc(sizeof(char) * 20);
if(!ret)
{
continue;
}
strcpy(fan[j], ret);
j++;
fan[j++] = ret;
}
break;
default:
continue;
}
}
fan[j] = NULL;
out:
return fan;
}
@ -185,48 +188,17 @@ char** kdk_fan_get_information()
const sensors_chip_name *match = NULL;
const sensors_chip_name *chip;
int chip_nr;
int cnt = 0;
chip_nr = 0;
int index = 0;
char **fan = NULL;
char **res = NULL;
char **tmp = realloc(res, sizeof(char) * 50);
if(!tmp)
{
return NULL;
}
res = tmp;
int j = 0;
int chip_nr = 0;
while ((chip = sensors_get_detected_chips(match, &chip_nr)))
{
int i = 0;
fan = print_chip(chip);
while(fan && fan[i])
{
res[i] = malloc(sizeof(char) * 32);
if(!res[i])
{
free(tmp);
goto err_out;
}
sprintf(res[i], "%s", fan[i]);
i++;
j = i;
}
cnt++;
}
res[j] = NULL;
if(fan)
{
while (fan[index])
{
free(fan[index]);
index ++;
}
free(fan);
}
return res;
sensors_cleanup();
return fan;
err_out:
while (fan[index])
{

View File

@ -163,7 +163,7 @@ struct HWInfo *kdk_hw_get_hwinfo(int type)
if (!hd_data)
{
klog_err("%s 申请内存失败于%s", "kdk_hw_get_sound", "hd_data");
goto out;
return result;
}
hd_data->progress = NULL;
@ -277,6 +277,7 @@ struct HWInfo *kdk_hw_get_hwinfo(int type)
}
out:
hd_free_hd_data(hd_data);
free(hd_data);
hd_free_hd_list(hd0);
return result;
}
@ -312,7 +313,7 @@ static void _write_info(struct power_device *node, GHashTable *info_hash)
attr = (GValue *)g_hash_table_lookup(info_hash, "HasStatistics");
node->has_statistics = attr ? g_value_get_boolean(attr) : false;
attr = (GValue *)g_hash_table_lookup(info_hash, "IsPersent");
attr = (GValue *)g_hash_table_lookup(info_hash, "IsPresent");
node->is_persent = attr ? g_value_get_boolean(attr) : false;
attr = (GValue *)g_hash_table_lookup(info_hash, "IsRechargeable");
@ -322,25 +323,25 @@ static void _write_info(struct power_device *node, GHashTable *info_hash)
switch (g_value_get_uint(attr))
{
case 1:
strcpy(node->technology, "charging");
strcpy(node->state, "charging");
break;
case 2:
strcpy(node->technology, "discharging");
strcpy(node->state, "discharging");
break;
case 3:
strcpy(node->technology, "empty");
strcpy(node->state, "empty");
break;
case 4:
strcpy(node->technology, "fully-charged");
strcpy(node->state, "fully-charged");
break;
case 5:
strcpy(node->technology, "pending-charge");
strcpy(node->state, "pending-charge");
break;
case 6:
strcpy(node->technology, "pending-discharge");
strcpy(node->state, "pending-discharge");
break;
default:
strcpy(node->technology, "unknown");
strcpy(node->state, "unknown");
break;
}
@ -348,31 +349,31 @@ static void _write_info(struct power_device *node, GHashTable *info_hash)
switch (g_value_get_uint(attr))
{
case 1:
strcpy(node->technology, "none");
strcpy(node->warning_level, "none");
break;
case 2:
strcpy(node->technology, "discharging");
strcpy(node->warning_level, "discharging");
break;
case 3:
strcpy(node->technology, "low");
strcpy(node->warning_level, "low");
break;
case 4:
strcpy(node->technology, "critical");
strcpy(node->warning_level, "critical");
break;
case 5:
strcpy(node->technology, "action");
strcpy(node->warning_level, "action");
break;
case 6:
strcpy(node->technology, "normal");
strcpy(node->warning_level, "normal");
break;
case 7:
strcpy(node->technology, "high");
strcpy(node->warning_level, "high");
break;
case 8:
strcpy(node->technology, "full");
strcpy(node->warning_level, "full");
break;
default:
strcpy(node->technology, "unknown");
strcpy(node->warning_level, "unknown");
break;
}
@ -401,13 +402,13 @@ static void _write_info(struct power_device *node, GHashTable *info_hash)
node->time_to_full = attr ? g_value_get_int64(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "Percentage");
node->time_to_full = attr ? g_value_get_double(attr) : 0.0f;
node->percentage = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "Temperature");
node->time_to_full = attr ? g_value_get_double(attr) : 0.0f;
node->temperature = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "Capacity");
node->time_to_full = attr ? g_value_get_double(attr) : 0.0f;
node->capacity = attr ? g_value_get_double(attr) : 0.0f;
attr = (GValue *)g_hash_table_lookup(info_hash, "Technology");
switch (g_value_get_uint(attr))
@ -440,6 +441,15 @@ static void _write_info(struct power_device *node, GHashTable *info_hash)
attr = (GValue *)g_hash_table_lookup(info_hash, "IconName");
strcpy(node->icon_name, attr ? g_value_get_string(attr) : "None");
attr = (GValue *)g_hash_table_lookup(info_hash, "Model");
strcpy(node->model, attr ? g_value_get_string(attr) : "None");
attr = (GValue *)g_hash_table_lookup(info_hash, "BatteryLevel");
node->battery_level = g_value_get_uint(attr);
attr = (GValue *)g_hash_table_lookup(info_hash, "Type");
node->type = g_value_get_uint(attr);
}
static void _daemon_forech(gpointer key, gpointer value, gpointer user_data)
@ -452,9 +462,9 @@ static void _daemon_forech(gpointer key, gpointer value, gpointer user_data)
if (0 == strcmp(tmp, "LidIsClosed"))
result->lid_is_closed = g_value_get_boolean(data);
if (0 == strcmp(tmp, "LidIsPresent"))
result->lid_is_closed = g_value_get_boolean(data);
result->lid_is_present = g_value_get_boolean(data);
if (0 == strcmp(tmp, "OnBattery"))
result->lid_is_closed = g_value_get_boolean(data);
result->on_battery = g_value_get_boolean(data);
}
static bool get_daemon_info(DBusGConnection *bus, GError **error, struct Power *result, DBusGProxy **upower_proxy)
@ -636,6 +646,7 @@ struct Power *kdk_hw_get_powerinfo()
if (!result)
{
klog_err("Failed to request memory Power");
dbus_g_connection_unref(bus);
return NULL;
}

View File

@ -53,54 +53,57 @@ extern "C"
struct HWInfo
{
char model[ATTRSIZE];
char vendor[ATTRSIZE];
char device[ATTRSIZE];
char driver[ATTRSIZE];
char revision[ATTRSIZE];
char busid[ATTRSIZE];
char devicenum[ATTRSIZE];
char width[8];
char clock[8];
char model[ATTRSIZE]; //模块名
char vendor[ATTRSIZE]; //厂商名
char device[ATTRSIZE]; //设备名
char driver[ATTRSIZE]; //设备驱动
char revision[ATTRSIZE]; //版本
char busid[ATTRSIZE]; //总线id
char devicenum[ATTRSIZE]; //设备号,例如鼠标键盘的字符设备号,块设备(光驱)的设备号
char width[8]; //声卡数据位宽
char clock[8]; //声卡时钟频率
struct HWInfo *next;
};
struct power_device
{
char name[256];
char native_path[32];
bool power_supply;
char updated[64];
bool has_history;
bool has_statistics;
bool is_persent;
bool is_rechargeable;
char state[32];
char warning_level[32];
double energy;
double energy_empty;
double energy_full;
double energy_full_design;
double energy_rate;
double voltage;
long time_to_empty;
long time_to_full;
double percentage;
double temperature;
double capacity;
char technology[32];
bool online;
char icon_name[64];
char name[256]; //设备名
char native_path[32]; //电源设备的本机路径
bool power_supply; //显示 "true" 表示这是一个电源设备,如电池或充电器
char updated[64]; //上次更新信息的时间戳
bool has_history; //显示 "true" 表示设备有历史信息,即充电和放电的历史记录
bool has_statistics; //显示 "true" 表示设备有统计信息,例如充电次数、使用时间等。
bool is_persent; //显示 "true" 表示电池存在
bool is_rechargeable; //显示 "true" 表示电池可充电
char state[32]; //电池的当前状态,例如 "charging"、"discharging"、"fully-charged" 等
char warning_level[32]; //电池电量低于该级别时会触发警告,
double energy; //电池的能量信息,包括当前能量、满电能量等
double energy_empty; //电池耗尽时的能量
double energy_full; //电池充满时的能量
double energy_full_design; //电池的设计容量
double energy_rate; //电池的当前充电或放电速率
double voltage; //电池的当前电压
long time_to_empty; //电池完全放空(耗尽)所需的时间
long time_to_full; //电池完全充满所需的时间
double percentage; //电池的电量百分比(电池当前的电量相对于满电容量的百分比)
double temperature; //电池的当前温度
double capacity; //电池的电量百分比(电池当前充电状态相对于满电的百分比)
char technology[32]; //电池所使用的技术
bool online; //显示 "true" 表示设备当前在线(连接到电源)
char icon_name[64]; //显示与设备状态相关联的图标名称
char model[64]; //电池型号
int battery_level; //电池电量等级
int type; //充电类型
struct power_device *next;
};
struct Power
{
char daemon_version[32];
bool on_battery;
bool lid_is_closed;
bool lid_is_present;
char critical_action[32];
char daemon_version[32]; //版本
bool on_battery; //系统当前是否依赖电池供电。如果值为'true',则表示系统正在使用电池供电;如果值为'false',则表示系统连接到外部电源
bool lid_is_closed; //设备的盖子(例如笔记本电脑的盖子)是否关闭。如果值为'true',则表示盖子已关闭;如果值为'false',则表示盖子处于打开状态
bool lid_is_present; //设备是否具有可关闭的盖子。如果值为'true',则表示设备具有可关闭的盖子;如果值为'false',则表示设备没有可关闭的盖子
char critical_action[32]; //电池电量低于临界水平时系统采取的动作的方法
struct power_device *devices;
};

View File

@ -44,27 +44,32 @@
#include <linux/ethtool.h>
#include <net/if_arp.h>
#include <linux/wireless.h>
#include <libnl3/netlink/netlink.h>
#include <libnl3/netlink/genl/genl.h>
#include <libnl3/netlink/genl/ctrl.h>
#include <libnl3/netlink/route/link.h>
#include <libnl3/netlink/route/addr.h>
#include <libnl3/netlink/addr.h>
#include <libnl3/netlink/types.h>
#include <libnl3/netlink/route/route.h>
#include <libnl3/netlink/netlink.h>
enum cardspec{
enum cardspec
{
NCSPEC_ALL,
NCSPEC_UP,
NCSPEC_DOWN
};
enum cardstat{
enum cardstat
{
NCSTAT_LINK_UP,
NCSTAT_LINK_DOWN,
NCSTAT_ERROR
};
enum cardcfg{
enum cardcfg
{
NCCFG_MAC,
NCCFG_IPv4,
NCCFG_IPv6,
@ -72,9 +77,9 @@ enum cardcfg{
NCCFG_IPv6_MASK
};
#define NC_IPv4_SIZE 16
#define NC_MAC_SIZE 18
#define SIOCGIWNAME 0x8B01
#define NC_IPv4_SIZE 16
#define NC_MAC_SIZE 18
#define SIOCGIWNAME 0x8B01
#define PCIID_PATH "/usr/share/misc/pci.ids"
struct get_ipv4_addr_ctx_t {
@ -131,12 +136,11 @@ configure_read_string(GKeyFile *keyfile, GString *ret, gchar *sec, gchar *key, g
}
static char **
get_ip_list(enum cardcfg type,const char *nc)
get_ip_list(enum cardcfg type, const char *nc)
{
int count = 0;
char curAddr[64] = "\0";
char *curAddr = NULL;
char **result = NULL;
char **res = NULL;
DIR *dir = NULL;
struct dirent *file;
char *path = "/etc/NetworkManager/system-connections/";
@ -144,14 +148,12 @@ get_ip_list(enum cardcfg type,const char *nc)
if (type == NCCFG_IPv4)
{
value = "ipv4";
if (kdk_nc_get_private_ipv4(nc))
strcpy(curAddr, kdk_nc_get_private_ipv4(nc));
curAddr = kdk_nc_get_private_ipv4(nc);
}
else if(type == NCCFG_IPv6)
else if (type == NCCFG_IPv6)
{
value = "ipv6";
if (kdk_nc_get_private_ipv6(nc))
strcpy(curAddr, kdk_nc_get_private_ipv6(nc));
curAddr = kdk_nc_get_private_ipv6(nc);
}
else
value = NULL;
@ -159,19 +161,18 @@ get_ip_list(enum cardcfg type,const char *nc)
if ((dir = opendir(path)) == NULL)
{
klog_err("opendir %s failed!", dir);
free(curAddr);
return NULL;
}
//网卡当前地址加入返回列表
if (curAddr && strcmp(curAddr,""))
// 网卡当前地址加入返回列表
if (NULL != curAddr)
{
result = (char **)calloc(++count + 1, sizeof(char *));
if(!result)
result = (char **)calloc(count + 2, sizeof(char *));
if (!result)
goto err_out;
result[count - 1] = (char *)calloc(strlen(curAddr) + 1, sizeof(char));
if(!result[count - 1])
goto err_out;
strncpy(result[count - 1], curAddr, strlen(curAddr));
result[count++] = curAddr;
curAddr = NULL;
}
while (file = readdir(dir))
@ -196,52 +197,48 @@ get_ip_list(enum cardcfg type,const char *nc)
if (0 == strcmp(val->str, nc))
{
//这种实现方式一个网卡只能取到9个ip 因为ascii码只有1-9
char num = '1';
while (1)
configure_read_string(keyFile, val, value, "address1", "null");
if (0 != strcmp(val->str, "null"))
{
char key[16];
memset(key,0,16);
strncpy(key,"address",7);
key[7] = num++;
configure_read_string(keyFile, val, value, key, "null");
if (0 != strcmp(val->str, "null"))
int i = -1;
while (val->str[++i] != 0x2f) // 0x2f是'/'的ascii码值
continue;
val->str[i] = '\0';
if (0 != strcmp(result[0], val->str))
{
int i = -1;
while (val->str[++i] != 0x2f)
; // 0x2f是'/'的ascii码值
val->str[i] = '\0';
if (0 != strcmp(curAddr, val->str))
char **tmp = (char **)realloc(result, (count + 2) * sizeof(char *));
if (!tmp)
{
res = (char **)realloc(result, (++count + 1) * sizeof(char *));
if (!res)
goto err_out;
result = res;
result[count - 1] = (char *)calloc(i + 1, sizeof(char));
if (!result[count - 1])
goto err_out;
strncpy(result[count - 1], val->str, i);
result[count] = NULL;
for (int i = 0; result[i]; i++)
free(result[i]);
free(result);
goto err_out;
}
result = tmp;
result[count++] = strndup(val->str, i);
result[count] = NULL;
}
else
break;
}
}
g_string_free(val,TRUE);
g_string_free(val, TRUE);
g_key_file_free(keyFile);
}
closedir(dir);
return result;
err_out:
while (result && count)
if (result)
{
free(result[count - 1]);
result[count - 1] = NULL;
while (count)
{
free(result[--count]);
}
free(result);
result = NULL;
}
free(result);
closedir(dir);
return NULL;
return result;
}
static enum cardstat _get_card_stat(const char *nc)
@ -259,7 +256,7 @@ static enum cardstat _get_card_stat(const char *nc)
if (ioctl(sfd, SIOCGIFFLAGS, &stIf) < 0)
{
klog_err("网卡[%s]状态获取失败:%s\n", nc, strerror(errno));
close (sfd);
close(sfd);
return NCSTAT_ERROR;
}
@ -275,7 +272,7 @@ static char **_get_cardlist(enum cardspec spec)
char **cards = NULL;
size_t cardnum = 0;
#ifdef __linux__
FILE* fp = fopen("/proc/net/dev", "r");
FILE *fp = fopen("/proc/net/dev", "r");
ASSERT_NOT_NULL(fp, NULL);
char buffer[1024];
while (fgets(buffer, 1024, fp))
@ -297,8 +294,8 @@ static char **_get_cardlist(enum cardspec spec)
if (_get_card_stat(buffer) != NCSTAT_LINK_DOWN)
continue;
}
cardnum ++;
char **tmp = realloc(cards, sizeof(char*) * cardnum);
cardnum++;
char **tmp = realloc(cards, sizeof(char *) * cardnum);
if (!tmp)
{
klog_err("内存申请失败:%s\n", strerror(errno));
@ -324,7 +321,7 @@ static char **_get_cardlist(enum cardspec spec)
cards = tmp;
cards[cardnum] = NULL;
goto out;
#endif // __linux__
#endif // __linux__
err_out:
#ifdef __linux__
fclose(fp);
@ -355,14 +352,15 @@ char **_get_nc_cfg(const char *nc, enum cardcfg cfg)
switch (cfg)
{
case NCCFG_MAC:{
case NCCFG_MAC:
{
if (ioctl(sfd, SIOCGIFHWADDR, &stIf) < 0)
{
klog_err("网卡[%s]MAC获取失败%s\n", nc, strerror(errno));
close(sfd);
return NULL;
}
res = malloc(sizeof(char*));
res = malloc(sizeof(char *));
if (!res)
{
klog_err("内存申请失败:%s\n", strerror(errno));
@ -378,28 +376,30 @@ char **_get_nc_cfg(const char *nc, enum cardcfg cfg)
return NULL;
}
snprintf(res[0], NC_MAC_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x",
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[0],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[1],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[2],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[3],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[4],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[5]);
}break;
case NCCFG_IPv4:{
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[0],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[1],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[2],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[3],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[4],
(unsigned char)stIf.ifr_ifru.ifru_hwaddr.sa_data[5]);
}
break;
case NCCFG_IPv4:
{
if (ioctl(sfd, SIOCGIFADDR, &stIf) < 0)
{
klog_err("网卡[%s]IPv4获取失败%s\n", nc, strerror(errno));
close(sfd);
return NULL;
}
res = malloc(sizeof(char*));
res = malloc(sizeof(char *));
if (!res)
{
klog_err("内存申请失败:%s\n", strerror(errno));
close(sfd);
return NULL;
}
res[0] = malloc(sizeof(char) * NC_IPv4_SIZE);
res[0] = malloc(NC_IPv4_SIZE * sizeof(char));
if (!res[0])
{
free(res);
@ -410,8 +410,10 @@ char **_get_nc_cfg(const char *nc, enum cardcfg cfg)
struct sockaddr_in sin;
memcpy(&sin, &stIf.ifr_ifru.ifru_addr, sizeof(sin));
snprintf(res[0], NC_IPv4_SIZE, "%s", inet_ntoa(sin.sin_addr));
}break;
case NCCFG_IPv6:{
}
break;
case NCCFG_IPv6:
{
struct ifaddrs *ifap, *ifa;
struct sockaddr_in6 *sa;
char addr[INET6_ADDRSTRLEN] = {0};
@ -426,7 +428,7 @@ char **_get_nc_cfg(const char *nc, enum cardcfg cfg)
}
}
res = malloc(sizeof(char*));
res = malloc(sizeof(char *));
if (!res)
{
klog_err("内存申请失败:%s\n", strerror(errno));
@ -448,11 +450,12 @@ char **_get_nc_cfg(const char *nc, enum cardcfg cfg)
while (addr[i] != '%' && addr[i] != '\0')
i++;
addr[i] = '\0';
sprintf(res[0], "%s",addr);
sprintf(res[0], "%s", addr);
freeifaddrs(ifap);
}break;
}
break;
default:
break;
}
@ -460,7 +463,7 @@ char **_get_nc_cfg(const char *nc, enum cardcfg cfg)
return res;
}
char** kdk_nc_get_cardlist()
char **kdk_nc_get_cardlist()
{
return _get_cardlist(NCSPEC_ALL);
}
@ -477,16 +480,16 @@ int kdk_nc_is_up(const char *nc)
return -1;
}
char** kdk_nc_get_upcards()
char **kdk_nc_get_upcards()
{
return _get_cardlist(NCSPEC_UP);
}
char* kdk_nc_get_phymac(const char *nc)
char *kdk_nc_get_phymac(const char *nc)
{
if (!nc)
return NULL;
char **maclist = _get_nc_cfg(nc, NCCFG_MAC);
if (!maclist)
return NULL;
@ -495,11 +498,11 @@ char* kdk_nc_get_phymac(const char *nc)
return mac;
}
char* kdk_nc_get_private_ipv4(const char *nc)
char *kdk_nc_get_private_ipv4(const char *nc)
{
if (!nc)
return NULL;
char **ipv4list = _get_nc_cfg(nc, NCCFG_IPv4);
if (!ipv4list)
return NULL;
@ -510,12 +513,12 @@ char* kdk_nc_get_private_ipv4(const char *nc)
char **kdk_nc_get_ipv4(const char *nc)
{
if(!nc)
if (!nc)
return NULL;
return get_ip_list(NCCFG_IPv4, nc);
return get_ip_list(NCCFG_IPv4, nc);
}
char* kdk_nc_get_private_ipv6(const char *nc)
char *kdk_nc_get_private_ipv6(const char *nc)
{
if (!nc)
return NULL;
@ -541,11 +544,11 @@ int kdk_nc_is_wireless(const char *nc)
return -1;
int i = 0, ret = -1;
char **list = kdk_nc_get_cardlist();
if(!list)
if (!list)
goto out;
while(list[i])
while (list[i])
{
if(0 == strcmp(nc, list[i++]))
if (0 == strcmp(nc, list[i++]))
{
char buffer[2 * IFNAMSIZ + 1];
int fd = socket(PF_INET, SOCK_DGRAM, 0);
@ -563,17 +566,17 @@ out:
return ret;
}
//根据mac地址获取从hwinfo --usb中获取指定网卡的vendor和device
static int __hwinfo_usb(const char * mac,char * vendor, char *product)
// 根据mac地址获取从hwinfo --usb中获取指定网卡的vendor和device
static int __hwinfo_usb(const char *mac, char *vendor, char *product)
{
FILE * fp = popen("hwinfo --usb","r");
if(!fp)
FILE *fp = popen("hwinfo --usb", "r");
if (!fp)
return -1;
char line[1024] = "\0";
char ven[256] = "\0";
char pro[256] = "\0";
int flags = 0;
while(fgets(line,1024,fp))
while (fgets(line, 1024, fp))
{
int index = 0;
if (flags && (0 < strlen(ven)) && (0 < strlen(pro)))
@ -585,10 +588,10 @@ static int __hwinfo_usb(const char * mac,char * vendor, char *product)
{
flags = 1;
}
if(strstr(line, "Vendor:"))
if (strstr(line, "Vendor:"))
{
// 返回数据为Vendor: usb 0xxxxx "Linux Foundation",取最后双引号中的内容
// 返回数据为Vendor: usb 0xxxxx "Linux Foundation",取最后双引号中的内容
strcpy(ven, &line[22]);
}
@ -598,13 +601,13 @@ static int __hwinfo_usb(const char * mac,char * vendor, char *product)
strcpy(pro, &line[22]);
}
if(0 < sscanf(line,"%d:%*s",&index))
if (0 < sscanf(line, "%d:%*s", &index))
{
memset(ven,0,256);
memset(pro,0,256);
memset(ven, 0, 256);
memset(pro, 0, 256);
}
}
if(flags)
if (flags)
{
strncpy(vendor, ven, strlen(ven) - 2);
strncpy(product, pro, strlen(pro) - 2);
@ -620,14 +623,13 @@ int kdk_nc_get_vendor_and_product(const char *nc, char *vendor, char *product)
char filename[64] = "0";
sprintf(filename, "/sys/class/net/%s/device", nc);
if (0 != access(filename, F_OK))
return -1; //非物理网卡,可能是逻辑网卡如 lo: 本地环回
return -1; // 非物理网卡,可能是逻辑网卡如 lo: 本地环回
FILE *fp = NULL;
//usb网卡通过hwinfo获取
// usb网卡通过hwinfo获取
char ncType[64] = "\0";
sprintf(ncType, "%s/%s", filename, "uevent");
if(NULL != (fp = fopen(ncType,"r")))
if (NULL != (fp = fopen(ncType, "r")))
{
char text[1024] = "\0";
if (0 > fread(text, sizeof(char), 1024, fp))
@ -638,7 +640,7 @@ int kdk_nc_get_vendor_and_product(const char *nc, char *vendor, char *product)
if (strstr(text, "usb_interface"))
{
char *mac = kdk_nc_get_phymac(nc);
int ret = __hwinfo_usb(mac,vendor,product);
int ret = __hwinfo_usb(mac, vendor, product);
free(mac);
return ret;
}
@ -647,23 +649,23 @@ int kdk_nc_get_vendor_and_product(const char *nc, char *vendor, char *product)
char productId[64] = "0";
strcpy(vendorId, filename);
strcpy(productId, filename);
//读厂家id
// 读厂家id
if (NULL != (fp = fopen(strcat(vendorId, "/vendor"), "r")))
{
fgets(vendorId, sizeof(vendorId), fp);
fclose(fp);
}
//读设备id
// 读设备id
if (NULL != (fp = fopen(strcat(productId, "/device"), "r")))
{
fgets(productId, sizeof(vendorId), fp);
fclose(fp);
}
long u[4] = {0,1,2,3}; // 0,1存储网卡的厂家和设备ID23存储pci.ids文件读到的ID
long u[4] = {0, 1, 2, 3}; // 0,1存储网卡的厂家和设备ID23存储pci.ids文件读到的ID
// memset(u, 0, sizeof(u));
int count = sscanf(vendorId, "%lx", &u[0]);
if(count < 1)
if (count < 1)
return -1;
sscanf(productId, "%lx", &u[1]);
if (count < 1)
@ -679,18 +681,18 @@ int kdk_nc_get_vendor_and_product(const char *nc, char *vendor, char *product)
if (strlen(line) == 0 || line[0] == '#')
continue;
//行前无制表符代表厂家id一个制表符代表设备id
// 行前无制表符代表厂家id一个制表符代表设备id
level = 0;
while (level < strlen(line) && line[level] == '\t')
level++;
//获取厂家名称
// 获取厂家名称
if (0 == level)
{
sscanf(line, "%lx", &u[2]);
if (u[0] == u[2])
strcpy(vendor, line + level + 6);
}
//在对应的厂家id下查找设备id
// 在对应的厂家id下查找设备id
if (1 == level && u[0] == u[2])
{
sscanf(line, "%lx", &u[3]);
@ -708,37 +710,141 @@ int kdk_nc_get_vendor_and_product(const char *nc, char *vendor, char *product)
char *kdk_nc_get_driver(const char *nc)
{
char *driver = NULL;
int ret;
struct ifreq ifr;
int fd = socket(AF_INET, SOCK_DGRAM, 0);
struct ethtool_drvinfo *driverInfo = (struct ethtool_drvinfo *)calloc(1, sizeof(struct ethtool_drvinfo));
driverInfo->cmd = ETHTOOL_GDRVINFO;
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, nc);
ifr.ifr_data = (char *)driverInfo;
struct ethtool_drvinfo driverInfo;
memset(&driverInfo, 0, sizeof(struct ethtool_drvinfo));
driverInfo.cmd = ETHTOOL_GDRVINFO;
ifr.ifr_data = (char *)&driverInfo;
ret = ioctl(fd, SIOCETHTOOL, &ifr);
if (0 != ret)
return NULL;
char *driver = (char*)malloc(32);
strcpy(driver,driverInfo->driver);
free(driverInfo);
goto out;
driver = strdup(driverInfo.driver);
out:
close(fd);
return driver;
}
inline void kdk_nc_freeall(char **list)
{
if (! list)
if (!list)
return;
size_t index = 0;
while (list[index])
{
free(list[index]);
index ++;
index++;
}
free(list);
}
char *kdk_nc_get_uuid(char *nc)
{
struct ifreq ifr;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock < 0)
{
perror("Socket creation failed");
return NULL;
}
strcpy(ifr.ifr_name, nc); // 网卡接口名,可以根据实际情况修改
if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
{
perror("IOCTL failed");
return NULL;
}
close(sock);
unsigned char *mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
char uuid[512] = {0};
// 将MAC地址转换为UUID格式
sprintf(uuid, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], mac[0], mac[1], mac[2], mac[3]);
return strdup(uuid);
}
int kdk_nc_get_carrier(char *nc)
{
struct nl_sock *sock = nl_socket_alloc();
if (!sock)
{
klog_err("[%s]Failed to allocate netlink socket", __func__);
return -1;
}
if (nl_connect(sock, NETLINK_ROUTE) < 0)
{
klog_err("[%s]Failed to connect to netlink socket", __func__);
nl_socket_free(sock);
return -1;
}
struct nl_cache *link_cache = NULL;
struct rtnl_link *link = NULL;
int if_index = if_nametoindex(nc);
if (!if_index)
{
klog_err("[%s]Failed to get interface index", __func__);
nl_socket_free(sock);
return -1;
}
if (rtnl_link_alloc_cache(sock, AF_UNSPEC, &link_cache) < 0)
{
klog_err("[%s]Failed to allocate link cache", __func__);
nl_socket_free(sock);
return -1;
}
link = rtnl_link_get(link_cache, if_index);
if (!link)
{
klog_err("[%s]Failed to get link information", __func__);
nl_cache_free(link_cache);
nl_socket_free(sock);
return -1;
}
uint8_t carrier = rtnl_link_get_carrier(link);
nl_cache_free(link_cache);
nl_socket_free(sock);
return carrier;
}
char *kdk_nc_get_duplex(char *nc)
{
char path[1024] = {0}, real_path[1024];
char res[1024] = {0};
sprintf(path, "/sys/class/net/%s/duplex", nc);
if (NULL == realpath(path, real_path))
return NULL;
FILE *fp = fopen(real_path, "r");
if(NULL == fp)
return NULL;
fgets(res, 1024, fp);
strstripspace(res);
char *result = strdup(res);
fclose(fp);
return result;
}
static void ipv4_prefixlen2netmask(int prefixlen, unsigned char *netmask)
{
char buffer[32] = {0};

View File

@ -135,6 +135,30 @@ extern char *kdk_nc_get_driver(const char *nc);
*/
extern inline void kdk_nc_freeall(char **ptr);
/**
* @brief uuid
*
* @param nc
* @return char* uuid
*/
extern char* kdk_nc_get_uuid(char *nc);
/**
* @brief
*
* @param nc
* @return int
*/
extern int kdk_nc_get_carrier(char *nc);
/**
* @brief (/)
*
* @param nc
* @return char*
*/
extern char* kdk_nc_get_duplex(char *nc);
/**
* @brief 广
*

View File

@ -23,17 +23,20 @@
#include "libkyusb.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libusb-1.0/libusb.h>
#include <libudev.h>
#include "libkylog.h"
#include <dbus-1.0/dbus/dbus.h>
/// @brief
/// @return usb device info
/// @brief
/// @return usb device info
pDriverInfoList kdk_usb_get_list()
{
struct udev *udev;
struct udev_enumerate *enumerate;
struct udev_list_entry *list_entry, *dev_list_entry;
struct udev_device *dev, *device, *interface;
struct udev *udev = NULL;
struct udev_enumerate *enumerate = NULL;
struct udev_list_entry *list_entry = NULL, *dev_list_entry = NULL;
struct udev_device *dev = NULL, *device = NULL, *interface = NULL;
pDriverInfoList list = NULL;
pDriverInfoList prevnode = NULL;
@ -41,7 +44,7 @@ pDriverInfoList kdk_usb_get_list()
/* Create the udev object */
udev = udev_new();
if (!udev)
if (NULL == udev)
{
klog_err("Can't create udev");
return list;
@ -49,62 +52,66 @@ pDriverInfoList kdk_usb_get_list()
/*enum devices*/
enumerate = udev_enumerate_new(udev);
if (NULL == enumerate)
{
klog_err("Can't create enumerate");
udev_unref(udev);
return list;
}
// 添加筛选条件 普通usb设备路径/sys/class/hidrawU盘路径/sys/class/block
// udev_enumerate_add_match_subsystem(enumerate, "hidraw");
// udev_enumerate_add_match_subsystem(enumerate, "block");
//扫描设备
// 扫描设备
udev_enumerate_scan_devices(enumerate);
//获取设备列表
// 获取设备列表
list_entry = udev_enumerate_get_list_entry(enumerate);
//遍历
// 遍历
udev_list_entry_foreach(dev_list_entry, list_entry)
{
const char *path;
//创建dev_device设备对象
// 创建dev_device设备对象
path = udev_list_entry_get_name(dev_list_entry);
device = udev_device_new_from_syspath(udev, path);
if(!device)
if (!device)
{
kdk_usb_free(list);
break;
}
//获取interface父节点此节点记录设备类型
// 获取interface父节点此节点记录设备类型
interface = udev_device_get_parent_with_subsystem_devtype(device, "usb", "usb_interface");
if (!interface)
{
goto free;
}
//非usb设备直接进入下一轮循环
// 非usb设备直接进入下一轮循环
dev = udev_device_get_parent_with_subsystem_devtype(device, "usb", "usb_device");
if (!dev)
{
goto free;
}
//同一款外设会生成两个设备文件,原因不明。暂时先手动去重
// 同一款外设会生成两个设备文件,原因不明。暂时先手动去重
pDriverInfoList tmp = list;
int isRepetive = 0;
while (tmp)
{
if(0 == strcmp(tmp->data->devNode,udev_device_get_devnode(dev)))
if (0 == strcmp(tmp->data->devNode, udev_device_get_devnode(dev)))
{
isRepetive = 1;
}
tmp = tmp->next;
}
if(isRepetive)
if (isRepetive)
{
goto free;
}
//申请节点内存
if(NULL == list)
// 申请节点内存
if (NULL == list)
{
curnode = (pDriverInfoList)calloc(1, sizeof(DriverInfoList));
list = curnode;
@ -127,26 +134,25 @@ pDriverInfoList kdk_usb_get_list()
kdk_usb_free(list);
return NULL;
}
sprintf(curnode->data->name, "%s", udev_device_get_sysattr_value(dev, "product") ? udev_device_get_sysattr_value(dev, "product"): "null");
sprintf(curnode->data->name, "%s", udev_device_get_sysattr_value(dev, "product") ? udev_device_get_sysattr_value(dev, "product") : "null");
sprintf(curnode->data->type, "%s", udev_device_get_sysattr_value(interface, "bInterfaceClass") ? udev_device_get_sysattr_value(interface, "bInterfaceClass") : "null");
sprintf(curnode->data->pid, "%s", udev_device_get_sysattr_value(dev, "idProduct") ? udev_device_get_sysattr_value(dev, "idProduct") : "null");
sprintf(curnode->data->vid, "%s", udev_device_get_sysattr_value(dev, "idVendor") ? udev_device_get_sysattr_value(dev, "idVendor") : "null");
sprintf(curnode->data->serialNo, "%s", udev_device_get_sysattr_value(dev, "serial") ? udev_device_get_sysattr_value(dev, "serial") : "null");
sprintf(curnode->data->devNode ,"%s", udev_device_get_devnode(dev));
sprintf(curnode->data->devNode, "%s", udev_device_get_devnode(dev));
// sprintf(curnode->data->vendor, "%s", udev_device_get_sysattr_value(dev, "manufacturer"));
if (NULL != prevnode)
prevnode->next = curnode;
prevnode = curnode;
curnode = NULL;
free:
if(device)
free:
if (device)
udev_device_unref(device);
}
udev_enumerate_unref(enumerate);
udev_unref(udev);
return list;
}
@ -161,3 +167,686 @@ void kdk_usb_free(pDriverInfoList list)
free(tmp);
}
}
pUsbInfo kdk_usb_get_bus_info()
{
int ret = libusb_init(NULL);
if (ret != 0)
{
klog_err("fail to init: %d\n", ret);
return NULL;
}
libusb_device **devs = NULL;
ssize_t count = libusb_get_device_list(NULL, &devs);
if (count < 0)
{
klog_err("fail to get device list: %d\n", count);
libusb_exit(NULL);
return NULL;
}
UsbInfo *result = calloc(count + 1, sizeof *result);
if (NULL == result)
{
klog_err("fail to request memory: %d\n");
libusb_exit(NULL);
return NULL;
}
for (int i = 0; i < count; i++)
{
libusb_device *dev = devs[i];
result[i].busNum = libusb_get_bus_number(dev);
result[i].devNum = libusb_get_device_address(dev);
result[i].next = result + i + 1;
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return result;
}
// int kdk_usb_get_found(int busNum, int devAddress)
// {
// return 0;
// }
char *_kdk_usb_get_productName(int busNum, int devAddress)
{
char *result = NULL;
int ret = libusb_init(NULL);
if (ret != 0)
{
klog_err("fail to init: %d\n", ret);
return NULL;
}
libusb_device **devs = NULL;
ssize_t count = libusb_get_device_list(NULL, &devs);
if (count < 0)
{
klog_err("fail to get device list: %d\n", count);
libusb_exit(NULL);
return NULL;
}
for (int i = 0; i < count; i++)
{
libusb_device *dev = devs[i];
if (libusb_get_bus_number(dev) == busNum && libusb_get_device_address(dev) == devAddress)
{
libusb_device_handle *dev_handle;
ret = libusb_open(dev, &dev_handle);
if (ret < 0)
{
klog_err("fail to open device : %d\n", ret);
return NULL;
}
unsigned char product[256];
libusb_get_string_descriptor_ascii(dev_handle, 2, product, sizeof(product));
libusb_close(dev_handle);
result = strdup(product);
break;
}
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return result;
}
char *kdk_usb_get_productName(int busNum, int devAddress)
{
char *ret = NULL;
DBusConnection *conn;
DBusError err;
dbus_error_init(&err);
conn = dbus_bus_get_private(DBUS_BUS_SYSTEM, &err);
if (NULL == conn)
{
ret = NULL;
}
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
DBusMessage *info_msg = NULL;
DBusPendingCall *sendMsgPending = NULL;
DBusMessage *replyMsg = NULL;
//创建用户
info_msg = dbus_message_new_method_call("com.kylin.kysdk.service", // target for the method call
"/com/kylin/kysdk/peripheralsenum", // object to call on
"com.kylin.kysdk.peripheralsenum", // interface to call on
"getUsbProductName"); // method name
if (!info_msg)
{ // -1 is default timeout
ret = NULL;
}
if (!dbus_message_append_args(info_msg, DBUS_TYPE_INT32, &busNum, DBUS_TYPE_INT32, &devAddress, DBUS_TYPE_INVALID))
{
ret = NULL;
}
if (!dbus_connection_send_with_reply(conn, info_msg, &sendMsgPending, -1))
{
ret = NULL;
}
if (sendMsgPending == NULL)
{
ret = NULL;
}
dbus_connection_flush(conn);
if (info_msg)
{
dbus_message_unref(info_msg);
}
dbus_pending_call_block(sendMsgPending);
replyMsg = dbus_pending_call_steal_reply(sendMsgPending);
if (replyMsg == NULL)
{
ret = NULL;
}
if (sendMsgPending)
{
dbus_pending_call_unref(sendMsgPending);
}
DBusMessageIter args;
if (!dbus_message_iter_init(replyMsg, &args))
{
dbus_message_unref(replyMsg);
ret = NULL;
}
else
{
dbus_message_iter_get_basic(&args, &ret);
}
if (replyMsg)
{
dbus_message_unref(replyMsg);
}
dbus_connection_close(conn);
if(ret == NULL)
{
ret = _kdk_usb_get_productName(busNum, devAddress);
}
char *productName = NULL;
if(ret != NULL)
{
productName = (char *)malloc(sizeof(char) * 256);
if(!productName)
{
productName = NULL;
}
strcpy(productName, ret);
}
return productName;
}
char *_kdk_usb_get_manufacturerName(int busNum, int devAddress)
{
char *result = NULL;
int ret = libusb_init(NULL);
if (ret != 0)
{
klog_err("fail to init: %d\n", ret);
return NULL;
}
libusb_device **devs = NULL;
ssize_t count = libusb_get_device_list(NULL, &devs);
if (count < 0)
{
klog_err("fail to get device list: %d\n", count);
libusb_exit(NULL);
return NULL;
}
for (int i = 0; i < count; i++)
{
libusb_device *dev = devs[i];
if (libusb_get_bus_number(dev) == busNum && libusb_get_device_address(dev) == devAddress)
{
libusb_device_handle *dev_handle;
ret = libusb_open(dev, &dev_handle);
if (ret < 0)
{
klog_err("fail to get device descriptor: %d\n", ret);
return NULL;
}
unsigned char manufacturer[256];
libusb_get_string_descriptor_ascii(dev_handle, 1, manufacturer, sizeof(manufacturer));
libusb_close(dev_handle);
result = strdup(manufacturer);
break;
}
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return result;
}
char *kdk_usb_get_manufacturerName(int busNum, int devAddress)
{
char *ret = NULL;
DBusConnection *conn;
DBusError err;
dbus_error_init(&err);
conn = dbus_bus_get_private(DBUS_BUS_SYSTEM, &err);
if (NULL == conn)
{
ret = NULL;
}
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
DBusMessage *info_msg = NULL;
DBusPendingCall *sendMsgPending = NULL;
DBusMessage *replyMsg = NULL;
//创建用户
info_msg = dbus_message_new_method_call("com.kylin.kysdk.service", // target for the method call
"/com/kylin/kysdk/peripheralsenum", // object to call on
"com.kylin.kysdk.peripheralsenum", // interface to call on
"getUsbManufacturerName"); // method name
if (!info_msg)
{ // -1 is default timeout
ret = NULL;
}
if (!dbus_message_append_args(info_msg, DBUS_TYPE_INT32, &busNum, DBUS_TYPE_INT32, &devAddress, DBUS_TYPE_INVALID))
{
ret = NULL;
}
if (!dbus_connection_send_with_reply(conn, info_msg, &sendMsgPending, -1))
{
ret = NULL;
}
if (sendMsgPending == NULL)
{
ret = NULL;
}
dbus_connection_flush(conn);
if (info_msg)
{
dbus_message_unref(info_msg);
}
dbus_pending_call_block(sendMsgPending);
replyMsg = dbus_pending_call_steal_reply(sendMsgPending);
if (replyMsg == NULL)
{
ret = NULL;
}
if (sendMsgPending)
{
dbus_pending_call_unref(sendMsgPending);
}
DBusMessageIter args;
if (!dbus_message_iter_init(replyMsg, &args))
{
dbus_message_unref(replyMsg);
ret = NULL;
}
else
{
dbus_message_iter_get_basic(&args, &ret);
}
if (replyMsg)
{
dbus_message_unref(replyMsg);
}
dbus_connection_close(conn);
if(ret == NULL)
{
ret = _kdk_usb_get_manufacturerName(busNum, devAddress);
}
char *manufacturerName = NULL;
if(ret != NULL)
{
manufacturerName = (char *)malloc(sizeof(char) * 256);
if(!manufacturerName)
{
manufacturerName = NULL;
}
strcpy(manufacturerName, ret);
}
return manufacturerName;
}
int kdk_usb_get_mount(int busNum, int devAddress)
{
int result = 0;
char *product = kdk_usb_get_productName(busNum, devAddress);
char *vendor = kdk_usb_get_manufacturerName(busNum, devAddress);
if (!product || !vendor)
return result;
char tmp[1024];
sprintf(tmp, "%s %s", vendor, product);
FILE *fp = popen("udisksctl status", "r");
if (NULL == fp)
return result;
char line[1024];
while (fgets(line, 1024, fp))
{
if (NULL != strstr(line, tmp))
{
result = 1;
break;
}
}
return result;
}
char *kdk_usb_get_version(int busNum, int devAddress)
{
char *result = NULL;
int ret = libusb_init(NULL);
if (ret != 0)
{
klog_err("fail to init: %d\n", ret);
return NULL;
}
libusb_device **devs = NULL;
ssize_t count = libusb_get_device_list(NULL, &devs);
if (count < 0)
{
klog_err("fail to get device list: %d\n", count);
libusb_exit(NULL);
return NULL;
}
for (int i = 0; i < count; i++)
{
libusb_device *dev = devs[i];
if (libusb_get_bus_number(dev) == busNum && libusb_get_device_address(dev) == devAddress)
{
struct libusb_device_descriptor desc;
ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
klog_err("Error getting device descriptor\n");
break;
}
char version[256];
sprintf(version, "%x.%x", desc.bcdUSB >> 8, desc.bcdUSB & 0xff);
result = strdup(version);
break;
}
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return result;
}
int kdk_usb_get_deviceClass(int busNum, int devAddress)
{
int result = LIBUSB_ERROR_OTHER;
int ret = libusb_init(NULL);
if (ret != 0)
{
klog_err("fail to init: %d\n", ret);
return result;
}
libusb_device **devs = NULL;
ssize_t count = libusb_get_device_list(NULL, &devs);
if (count < 0)
{
klog_err("fail to get device list: %d\n", count);
libusb_exit(NULL);
return result;
}
for (int i = 0; i < count; i++)
{
libusb_device *dev = devs[i];
if (libusb_get_bus_number(dev) == busNum && libusb_get_device_address(dev) == devAddress)
{
struct libusb_device_descriptor desc;
ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
klog_err("Error getting device descriptor\n");
result = ret;
break;
}
result = desc.bDeviceClass;
break;
}
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return result;
}
int kdk_usb_get_deviceSubClass(int busNum, int devAddress)
{
int result = LIBUSB_ERROR_OTHER;
int ret = libusb_init(NULL);
if (ret != 0)
{
klog_err("fail to init: %d\n", ret);
return result;
}
libusb_device **devs = NULL;
ssize_t count = libusb_get_device_list(NULL, &devs);
if (count < 0)
{
klog_err("fail to get device list: %d\n", count);
libusb_exit(NULL);
return result;
}
for (int i = 0; i < count; i++)
{
libusb_device *dev = devs[i];
if (libusb_get_bus_number(dev) == busNum && libusb_get_device_address(dev) == devAddress)
{
struct libusb_device_descriptor desc;
ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
klog_err("Error getting device descriptor\n");
result = ret;
break;
}
result = desc.bDeviceSubClass;
break;
}
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return result;
}
int kdk_usb_get_deviceProtocol(int busNum, int devAddress)
{
int result = LIBUSB_ERROR_OTHER;
int ret = libusb_init(NULL);
if (ret != 0)
{
klog_err("fail to init: %d\n", ret);
return result;
}
libusb_device **devs = NULL;
ssize_t count = libusb_get_device_list(NULL, &devs);
if (count < 0)
{
klog_err("fail to get device list: %d\n", count);
libusb_exit(NULL);
return result;
}
for (int i = 0; i < count; i++)
{
libusb_device *dev = devs[i];
if (libusb_get_bus_number(dev) == busNum && libusb_get_device_address(dev) == devAddress)
{
struct libusb_device_descriptor desc;
ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
klog_err("Error getting device descriptor\n");
result = ret;
break;
}
result = desc.bDeviceProtocol;
break;
}
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return result;
}
char *kdk_usb_get_speed(int busNum, int devAddress)
{
char *result = NULL;
int ret = libusb_init(NULL);
if (ret != 0)
{
klog_err("fail to init: %d\n", ret);
return NULL;
}
libusb_device **devs = NULL;
ssize_t count = libusb_get_device_list(NULL, &devs);
if (count < 0)
{
klog_err("fail to get device list: %d\n", count);
libusb_exit(NULL);
return NULL;
}
for (int i = 0; i < count; i++)
{
libusb_device *dev = devs[i];
if (libusb_get_bus_number(dev) == busNum && libusb_get_device_address(dev) == devAddress)
{
struct libusb_device_descriptor desc;
ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
klog_err("Error getting device descriptor\n");
break;
}
switch(libusb_get_device_speed(dev))
{
case 1:
result = strdup("1.5MBit/s");
break;
case 2:
result = strdup("12MBit/s");
break;
case 3:
result = strdup("480MBit/s");
break;
case 4:
result = strdup("5000MBit/s");
break;
case 5:
result = strdup("10000MBit/s");
break;
default:
result = strdup("unknown");
}
break;
}
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return result;
}
pUsbDeviceDescriptor kdk_usb_get_device_descriptor(int busNum, int devAddress)
{
pUsbDeviceDescriptor result = calloc(1, sizeof *result);
if (NULL == result)
{
klog_err("fail to request memory");
return NULL;
}
int ret = libusb_init(NULL);
if (ret != 0)
{
klog_err("fail to init: %d", ret);
return NULL;
}
libusb_device **devs = NULL;
ssize_t count = libusb_get_device_list(NULL, &devs);
if (count < 0)
{
klog_err("fail to get device list: %d", count);
libusb_exit(NULL);
return NULL;
}
for (int i = 0; i < count; i++)
{
libusb_device *dev = devs[i];
if (libusb_get_bus_number(dev) == busNum && libusb_get_device_address(dev) == devAddress)
{
struct libusb_device_descriptor desc;
ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
klog_err("Error getting device descriptor\n");
break;
}
result->lenth = desc.bLength;
result->descriptorType = desc.bDescriptorType;
result->maxPacketSize0 = desc.bMaxPacketSize0;
result->numConfigurations = desc.bNumConfigurations;
break;
}
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return result;
}
void kdk_usb_free_usb_info(pUsbInfo list)
{
if(NULL == list)
return;
while (list)
{
pUsbInfo* tmp = list;
list = list->next;
free(tmp);
}
}
void kdk_usb_free_usb_device_descriptor(pUsbDeviceDescriptor *descriptor)
{
if(NULL == descriptor)
return;
free(descriptor);
}

View File

@ -48,8 +48,8 @@ typedef struct driver_info
{
char name[32]; //名称
char type[2 + 1]; //类型
char pid[4 + 1];
char vid[4 + 1];
char pid[4 + 1]; //设备pid
char vid[4 + 1]; //设备vid
char serialNo[32]; //序列号
char devNode[32]; //路径
} DriverInfo, *pDriverInfo;
@ -63,6 +63,21 @@ typedef struct driver_list
struct driver_list *next;
} DriverInfoList, *pDriverInfoList;
typedef struct _UsbInfo
{
unsigned short busNum; //总线地址
unsigned short devNum; //设备地址
struct _UsbInfo* next; //链表next指针
}UsbInfo, *pUsbInfo;
typedef struct _UsbDeviceDescriptor
{
unsigned short lenth; //描述符的字节数恒为18
unsigned short descriptorType; //描述符类型恒为0x01
unsigned short maxPacketSize0; //端点0的最大数据包大小
unsigned short numConfigurations; //可能的配置数量
}UsbDeviceDescriptor, *pUsbDeviceDescriptor;
/**
* @brief usb设备信息
*
@ -77,6 +92,118 @@ extern pDriverInfoList kdk_usb_get_list();
*/
extern void kdk_usb_free(pDriverInfoList list);
/**
* @brief usb设备的总线地址和设备地址
*
* @return pUsbInfo usb设备总线地址和设备地址结构体
*/
extern pUsbInfo kdk_usb_get_bus_info();
/**
* @brief usb设备是否连接
*
* @param busNum 线
* @param devAddress
* @return int true ; false
*/
// extern int kdk_usb_get_found(int busNum, int devAddress);
/**
* @brief usb硬盘类设备是否挂载
*
* @param busNum 线
* @param devAddress
* @return int true ; false
*/
extern int kdk_usb_get_mount(int busNum, int devAddress);
/**
* @brief usb设备的产品信息
*
* @param busNum 线
* @param devAddress
* @return char* usb设备的产品信息
*/
extern char* kdk_usb_get_productName(int busNum, int devAddress);
/**
* @brief usb设备厂商信息
*
* @param busNum 线
* @param devAddress
* @return char* usb设备的厂商信息
*/
extern char* kdk_usb_get_manufacturerName(int busNum, int devAddress);
/**
* @brief usb设备的版本
*
* @param busNum 线
* @param devAddress
* @return char* usb设备的版本
*/
extern char* kdk_usb_get_version(int busNum, int devAddress);
/**
* @brief usb设备的设备类
*
* @param busNum 线
* @param devAddress
* @return int usb设备的设备类
*/
extern int kdk_usb_get_deviceClass(int busNum, int devAddress);
/**
* @brief usb设备的设备子类
*
* @param busNum 线
* @param devAddress
* @return int usb设备的设备子类
*/
extern int kdk_usb_get_deviceSubClass(int busNum, int devAddress);
/**
* @brief USB设备的协议码
*
* @param busNum 线
* @param devAddress
* @return int USB设备的协议码
*/
extern int kdk_usb_get_deviceProtocol(int busNum, int devAddress);
/**
* @brief usb设备的协商连接速度
*
* @param busNum 线
* @param devAddress
* @return char* usb设备的协商连接速度
*/
extern char* kdk_usb_get_speed(int busNum, int devAddress);
/**
* @brief usb设备的设备描述符
*
* @param busNum 线
* @param devAddress
* @return pUsbDeviceDescriptor usb设备的设备描述符
*/
extern pUsbDeviceDescriptor kdk_usb_get_device_descriptor(int busNum, int devAddress);
/**
* @brief kdk_usb_get_bus_info返回
*
* @param list kdk_usb_get_bus_info返回的指针
*/
extern void kdk_usb_free_usb_info(pUsbInfo list);
/**
* @brief kdk_usb_get_device_descriptor返回
*
* @param descriptor kdk_usb_get_device_descriptor返回的指针
*/
extern void kdk_usb_free_usb_device_descriptor(pUsbDeviceDescriptor *descriptor);
#ifdef __cplusplus
}
#endif

View File

@ -39,34 +39,49 @@ int main()
char *features = "\0";
char *bus = "\0";
int **id = kdk_bluetooth_get_device_id();
do
{
if(NULL == id)
return 0;
for(; id[i]; i++)
{
printf("id = %d\n",id[i]);
manufacturer = kdk_bluetooth_get_manufacturer(i);
printf("manufacturer: %s\n", manufacturer);
free(manufacturer);
version = kdk_bluetooth_get_dev_version(i);
printf("version: %s\n", version);
free(version);
name = kdk_bluetooth_get_name(id[i]);
printf("name: %s\n", name);
address = kdk_bluetooth_get_address(id[i]);
printf("address: %s\n", address);
link_mode = kdk_bluetooth_get_link_mode(id[i]);
printf("link_mode: %s\n", link_mode);
link_policy = kdk_bluetooth_get_link_policy(id[i]);
printf("link_policy: %s\n", link_policy);
scomtu = kdk_bluetooth_get_scomtu(id[i]);
printf("scomtu: %s\n", scomtu);
alcmtu = kdk_bluetooth_get_alcmtu(id[i]);
printf("alcmtu: %s\n", alcmtu);
packettype = kdk_bluetooth_get_packettype(id[i]);
printf("packettype: %s\n", packettype);
features = kdk_bluetooth_get_features(id[i]);
printf("features: %s\n", features);
bus = kdk_bluetooth_get_bus(id[i]);
printf("bus: %s\n", bus);
i++;
}while(id[i]);
free(id[i]);
}
free(id);
return 0;
}

View File

@ -33,6 +33,7 @@ int main()
printf("CPU 单核核心数量:%u\n", kdk_cpu_get_corenums());
printf("CPU 虚拟化支持:%s\n", kdk_cpu_get_virt());
printf("CPU 线程数:%u\n", kdk_cpu_get_process());
printf("CPU 最大频率:%0.2f MHz\n", kdk_cpu_get_max_freq_MHz());
printf("CPU 最小频率:%0.2f MHz\n", kdk_cpu_get_min_freq_MHz());
char *run_time = kdk_cpu_get_running_time();

View File

@ -27,30 +27,41 @@
int main()
{
char** name = kdk_edid_get_interface();
size_t count = 0;
while (name[count])
if(NULL == name)
return 0;
for(size_t count = 0; name[count]; count++)
{
printf("当前接口 = %s\n", name[count]);
float gamma = kdk_edid_get_gamma(name[count]);
printf("gamma = %0.2f\n", gamma);
float size = kdk_edid_get_size(name[count]);
printf("size = %0.1f\n", size);
char *max_resolution = kdk_edid_get_max_resolution(name[count]);
printf("max_resolution = %s\n", max_resolution);
free(max_resolution);
char *model = kdk_edid_get_model(name[count]);
printf("model = %s\n", model);
free(model);
char *area = kdk_edid_get_visible_area(name[count]);
printf("area = %s\n", area);
free(area);
char *manufacturer = kdk_edid_get_manufacturer(name[count]);
printf("manufacturer = %s\n", manufacturer);
free(manufacturer);
int week = kdk_edid_get_week(name[count]);
printf("week = %d\n", week);
int year = kdk_edid_get_year(name[count]);
printf("year = %d\n", year);
int primary = kdk_edid_get_primary(name[count]);
printf("%s\n", primary == 1 ? "" : "");
@ -67,7 +78,7 @@ int main()
free(character);
printf("---------------------------------------\n");
count ++;
}
kdk_edid_freeall(name);
return 0;

View File

@ -28,10 +28,9 @@ int main()
{
char **fan = kdk_fan_get_information();
int index = 0;
while (fan[index])
for (int index = 0; fan[index]; index++)
{
printf("%s\n", fan[index]);
index++;
}
kdk_fan_freeall(fan);
return 0;

View File

@ -105,6 +105,9 @@ static void Traverse_power()
printf("\ttechnology : %s\n", tmp->technology);
printf("\tonline : %s\n", tmp->online ? "true" : "false");
printf("\ticon name : %s\n", tmp->icon_name);
printf("\tmodel : %s\n", tmp->model);
printf("\tbattery_level : %d\n", tmp->battery_level);
printf("\ttype : %d\n", tmp->type);
tmp = tmp->next;
}
kdk_hw_free_power_info(power);

View File

@ -37,11 +37,30 @@ int main()
char *driver = kdk_nc_get_driver(cards[index]);
char vendor[256] = "\0", product[256] = "\0";
kdk_nc_get_vendor_and_product(cards[index], vendor, product);
printf("Card %zd: %s\tStatus: %s\tMac: %s\tIPv4: %s\tIPv6: %s\t Vendor: %s\t Product: %s\t Type: %s\t driver: %s\t \n",
printf("Card %zd: %s\tStatus: %s\tMac: %s\tIPv4: %s\tIPv6: %s\t Vendor: %s\t Product: %s\t Type: %s\t driver: %s\n",
index + 1, cards[index], kdk_nc_is_up(cards[index]) == 1 ? "Up" : "Down",
mac, ipv4, ipv6, vendor, product,
kdk_nc_is_wireless(cards[index]) ? "wireless" : "ethernet", driver);
if (mac)
free(mac);
if (ipv4)
free(ipv4);
if (ipv6)
free(ipv6);
if (driver)
free(driver);
char *uuid = kdk_nc_get_uuid(cards[index]);
printf("%s\n", uuid ? uuid : "get uuid faile");
free(uuid);
printf("%d\n", kdk_nc_get_carrier(cards[index]));
char *duplex = kdk_nc_get_duplex(cards[index]);
printf("%s\n", duplex ? duplex : "get duplex failed");
free(duplex);
char *conn = kdk_nc_get_conn_type(cards[index]);
printf("Conn type = %s\n", conn);
@ -103,7 +122,8 @@ int main()
printf("AllIpV4: ");
while (list4 && list4[i])
{
printf("%s\n", list4[i]);
printf("%s\t", list4[i]);
char *boardaddr = kdk_nc_get_broadAddr(cards[index], list4[i]);
printf("boardaddr = %s\n", boardaddr);
free(boardaddr);
@ -111,7 +131,8 @@ int main()
char *netmask = kdk_nc_get_netmask(cards[index], list4[i]);
printf("netmask = %s\n", netmask);
free(netmask);
i++;
free(list4[i++]);
}
printf("\n");
char **list6 = kdk_nc_get_ipv6(cards[index]);
@ -120,24 +141,23 @@ int main()
while (list6 && list6[i])
{
printf("%s\t", list6[i]);
int len = kdk_nc_get_mask_length(0, cards[index], list6[i]);
printf("netmask_length = %d\n", len);
int scope = kdk_nc_get_scope(cards[index], list6[i]);
printf("scope = %d\n", scope);
i++;
free(list6[i++]);
}
printf("\n");
free(mac);
free(ipv4);
free(ipv6);
free(list4);
free(list6);
free(driver);
index++;
}
kdk_nc_freeall(cards);
char **upcards = kdk_nc_get_upcards();
index = 0;
printf("工作网卡:\n");

View File

@ -23,6 +23,9 @@
#include "stdio.h"
#include "../libkyusb.h"
#define BUS_NUM 1
#define DEV_NUM 5
int main()
{
pDriverInfoList list = kdk_usb_get_list();
@ -42,5 +45,23 @@ int main()
}
kdk_usb_free(list);
pUsbInfo usb_info = kdk_usb_get_bus_info();
pUsbInfo tmp = usb_info;
while(tmp)
{
printf("%03u:%03u\n", tmp->busNum, tmp->devNum);
tmp = tmp->next;
}
printf("%d\n", kdk_usb_get_mount(BUS_NUM,DEV_NUM));
printf("%s\n", kdk_usb_get_productName(BUS_NUM,DEV_NUM));
printf("%s\n", kdk_usb_get_manufacturerName(BUS_NUM,DEV_NUM));
printf("%s\n", kdk_usb_get_version(BUS_NUM,DEV_NUM));
printf("%d\n", kdk_usb_get_deviceClass(BUS_NUM,DEV_NUM));
printf("%d\n", kdk_usb_get_deviceSubClass(BUS_NUM,DEV_NUM));
printf("%d\n", kdk_usb_get_deviceProtocol(BUS_NUM,DEV_NUM));
printf("%s\n", kdk_usb_get_speed(BUS_NUM,DEV_NUM));
pUsbDeviceDescriptor desc = kdk_usb_get_device_descriptor(BUS_NUM,DEV_NUM);
printf("%d %d %d %d\n",desc->lenth,desc->descriptorType, desc->maxPacketSize0, desc->numConfigurations);
return 0;
}

View File

@ -2,7 +2,7 @@ project(kyimageproc)
aux_source_directory(. SOURCESCODE)
include_directories(.)
add_library(kyimageproc SHARED ${SOURCESCODE})
set_target_properties(kyimageproc PROPERTIES VERSION 2.3.0 SOVERSION 1)
set_target_properties(kyimageproc PROPERTIES VERSION 2.4.0 SOVERSION 1)
find_package(PkgConfig REQUIRED)
pkg_check_modules(KYSDKLOG kysdk-log)

View File

@ -74,12 +74,12 @@ int read_image(const char * const file, size_t *width, size_t *height, rgb_t **b
char* ret2;
ret = 0;
char fullname[256]={0};
if(!realpath(file,fullname) || verify_file(file))
char canonical_filename[256]={0};
if(!realpath(file,canonical_filename) || verify_file(canonical_filename))
{
return 0x05;
}
FILE *fp = fopen(fullname, "rb");
FILE *fp = fopen(canonical_filename, "rb");
if(fp == NULL) {
klog_err("Could not open file:%s\n",file);
return 0x1;

View File

@ -38,14 +38,14 @@ extern "C"
extern void* kdk_jpeg_encoder_init();
/**
* @brief
* @brief jpeg图编码接口
*
* @param handle
* @param
* @param
* @return -1 0
* @param srcFile
* @param destFile
* @return int -1 0
*/
extern int kdk_jpeg_encode_to_file(void *handle, char*srcFile, char *destFile);
extern int kdk_jpeg_encode_to_file(void *handle, char *srcFile, char *destFile);
/**
* @brief

View File

@ -0,0 +1,50 @@
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memory>
#include <string>
#include <unordered_map>
namespace paddle {
namespace framework {
class Cipher {
public:
Cipher() = default;
virtual ~Cipher() {}
// encrypt string
virtual std::string Encrypt(const std::string& plaintext,
const std::string& key) = 0;
// decrypt string
virtual std::string Decrypt(const std::string& ciphertext,
const std::string& key) = 0;
// encrypt strings and read them to file,
virtual void EncryptToFile(const std::string& plaintext,
const std::string& key,
const std::string& filename) = 0;
// read from file and decrypt them
virtual std::string DecryptFromFile(const std::string& key,
const std::string& filename) = 0;
};
class CipherFactory {
public:
CipherFactory() = default;
static std::shared_ptr<Cipher> CreateCipher(const std::string& config_file);
};
} // namespace framework
} // namespace paddle

View File

@ -0,0 +1,32 @@
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#if !defined(_MSC_VER) && __cplusplus < 199711L
#error C++11 or later compatible compiler is required to use Paddle.
#endif
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX // msvc max/min macro conflict with std::min/max
#endif
#endif
#include "ext_dispatch.h" // NOLINT
#include "ext_dtype.h" // NOLINT
#include "ext_exception.h" // NOLINT
#include "ext_op_meta_info.h" // NOLINT
#include "ext_place.h" // NOLINT
#include "ext_tensor.h" // NOLINT

View File

@ -0,0 +1,98 @@
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include "ext_dtype.h" // NOLINT
#include "ext_exception.h" // NOLINT
namespace paddle {
///////// Basic Marco ///////////
#define PD_PRIVATE_CASE_TYPE_USING_HINT(NAME, enum_type, type, HINT, ...) \
case enum_type: { \
using HINT = type; \
__VA_ARGS__(); \
break; \
}
#define PD_PRIVATE_CASE_TYPE(NAME, enum_type, type, ...) \
PD_PRIVATE_CASE_TYPE_USING_HINT(NAME, enum_type, type, data_t, __VA_ARGS__)
///////// Floating Dispatch Marco ///////////
#define PD_DISPATCH_FLOATING_TYPES(TYPE, NAME, ...) \
[&] { \
const auto& __dtype__ = TYPE; \
switch (__dtype__) { \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::FLOAT32, float, \
__VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::FLOAT64, double, \
__VA_ARGS__) \
default: \
PD_THROW("function " #NAME " is not implemented for data type `", \
::paddle::ToString(__dtype__), "`"); \
} \
}()
///////// Integral Dispatch Marco ///////////
#define PD_DISPATCH_INTEGRAL_TYPES(TYPE, NAME, ...) \
[&] { \
const auto& __dtype__ = TYPE; \
switch (__dtype__) { \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT32, int, __VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT64, int64_t, \
__VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT8, int8_t, \
__VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::UINT8, uint8_t, \
__VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT16, int16_t, \
__VA_ARGS__) \
default: \
PD_THROW("function " #NAME " is not implemented for data type `" + \
::paddle::ToString(__dtype__) + "`"); \
} \
}()
///////// Floating and Integral Dispatch Marco ///////////
#define PD_DISPATCH_FLOATING_AND_INTEGRAL_TYPES(TYPE, NAME, ...) \
[&] { \
const auto& __dtype__ = TYPE; \
switch (__dtype__) { \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::FLOAT32, float, \
__VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::FLOAT64, double, \
__VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT32, int, __VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT64, int64_t, \
__VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT8, int8_t, \
__VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::UINT8, uint8_t, \
__VA_ARGS__) \
PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT16, int16_t, \
__VA_ARGS__) \
default: \
PD_THROW("function " #NAME " is not implemented for data type `" + \
::paddle::ToString(__dtype__) + "`"); \
} \
}()
// TODO(chenweihang): Add more Marcos in the future if needed
} // namespace paddle

View File

@ -0,0 +1,27 @@
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#if defined(_WIN32)
#ifndef PD_DLL_DECL
#ifdef PADDLE_DLL_EXPORT
#define PD_DLL_DECL __declspec(dllexport)
#else
#define PD_DLL_DECL __declspec(dllimport)
#endif // PADDLE_DLL_EXPORT
#endif // PD_DLL_DECL
#else
#define PD_DLL_DECL
#endif // _WIN32

View File

@ -0,0 +1,81 @@
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <cstdint>
#include <string>
#include "ext_exception.h" // NOLINT
namespace paddle {
enum class DataType {
BOOL,
INT8,
UINT8,
INT16,
INT32,
INT64,
FLOAT32,
FLOAT64,
// TODO(JiabinYang) support more data types if needed.
};
inline std::string ToString(DataType dtype) {
switch (dtype) {
case DataType::BOOL:
return "bool";
case DataType::INT8:
return "int8_t";
case DataType::UINT8:
return "uint8_t";
case DataType::INT16:
return "int16_t";
case DataType::INT32:
return "int32_t";
case DataType::INT64:
return "int64_t";
case DataType::FLOAT32:
return "float";
case DataType::FLOAT64:
return "double";
default:
PD_THROW("Unsupported paddle enum data type.");
}
}
#define PD_FOR_EACH_DATA_TYPE(_) \
_(bool, DataType::BOOL) \
_(int8_t, DataType::INT8) \
_(uint8_t, DataType::UINT8) \
_(int16_t, DataType::INT16) \
_(int, DataType::INT32) \
_(int64_t, DataType::INT64) \
_(float, DataType::FLOAT32) \
_(double, DataType::FLOAT64)
template <paddle::DataType T>
struct DataTypeToCPPType;
#define PD_SPECIALIZE_DataTypeToCPPType(cpp_type, data_type) \
template <> \
struct DataTypeToCPPType<data_type> { \
using type = cpp_type; \
};
PD_FOR_EACH_DATA_TYPE(PD_SPECIALIZE_DataTypeToCPPType)
#undef PD_SPECIALIZE_DataTypeToCPPType
} // namespace paddle

View File

@ -0,0 +1,108 @@
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <iostream>
#include <sstream>
#include <string>
namespace paddle {
//////////////// Exception handling and Error Message /////////////////
#if !defined(_WIN32)
#define PD_UNLIKELY(expr) (__builtin_expect(static_cast<bool>(expr), 0))
#define PD_LIKELY(expr) (__builtin_expect(static_cast<bool>(expr), 1))
#else
#define PD_UNLIKELY(expr) (expr)
#define PD_LIKELY(expr) (expr)
#endif
struct PD_Exception : public std::exception {
public:
template <typename... Args>
explicit PD_Exception(const std::string& msg, const char* file, int line,
const char* default_msg) {
std::ostringstream sout;
if (msg.empty()) {
sout << default_msg << "\n [" << file << ":" << line << "]";
} else {
sout << msg << "\n [" << file << ":" << line << "]";
}
err_msg_ = sout.str();
}
const char* what() const noexcept override { return err_msg_.c_str(); }
private:
std::string err_msg_;
};
class ErrorMessage {
public:
template <typename... Args>
explicit ErrorMessage(const Args&... args) {
build_string(args...);
}
void build_string() { oss << ""; }
template <typename T>
void build_string(const T& t) {
oss << t;
}
template <typename T, typename... Args>
void build_string(const T& t, const Args&... args) {
build_string(t);
build_string(args...);
}
std::string to_string() { return oss.str(); }
private:
std::ostringstream oss;
};
#if defined _WIN32
#define HANDLE_THE_ERROR try {
#define END_HANDLE_THE_ERROR \
} \
catch (const std::exception& e) { \
std::cerr << e.what() << std::endl; \
throw e; \
}
#else
#define HANDLE_THE_ERROR
#define END_HANDLE_THE_ERROR
#endif
#define PD_CHECK(COND, ...) \
do { \
if (PD_UNLIKELY(!(COND))) { \
auto __message__ = ::paddle::ErrorMessage(__VA_ARGS__).to_string(); \
throw ::paddle::PD_Exception(__message__, __FILE__, __LINE__, \
"Expected " #COND \
", but it's not satisfied."); \
} \
} while (0)
#define PD_THROW(...) \
do { \
auto __message__ = ::paddle::ErrorMessage(__VA_ARGS__).to_string(); \
throw ::paddle::PD_Exception(__message__, __FILE__, __LINE__, \
"An error occured."); \
} while (0)
} // namespace paddle

View File

@ -0,0 +1,381 @@
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <boost/any.hpp>
#include "ext_dll_decl.h" // NOLINT
#include "ext_exception.h" // NOLINT
#include "ext_tensor.h" // NOLINT
/**
* Op Meta Info Related Define.
*
* Used to maintain operator core information.
*
*/
namespace paddle {
namespace framework {
class PD_DLL_DECL OpMetaInfoHelper;
} // namespace framework
using Tensor = paddle::Tensor;
///////////////// Util Marco Define ////////////////
#define PD_DISABLE_COPY_AND_ASSIGN(classname) \
private: \
classname(const classname&) = delete; \
classname(classname&&) = delete; \
classname& operator=(const classname&) = delete; \
classname& operator=(classname&&) = delete
#define STATIC_ASSERT_GLOBAL_NAMESPACE(uniq_name, msg) \
struct __test_global_namespace_##uniq_name##__ {}; \
static_assert(std::is_same<::__test_global_namespace_##uniq_name##__, \
__test_global_namespace_##uniq_name##__>::value, \
msg)
///////////////// Util Define and Function ////////////////
inline std::string Grad(const std::string& var_name) {
std::string result;
result.reserve(var_name.size() + 5U);
result += var_name;
result += "@GRAD";
return result;
}
////////////////////// Kernel Function (PD_KERNEL) ////////////////////////
// Record Op kernel core function
using KernelFunc = std::vector<Tensor> (*)(std::vector<Tensor> inputs,
std::vector<boost::any> attrs);
#define PD_SPECIALIZE_ComputeCallHelper(attr_type) \
template <typename... Tail> \
struct ComputeCallHelper<attr_type, Tail...> { \
template <int in_idx, int attr_idx, typename... PreviousArgs> \
static Return Compute(std::vector<Tensor> inputs, \
std::vector<boost::any> attrs, \
const PreviousArgs&... pargs) { \
try { \
attr_type arg = boost::any_cast<attr_type>(attrs[attr_idx]); \
return ComputeCallHelper<Tail...>::template Compute<in_idx, \
attr_idx + 1>( \
inputs, attrs, pargs..., arg); \
} catch (boost::bad_any_cast&) { \
PD_THROW( \
"Attribute cast error in custom operator. Expected " #attr_type \
" value."); \
} \
} \
}
template <typename T>
struct TypeTag {};
template <typename F, F f>
struct KernelFuncImpl;
template <typename Return, typename... Args, Return (*impl_fn)(Args...)>
struct KernelFuncImpl<Return (*)(Args...), impl_fn> {
static Return Compute(std::vector<Tensor> inputs,
std::vector<boost::any> attrs) {
return ComputeCallHelper<Args..., TypeTag<int>>::template Compute<0, 0>(
inputs, attrs);
}
private:
template <typename... RemainingArgs>
struct ComputeCallHelper;
// for Tensor input
template <typename... Tail>
struct ComputeCallHelper<const Tensor&, Tail...> {
template <int in_idx, int attr_idx, typename... PreviousArgs>
static Return Compute(std::vector<Tensor> inputs,
std::vector<boost::any> attrs,
const PreviousArgs&... pargs) {
static_assert(attr_idx == 0,
"Input tensor should appear before attributes.");
const Tensor& arg = inputs[in_idx];
return ComputeCallHelper<Tail...>::template Compute<in_idx + 1, attr_idx>(
inputs, attrs, pargs..., arg);
}
};
PD_SPECIALIZE_ComputeCallHelper(bool);
PD_SPECIALIZE_ComputeCallHelper(int);
PD_SPECIALIZE_ComputeCallHelper(float);
PD_SPECIALIZE_ComputeCallHelper(int64_t);
PD_SPECIALIZE_ComputeCallHelper(std::string);
PD_SPECIALIZE_ComputeCallHelper(std::vector<int>);
PD_SPECIALIZE_ComputeCallHelper(std::vector<float>);
PD_SPECIALIZE_ComputeCallHelper(std::vector<int64_t>);
PD_SPECIALIZE_ComputeCallHelper(std::vector<std::string>);
// TODO(chenweihang): support other attribute type if needed.
// Why not support other attribute type here?
// - boost::blank, std::vector<bool> and std::vector<double>
// are not used in op
// - BlockDesc* and std::vector<BlockDesc*> are used in framework
// end: base template
template <typename T>
struct ComputeCallHelper<TypeTag<T>> {
template <int in_idx, int attr_idx>
static Return Compute(std::vector<Tensor> inputs,
std::vector<boost::any> attrs, const Args&... args) {
return impl_fn(args...);
}
};
};
#define PD_KERNEL(...) \
::paddle::KernelFuncImpl<decltype(&__VA_ARGS__), &__VA_ARGS__>::Compute
/////////////// InferShape Function (PD_INFER_SHAPE) ///////////////
// Record Op infershape core function
using InferShapeFunc = std::vector<std::vector<int64_t>> (*)(
std::vector<std::vector<int64_t>> input_shapes);
template <typename F, F f>
struct InferShapeFuncImpl;
template <typename Return, typename... Args, Return (*impl_fn)(Args...)>
struct InferShapeFuncImpl<Return (*)(Args...), impl_fn> {
static Return InferShape(std::vector<std::vector<int64_t>> input_shapes) {
return InferShapeCallHelper<Args..., TypeTag<int>>::template InferShape<0>(
input_shapes);
}
private:
template <typename... RemainingArgs>
struct InferShapeCallHelper;
// only one type input: std::vector<int64_t>
template <typename... Tail>
struct InferShapeCallHelper<std::vector<int64_t>, Tail...> {
template <int in_idx, typename... PreviousArgs>
static Return InferShape(std::vector<std::vector<int64_t>> input_shapes,
const PreviousArgs&... pargs) {
std::vector<int64_t> arg = input_shapes[in_idx];
return InferShapeCallHelper<Tail...>::template InferShape<in_idx + 1>(
input_shapes, pargs..., arg);
}
};
// end: base template
template <typename T>
struct InferShapeCallHelper<TypeTag<T>> {
template <int in_idx>
static Return InferShape(std::vector<std::vector<int64_t>> input_shapes,
const Args&... args) {
return impl_fn(args...);
}
};
};
#define PD_INFER_SHAPE(...) \
::paddle::InferShapeFuncImpl<decltype(&__VA_ARGS__), &__VA_ARGS__>::InferShape
/////////////// InferDataType Function (PD_INFER_DTYPE) ///////////////
// Record Op Infer dtype core function
using InferDtypeFunc =
std::vector<DataType> (*)(std::vector<DataType> input_dtypes);
template <typename F, F f>
struct InferDtypeFuncImpl;
template <typename Return, typename... Args, Return (*impl_fn)(Args...)>
struct InferDtypeFuncImpl<Return (*)(Args...), impl_fn> {
static Return InferDtype(std::vector<DataType> input_dtypes) {
return InferDtypeCallHelper<Args..., TypeTag<int>>::template InferDtype<0>(
input_dtypes);
}
private:
template <typename... RemainingArgs>
struct InferDtypeCallHelper;
// Only one type input now: DataType
template <typename... Tail>
struct InferDtypeCallHelper<DataType, Tail...> {
template <int in_idx, typename... PreviousArgs>
static Return InferDtype(std::vector<DataType> input_dtypes,
const PreviousArgs&... pargs) {
DataType arg = input_dtypes[in_idx];
return InferDtypeCallHelper<Tail...>::template InferDtype<in_idx + 1>(
input_dtypes, pargs..., arg);
}
};
// end: base template
template <typename T>
struct InferDtypeCallHelper<TypeTag<T>> {
template <int in_idx>
static Return InferDtype(std::vector<DataType> input_dtypes,
const Args&... args) {
return impl_fn(args...);
}
};
};
#define PD_INFER_DTYPE(...) \
::paddle::InferDtypeFuncImpl<decltype(&__VA_ARGS__), &__VA_ARGS__>::InferDtype
////////////////////// Op Meta Info //////////////////////
class PD_DLL_DECL OpMetaInfo {
public:
explicit OpMetaInfo(const std::string& op_name) : name_(op_name) {}
// format: {"<name1>", "<name2>", ...}
OpMetaInfo& Inputs(std::vector<std::string>&& inputs);
// format: {"<name1>", "<name2>", ...}
OpMetaInfo& Outputs(std::vector<std::string>&& outputs);
// format: {"<name1>:<type1>", "<name1>:<type1>", ...}
OpMetaInfo& Attrs(std::vector<std::string>&& attrs);
// format: PD_KERNEL(...)
OpMetaInfo& SetKernelFn(KernelFunc&& func);
// format: PD_INFER_SHAPE(...)
OpMetaInfo& SetInferShapeFn(InferShapeFunc&& func);
// format: PD_INFER_DTYPE(...)
OpMetaInfo& SetInferDtypeFn(InferDtypeFunc&& func);
private:
friend class framework::OpMetaInfoHelper;
// 1. desc info
std::string name_;
std::vector<std::string> inputs_;
std::vector<std::string> outputs_;
std::vector<std::string> attrs_;
// 2. func info
KernelFunc kernel_fn_{nullptr};
InferShapeFunc infer_shape_fn_{nullptr};
InferDtypeFunc infer_dtype_fn_{nullptr};
};
//////////////// Op Meta Info Map /////////////////
class PD_DLL_DECL OpMetaInfoMap {
public:
// this function's impl should keep in header file.
// if move to cc file, meta info can not be added
// into map
static OpMetaInfoMap& Instance() {
static OpMetaInfoMap g_custom_op_meta_info_map;
return g_custom_op_meta_info_map;
}
std::vector<OpMetaInfo>& operator[](const std::string& name);
const std::unordered_map<std::string, std::vector<OpMetaInfo>>& GetMap()
const;
private:
OpMetaInfoMap() = default;
std::unordered_map<std::string, std::vector<OpMetaInfo>> map_;
PD_DISABLE_COPY_AND_ASSIGN(OpMetaInfoMap);
};
//////////////// Op Meta Info Builder /////////////////
class PD_DLL_DECL OpMetaInfoBuilder {
public:
explicit OpMetaInfoBuilder(std::string&& name, size_t index);
OpMetaInfoBuilder& Inputs(std::vector<std::string>&& inputs);
OpMetaInfoBuilder& Outputs(std::vector<std::string>&& outputs);
OpMetaInfoBuilder& Attrs(std::vector<std::string>&& attrs);
OpMetaInfoBuilder& SetKernelFn(KernelFunc func);
OpMetaInfoBuilder& SetInferShapeFn(InferShapeFunc func);
OpMetaInfoBuilder& SetInferDtypeFn(InferDtypeFunc func);
private:
// Forward Op name
std::string name_;
// ref current info ptr
OpMetaInfo* info_ptr_;
// The current op meta info index in vector
// - 0: op, 1: grad_op, 2: grad_grad_op
size_t index_;
};
/////////////////////// Op register API /////////////////////////
// For inference: compile directly with framework
// Call after PD_BUILD_OP(...)
void RegisterAllCustomOperator();
// Using this api to load compiled custom operator's dynamic library and
// register Custom
// Operator into it
void LoadCustomOperatorLib(const std::string& dso_name);
/////////////////////// Op register Macro /////////////////////////
#define PD_BUILD_OP(op_name) \
STATIC_ASSERT_GLOBAL_NAMESPACE( \
__reg_op__##op_name, "PD_BUILD_OP must be called in global namespace."); \
static ::paddle::OpMetaInfoBuilder __op_meta_info_##op_name##__ = \
::paddle::OpMetaInfoBuilder(#op_name, 0)
#define PD_BUILD_GRAD_OP(op_name) \
STATIC_ASSERT_GLOBAL_NAMESPACE( \
__reg_grad_op__##op_name, \
"PD_BUILD_GRAD_OP must be called in global namespace."); \
static ::paddle::OpMetaInfoBuilder __grad_op_meta_info_##op_name##__ = \
::paddle::OpMetaInfoBuilder(#op_name, 1)
#define PD_BUILD_DOUBLE_GRAD_OP(op_name) \
STATIC_ASSERT_GLOBAL_NAMESPACE( \
__reg_grad_grad_op__##op_name, \
"PD_BUILD_DOUBLE_GRAD_OP must be called in global namespace."); \
static ::paddle::OpMetaInfoBuilder __grad_grad_op_meta_info_##op_name##__ = \
::paddle::OpMetaInfoBuilder(#op_name, 2)
} // namespace paddle
///////////////////// C API ///////////////////
#ifdef __cplusplus
extern "C" {
#endif
#if defined(_WIN32)
// C-API to get global OpMetaInfoMap.
__declspec(dllexport) inline paddle::OpMetaInfoMap& PD_GetOpMetaInfoMap() {
return paddle::OpMetaInfoMap::Instance();
}
#endif // _WIN32
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,22 @@
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
namespace paddle {
// TODO(yangjiabin): Add other place support in next PR
enum class PlaceType { kUNK = -1, kCPU, kGPU };
} // namespace paddle

View File

@ -0,0 +1,125 @@
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <memory>
#include <vector>
#ifdef PADDLE_WITH_CUDA
#include <cuda_runtime.h>
#endif
#include "ext_dll_decl.h" // NOLINT
#include "ext_dtype.h" // NOLINT
#include "ext_place.h" // NOLINT
namespace paddle {
namespace framework {
class CustomTensorUtils;
} // namespace framework
class StreamWrapper {
public:
StreamWrapper() : stream_(nullptr), is_stream_set_(false) {}
void SetStream(void* stream) {
stream_ = stream;
is_stream_set_ = true;
}
void* GetStream() const { return stream_; }
bool IsStreamSet() const { return is_stream_set_; }
private:
// cudaStream_t stream_;
void* stream_;
bool is_stream_set_;
};
class PD_DLL_DECL Tensor {
public:
/// \brief Construct a Tensor on target Place for CustomOp.
/// Generally it's only used for user to create Tensor.
explicit Tensor(const PlaceType& place);
/// \brief Reset the shape of the tensor.
/// Generally it's only used for the input tensor.
/// Reshape must be called before calling
/// mutable_data() or copy_to(const PlaceType& place)
/// \param shape The shape to set.
void reshape(const std::vector<int64_t>& shape);
/// \brief Get the memory pointer in CPU or GPU with
/// specific data type.
/// Please Reshape the tensor first before call this.
/// It's usually used to get input data pointer.
/// \param place The place of the tensor this will
/// override the original place of current tensor.
template <typename T>
T* mutable_data(const PlaceType& place);
/// \brief Get the memory pointer in CPU or GPU with
/// specific data type. Please Reshape the tensor
/// first before call this.It's usually used to get
/// input data pointer.
template <typename T>
T* mutable_data();
/// \brief Get the memory pointer directly.
/// It's usually used to get the output data pointer.
/// \return The tensor data buffer pointer.
template <typename T>
T* data() const;
/// \brief Copy the host memory to tensor data.
/// It's usually used to set the input tensor data.
/// \param PlaceType of target place, of which
/// the tensor will copy to.
template <typename T>
Tensor copy_to(const PlaceType& place) const;
/// \brief Return the shape of the Tensor.
std::vector<int64_t> shape() const;
/// \brief Return the data type of the tensor.
/// It's usually used to get the output tensor data type.
/// \return The data type of the tensor.
DataType type() const;
/// \brief Get the size of current tensor.
/// Use this method to get the size of tensor
/// \return int64_t.
int64_t size() const;
/// \brief Get the place of current tensor.
/// Use this method to get the place of tensor
/// \return Place.
const PlaceType& place() const;
/// \brief Cast datatype from one to another
Tensor cast(const DataType& target_type) const;
#ifdef PADDLE_WITH_CUDA
/// \bref Get current stream of Tensor
cudaStream_t stream() const;
#endif
private:
friend class framework::CustomTensorUtils;
mutable std::shared_ptr<void> tensor_;
mutable PlaceType place_;
StreamWrapper stream_;
};
} // namespace paddle

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,680 @@
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///
/// \file paddle_analysis_config.h
///
/// \brief Paddle Analysis Config API信息
///
/// \author paddle-infer@baidu.com
/// \date 2020-03-20
/// \since 1.7
///
#pragma once
#include <cassert>
#include <map>
#include <memory>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "paddle_infer_declare.h" // NOLINT
/*! \file */
// Here we include some header files with relative paths, for that in deploy,
// the abstract path of this header file will be changed.
#include "paddle_api.h" // NOLINT
#include "paddle_pass_builder.h" // NOLINT
#ifdef PADDLE_WITH_MKLDNN
#include "paddle_mkldnn_quantizer_config.h" // NOLINT
#endif
namespace paddle {
class AnalysisPredictor;
struct MkldnnQuantizerConfig;
///
/// \brief configuration manager for AnalysisPredictor.
/// \since 1.7.0
///
/// AnalysisConfig manages configurations of AnalysisPredictor.
/// During inference procedure, there are many parameters(model/params path,
/// place of inference, etc.)
/// to be specified, and various optimizations(subgraph fusion, memory
/// optimazation, TensorRT engine, etc.)
/// to be done. Users can manage these settings by creating and modifying an
/// AnalysisConfig,
/// and loading it into AnalysisPredictor.
///
struct PD_INFER_DECL AnalysisConfig {
AnalysisConfig() = default;
///
/// \brief Construct a new AnalysisConfig from another
/// AnalysisConfig.
///
/// \param[in] other another AnalysisConfig
///
explicit AnalysisConfig(const AnalysisConfig& other);
///
/// \brief Construct a new AnalysisConfig from a no-combined model.
///
/// \param[in] model_dir model directory of the no-combined model.
///
explicit AnalysisConfig(const std::string& model_dir);
///
/// \brief Construct a new AnalysisConfig from a combined model.
///
/// \param[in] prog_file model file path of the combined model.
/// \param[in] params_file params file path of the combined model.
///
explicit AnalysisConfig(const std::string& prog_file,
const std::string& params_file);
///
/// \brief Precision of inference in TensorRT.
///
enum class Precision {
kFloat32 = 0, ///< fp32
kInt8, ///< int8
kHalf, ///< fp16
};
///
/// \brief Set the no-combined model dir path.
///
/// \param model_dir model dir path.
///
void SetModel(const std::string& model_dir) { model_dir_ = model_dir; }
///
/// \brief Set the combined model with two specific pathes for program and
/// parameters.
///
/// \param prog_file_path model file path of the combined model.
/// \param params_file_path params file path of the combined model.
///
void SetModel(const std::string& prog_file_path,
const std::string& params_file_path);
///
/// \brief Set the model file path of a combined model.
///
/// \param x model file path.
///
void SetProgFile(const std::string& x) { prog_file_ = x; }
///
/// \brief Set the params file path of a combined model.
///
/// \param x params file path.
///
void SetParamsFile(const std::string& x) { params_file_ = x; }
///
/// \brief Set the path of optimization cache directory.
///
/// \param opt_cache_dir the path of optimization cache directory.
///
void SetOptimCacheDir(const std::string& opt_cache_dir) {
opt_cache_dir_ = opt_cache_dir;
}
///
/// \brief Get the model directory path.
///
/// \return const std::string& The model directory path.
///
const std::string& model_dir() const { return model_dir_; }
///
/// \brief Get the program file path.
///
/// \return const std::string& The program file path.
///
const std::string& prog_file() const { return prog_file_; }
///
/// \brief Get the combined parameters file.
///
/// \return const std::string& The combined parameters file.
///
const std::string& params_file() const { return params_file_; }
// Padding related.
///
/// \brief Turn off FC Padding.
///
///
void DisableFCPadding();
///
/// \brief A boolean state telling whether fc padding is used.
///
/// \return bool Whether fc padding is used.
///
bool use_fc_padding() const { return use_fc_padding_; }
// GPU related.
///
/// \brief Turn on GPU.
///
/// \param memory_pool_init_size_mb initial size of the GPU memory pool in MB.
/// \param device_id device_id the GPU card to use (default is 0).
///
void EnableUseGpu(uint64_t memory_pool_init_size_mb, int device_id = 0);
///
/// \brief Turn off GPU.
///
///
void DisableGpu();
void EnableXpu(int l3_workspace_size = 0xfffc00);
///
/// \brief A boolean state telling whether the GPU is turned on.
///
/// \return bool Whether the GPU is turned on.
///
bool use_gpu() const { return use_gpu_; }
///
/// \brief A boolean state telling whether the XPU is turned on.
///
/// \return bool Whether the XPU is turned on.
///
bool use_xpu() const { return use_xpu_; }
///
/// \brief Get the GPU device id.
///
/// \return int The GPU device id.
///
int gpu_device_id() const { return gpu_device_id_; }
///
/// \brief Get the XPU device id.
///
/// \return int The XPU device id.
///
int xpu_device_id() const { return xpu_device_id_; }
///
/// \brief Get the initial size in MB of the GPU memory pool.
///
/// \return int The initial size in MB of the GPU memory pool.
///
int memory_pool_init_size_mb() const { return memory_pool_init_size_mb_; }
///
/// \brief Get the proportion of the initial memory pool size compared to the
/// device.
///
/// \return float The proportion of the initial memory pool size.
///
float fraction_of_gpu_memory_for_pool() const;
// CUDNN related.
///
/// \brief Turn on CUDNN.
///
///
void EnableCUDNN();
///
/// \brief A boolean state telling whether to use CUDNN.
///
/// \return bool Whether to use CUDNN.
///
bool cudnn_enabled() const { return use_cudnn_; }
///
/// \brief Control whether to perform IR graph optimization.
/// If turned off, the AnalysisConfig will act just like a NativeConfig.
///
/// \param x Whether the ir graph optimization is actived.
///
void SwitchIrOptim(int x = true) { enable_ir_optim_ = x; }
///
/// \brief A boolean state telling whether the ir graph optimization is
/// actived.
///
/// \return bool Whether to use ir graph optimization.
///
bool ir_optim() const { return enable_ir_optim_; }
///
/// \brief INTERNAL Determine whether to use the feed and fetch operators.
/// Just for internal development, not stable yet.
/// When ZeroCopyTensor is used, this should be turned off.
///
/// \param x Whether to use the feed and fetch operators.
///
void SwitchUseFeedFetchOps(int x = true) { use_feed_fetch_ops_ = x; }
///
/// \brief A boolean state telling whether to use the feed and fetch
/// operators.
///
/// \return bool Whether to use the feed and fetch operators.
///
bool use_feed_fetch_ops_enabled() const { return use_feed_fetch_ops_; }
///
/// \brief Control whether to specify the inputs' names.
/// The ZeroCopyTensor type has a name member, assign it with the
/// corresponding
/// variable name. This is used only when the input ZeroCopyTensors passed to
/// the
/// AnalysisPredictor.ZeroCopyRun() cannot follow the order in the training
/// phase.
///
/// \param x Whether to specify the inputs' names.
///
void SwitchSpecifyInputNames(bool x = true) { specify_input_name_ = x; }
///
/// \brief A boolean state tell whether the input ZeroCopyTensor names
/// specified should
/// be used to reorder the inputs in AnalysisPredictor.ZeroCopyRun().
///
/// \return bool Whether to specify the inputs' names.
///
bool specify_input_name() const { return specify_input_name_; }
///
/// \brief Turn on the TensorRT engine.
/// The TensorRT engine will accelerate some subgraphes in the original Fluid
/// computation graph. In some models such as resnet50, GoogleNet and so on,
/// it gains significant performance acceleration.
///
/// \param workspace_size The memory size(in byte) used for TensorRT
/// workspace.
/// \param max_batch_size The maximum batch size of this prediction task,
/// better set as small as possible for less performance loss.
/// \param min_subgrpah_size The minimum TensorRT subgraph size needed, if a
/// subgraph is smaller than this, it will not be transferred to TensorRT
/// engine.
/// \param precision The precision used in TensorRT.
/// \param use_static Serialize optimization information to disk for reusing.
/// \param use_calib_mode Use TRT int8 calibration(post training
/// quantization).
///
///
void EnableTensorRtEngine(int workspace_size = 1 << 20,
int max_batch_size = 1, int min_subgraph_size = 3,
Precision precision = Precision::kFloat32,
bool use_static = false,
bool use_calib_mode = true);
///
/// \brief A boolean state telling whether the TensorRT engine is used.
///
/// \return bool Whether the TensorRT engine is used.
///
bool tensorrt_engine_enabled() const { return use_tensorrt_; }
///
/// \brief Set min, max, opt shape for TensorRT Dynamic shape mode.
/// \param min_input_shape The min input shape of the subgraph input.
/// \param max_input_shape The max input shape of the subgraph input.
/// \param opt_input_shape The opt input shape of the subgraph input.
/// \param disable_trt_plugin_fp16 Setting this parameter to true means that
/// TRT plugin will not run fp16.
///
void SetTRTDynamicShapeInfo(
std::map<std::string, std::vector<int>> min_input_shape,
std::map<std::string, std::vector<int>> max_input_shape,
std::map<std::string, std::vector<int>> optim_input_shape,
bool disable_trt_plugin_fp16 = false);
///
/// \brief Prevent ops running in Paddle-TRT
/// NOTE: just experimental, not an official stable API, easy to be broken.
///
void Exp_DisableTensorRtOPs(const std::vector<std::string>& ops);
///
/// \brief Replace some TensorRT plugins to TensorRT OSS(
/// https://github.com/NVIDIA/TensorRT), with which some models's inference
/// may be more high-performance. Libnvinfer_plugin.so greater than
/// V7.2.1 is needed.
///
void EnableTensorRtOSS();
///
/// \brief A boolean state telling whether to use the TensorRT OSS.
///
/// \return bool Whether to use the TensorRT OSS.
///
bool tensorrt_oss_enabled() { return trt_use_oss_; }
///
/// \brief Enable TensorRT DLA
/// \param dla_core ID of DLACore, which should be 0, 1,
/// ..., IBuilder.getNbDLACores() - 1
///
void EnableTensorRtDLA(int dla_core = 0);
///
/// \brief A boolean state telling whether to use the TensorRT DLA.
///
/// \return bool Whether to use the TensorRT DLA.
///
bool tensorrt_dla_enabled() { return trt_use_dla_; }
///
/// \brief Turn on the usage of Lite sub-graph engine.
///
/// \param precision_mode Precion used in Lite sub-graph engine.
/// \param passes_filter Set the passes used in Lite sub-graph engine.
/// \param ops_filter Operators not supported by Lite.
///
void EnableLiteEngine(
AnalysisConfig::Precision precision_mode = Precision::kFloat32,
bool zero_copy = false,
const std::vector<std::string>& passes_filter = {},
const std::vector<std::string>& ops_filter = {});
///
/// \brief A boolean state indicating whether the Lite sub-graph engine is
/// used.
///
/// \return bool whether the Lite sub-graph engine is used.
///
bool lite_engine_enabled() const { return use_lite_; }
///
/// \brief Control whether to debug IR graph analysis phase.
/// This will generate DOT files for visualizing the computation graph after
/// each analysis pass applied.
///
/// \param x whether to debug IR graph analysis phase.
///
void SwitchIrDebug(int x = true);
///
/// \brief Turn on MKLDNN.
///
///
void EnableMKLDNN();
///
/// \brief Set the cache capacity of different input shapes for MKLDNN.
/// Default value 0 means not caching any shape.
/// Please see MKL-DNN Data Caching Design Document:
/// https://github.com/PaddlePaddle/FluidDoc/blob/develop/doc/fluid/design/mkldnn/caching/caching.md
///
/// \param capacity The cache capacity.
///
void SetMkldnnCacheCapacity(int capacity);
///
/// \brief A boolean state telling whether to use the MKLDNN.
///
/// \return bool Whether to use the MKLDNN.
///
bool mkldnn_enabled() const { return use_mkldnn_; }
///
/// \brief Set the number of cpu math library threads.
///
/// \param cpu_math_library_num_threads The number of cpu math library
/// threads.
///
void SetCpuMathLibraryNumThreads(int cpu_math_library_num_threads);
///
/// \brief An int state telling how many threads are used in the CPU math
/// library.
///
/// \return int The number of threads used in the CPU math library.
///
int cpu_math_library_num_threads() const {
return cpu_math_library_num_threads_;
}
///
/// \brief Transform the AnalysisConfig to NativeConfig.
///
/// \return NativeConfig The NativeConfig transformed.
///
NativeConfig ToNativeConfig() const;
///
/// \brief Specify the operator type list to use MKLDNN acceleration.
///
/// \param op_list The operator type list.
///
void SetMKLDNNOp(std::unordered_set<std::string> op_list) {
mkldnn_enabled_op_types_ = op_list;
}
///
/// \brief Turn on MKLDNN quantization.
///
///
void EnableMkldnnQuantizer();
///
/// \brief Turn on MKLDNN bfloat16.
///
///
void EnableMkldnnBfloat16();
///
/// \brief A boolean state telling whether to use the MKLDNN Bfloat16.
///
/// \return bool Whether to use the MKLDNN Bfloat16.
///
bool mkldnn_bfloat16_enabled() const { return use_mkldnn_bfloat16_; }
/// \brief Specify the operator type list to use Bfloat16 acceleration.
///
/// \param op_list The operator type list.
///
void SetBfloat16Op(std::unordered_set<std::string> op_list) {
bfloat16_enabled_op_types_ = op_list;
}
///
/// \brief A boolean state telling whether the thread local CUDA stream is
/// enabled.
///
/// \return bool Whether the thread local CUDA stream is enabled.
///
bool thread_local_stream_enabled() const { return thread_local_stream_; }
///
/// \brief A boolean state telling whether the MKLDNN quantization is enabled.
///
/// \return bool Whether the MKLDNN quantization is enabled.
///
bool mkldnn_quantizer_enabled() const { return use_mkldnn_quantizer_; }
///
/// \brief Get MKLDNN quantizer config.
///
/// \return MkldnnQuantizerConfig* MKLDNN quantizer config.
///
MkldnnQuantizerConfig* mkldnn_quantizer_config() const;
///
/// \brief Specify the memory buffer of program and parameter.
/// Used when model and params are loaded directly from memory.
///
/// \param prog_buffer The memory buffer of program.
/// \param prog_buffer_size The size of the model data.
/// \param params_buffer The memory buffer of the combined parameters file.
/// \param params_buffer_size The size of the combined parameters data.
///
void SetModelBuffer(const char* prog_buffer, size_t prog_buffer_size,
const char* params_buffer, size_t params_buffer_size);
///
/// \brief A boolean state telling whether the model is set from the CPU
/// memory.
///
/// \return bool Whether model and params are loaded directly from memory.
///
bool model_from_memory() const { return model_from_memory_; }
///
/// \brief Turn on memory optimize
/// NOTE still in development.
///
void EnableMemoryOptim();
///
/// \brief A boolean state telling whether the memory optimization is
/// activated.
///
/// \return bool Whether the memory optimization is activated.
///
bool enable_memory_optim() const;
///
/// \brief Turn on profiling report.
/// If not turned on, no profiling report will be generated.
///
void EnableProfile();
///
/// \brief A boolean state telling whether the profiler is activated.
///
/// \return bool Whether the profiler is activated.
///
bool profile_enabled() const { return with_profile_; }
///
/// \brief Mute all logs in Paddle inference.
///
void DisableGlogInfo();
///
/// \brief A boolean state telling whether logs in Paddle inference are muted.
///
/// \return bool Whether logs in Paddle inference are muted.
///
bool glog_info_disabled() const { return !with_glog_info_; }
///
/// \brief Set the AnalysisConfig to be invalid.
/// This is to ensure that an AnalysisConfig can only be used in one
/// AnalysisPredictor.
///
void SetInValid() const { is_valid_ = false; }
///
/// \brief A boolean state telling whether the AnalysisConfig is valid.
///
/// \return bool Whether the AnalysisConfig is valid.
///
bool is_valid() const { return is_valid_; }
friend class ::paddle::AnalysisPredictor;
///
/// \brief Get a pass builder for customize the passes in IR analysis phase.
/// NOTE: Just for developer, not an official API, easy to be broken.
///
///
PassStrategy* pass_builder() const;
///
/// \brief Enable the GPU multi-computing stream feature.
/// NOTE: The current behavior of this interface is to bind the computation
/// stream to the thread, and this behavior may be changed in the future.
///
void EnableGpuMultiStream();
void PartiallyRelease();
protected:
// Update the config.
void Update();
std::string SerializeInfoCache();
protected:
// Model pathes.
std::string model_dir_;
mutable std::string prog_file_;
mutable std::string params_file_;
// GPU related.
bool use_gpu_{false};
int gpu_device_id_{0};
int xpu_device_id_{0};
uint64_t memory_pool_init_size_mb_{100}; // initial size is 100MB.
bool use_cudnn_{false};
// Padding related
bool use_fc_padding_{true};
// TensorRT related.
bool use_tensorrt_{false};
// For workspace_size, refer it from here:
// https://docs.nvidia.com/deeplearning/sdk/tensorrt-developer-guide/index.html#troubleshooting
int tensorrt_workspace_size_{1 << 30};
// While TensorRT allows an engine optimized for a given max batch size
// to run at any smaller size, the performance for those smaller
// sizes may not be as well-optimized. Therefore, Max batch is best
// equivalent to the runtime batch size.
int tensorrt_max_batchsize_{1};
// We transform the Ops that can be converted into TRT layer in the model,
// and aggregate these Ops into subgraphs for TRT execution.
// We set this variable to control the minimum number of nodes in the
// subgraph, 3 as default value.
int tensorrt_min_subgraph_size_{3};
Precision tensorrt_precision_mode_{Precision::kFloat32};
bool trt_use_static_engine_{false};
bool trt_use_calib_mode_{true};
bool trt_use_oss_{false};
bool trt_use_dla_{false};
int trt_dla_core_{0};
std::map<std::string, std::vector<int>> min_input_shape_{};
std::map<std::string, std::vector<int>> max_input_shape_{};
std::map<std::string, std::vector<int>> optim_input_shape_{};
std::vector<std::string> trt_disabled_ops_{};
bool disable_trt_plugin_fp16_{false};
// memory reuse related.
bool enable_memory_optim_{false};
bool use_mkldnn_{false};
std::unordered_set<std::string> mkldnn_enabled_op_types_;
bool model_from_memory_{false};
bool enable_ir_optim_{true};
bool use_feed_fetch_ops_{true};
bool ir_debug_{false};
bool specify_input_name_{false};
int cpu_math_library_num_threads_{1};
bool with_profile_{false};
bool with_glog_info_{true};
// A runtime cache, shouldn't be transferred to others.
std::string serialized_info_cache_;
mutable std::unique_ptr<PassStrategy> pass_builder_;
bool use_lite_{false};
std::vector<std::string> lite_passes_filter_;
std::vector<std::string> lite_ops_filter_;
Precision lite_precision_mode_;
bool lite_zero_copy_;
bool thread_local_stream_{false};
bool use_xpu_{false};
int xpu_l3_workspace_size_;
// mkldnn related.
int mkldnn_cache_capacity_{0};
bool use_mkldnn_quantizer_{false};
std::shared_ptr<MkldnnQuantizerConfig> mkldnn_quantizer_config_;
bool use_mkldnn_bfloat16_{false};
std::unordered_set<std::string> bfloat16_enabled_op_types_;
// If the config is already used on a predictor, it becomes invalid.
// Any config can only be used with one predictor.
// Variables held by config can take up a lot of memory in some cases.
// So we release the memory when the predictor is set up.
mutable bool is_valid_{true};
std::string opt_cache_dir_;
};
} // namespace paddle

Some files were not shown because too many files have changed in this diff Show More