main.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. #include <main.h>
  2. //#include "userfunc.h"
  3. #include <cameramanager.h>
  4. #include <mqtthandler.h>
  5. #include <mserial.h>
  6. #include <mysql.h>
  7. #include <EasyTableModel.h>
  8. #include <customitem.h>
  9. #include <m_loger.h>
  10. #include <TreeModel.h>
  11. #include <app_curlFunc.h>
  12. #include <wif_service.h>
  13. #include <ethernet_service.h>
  14. #include <QProcess>
  15. #include <QVariantMap>
  16. #include <QQuickWindow>
  17. #include <app_credentials.h>
  18. #include <PermissionBridge.h>
  19. #include <logviewer.h>
  20. #include <oamanager.h>
  21. #include <systemmonitor.h>
  22. //uncomment this line to add the Live Client Module and use live reloading with your custom C++ code
  23. //#include <FelgoLiveClient>
  24. class param;
  25. QString param::table_mqtt = "mqtt"; //mqtt配置表
  26. QString param::table_mqtt_other = "mqtt_other"; //mqtt对接配置表
  27. QString param::table_ftp = "ftp"; //FTP配置表
  28. QString param::table_ftp_other = "ftp_other"; //FTP对接配置表
  29. QString param::table_camera = "camera"; //相机参数配置表
  30. QString param::table_location = "location"; //定位信息参数配置表
  31. QString param::table_config = "config"; //参数配置表
  32. void traverseQmlObject(QObject *qmlObject, int depth = 0) {
  33. QString indentation = QString(" ").repeated(depth);
  34. LOG("{}Type: {} Name: {}", indentation.toStdString(),
  35. qmlObject->metaObject()->className(),
  36. qmlObject->objectName().toStdString());
  37. for (QObject *child : qmlObject->children()) {
  38. traverseQmlObject(child, depth + 1);
  39. }
  40. }
  41. // 网口相机(GigE)链路配置:eth0 静态IP 192.168.100.101 + Jumbo帧(优先 MTU 9000)
  42. //
  43. // 【2026-09-30 重要调整:改用 EnjoySDK,不再依赖 su】
  44. // 之前用 shell 的 ifconfig + su 改网卡,现场反复失败,根因是:
  45. // 修改 MTU / 静态 IP 需要 CAP_NET_ADMIN,普通 app uid 进程一定被内核拒绝
  46. // (errno=EPERM,即 "Operation not permitted")。设备若未 root,su 也拿不到权限。
  47. // EnjoySDK 走的是系统 EthernetService(system uid),普通应用即可下发配置,无需 root,
  48. // 且由系统服务负责持久化 —— 这是本平台配置网卡的正确路径。
  49. //
  50. // 【关键约束:mode=STATIC 必须与 IP 一次性下发】
  51. // setEthernetConfig 会校验整个配置对象:静态模式下 IP/子网掩码必须合法,
  52. // 否则返回 ERR_CONFIG_INVALID = -101。
  53. // 所以不能"先只改 mode 提交一次、再填 IP 提交第二次"——第一次提交时 IP 还是
  54. // DHCP 遗留的 0.0.0.0,校验必然失败。正确做法见 EthernetService::setStaticIp。
  55. //
  56. // 【MTU 说明】
  57. // EnjoySDK 未提供 MTU 接口,Jumbo 帧仍需 ifconfig(依赖 root)。
  58. // 但 MTU 设不上去不是致命错误:GigE 在 MTU 1500 下仍可通信,仅大帧带宽利用率下降,
  59. // 因此 MTU 失败只 WARN,不影响整体配置结果。
  60. //
  61. // 【现场排查要点】
  62. // 1) 修改网卡 MTU / 静态 IP 需要 CAP_NET_ADMIN。日志里 ifconfig 报的错误码是 ioctl 请求的
  63. // 十六进制值,对照表:
  64. // 8914 = SIOCSIFFLAGS (down/up)
  65. // 8922 = SIOCSIFMTU (mtu)
  66. // 8916 = SIOCSIFADDR (ip/netmask)
  67. // 8915 = SIOCGIFADDR (读 ip)
  68. // - "Operation not permitted"(EPERM) => 进程缺 CAP_NET_ADMIN,即 su 没生效
  69. // (设备未 root / su 不存在 / 被 SELinux 拦)。判据是 errno 而非日志字面。
  70. // - "Invalid argument"(EINVAL) => 已经拿到 root,但驱动拒绝了该 ioctl 的参数。
  71. // 本平台的 sunxi-gmac 就是这种:设 MTU 9000 会被拒(硬件/驱动上限低于 9000)。
  72. // 这两种要分清:前者是无权限,后者是有权限但值不被支持,处理方式完全不同。
  73. //
  74. // 2) 静态 IP 是 GigE 相机能被搜到的前提,必须成功;失败时重试若干轮等待驱动/链路就绪。
  75. //
  76. // 【根治方式】(更推荐在系统侧配置,不依赖应用内 su)
  77. // 1) 静态 IP:Android 10 EthernetService 支持静态 IP 下发,
  78. // 在 /system/etc/ethernet/config.xml 为 eth0 增加 StaticIPSettings(192.168.100.101/24),
  79. // 由系统服务(system uid)完成,无需 root。
  80. // 2) Jumbo 帧:在 init.rc 或 /system/etc/init.d/ 开机脚本执行 ifconfig eth0 mtu <N>,
  81. // N 取该平台驱动实际支持的最大值。
  82. // 3) 必须应用内配置时,APK 需预置为系统应用(platform 签名 + sharedUserId)。
  83. static void setupEth0()
  84. {
  85. const QString kIface = QStringLiteral("eth0");
  86. const QString kIp = QStringLiteral("192.168.100.101");
  87. const QString kNetmask = QStringLiteral("255.255.255.0");
  88. // ================= 步骤 1:MTU 阶梯降级(EnjoySDK 无 MTU 接口,仍走 ifconfig)=================
  89. // 【顺序很重要】必须在设静态 IP **之前** 调 MTU:
  90. // ifconfig down/up 会把网卡重置,若先由 EnjoySDK 下发静态 IP 再改 MTU,
  91. // down/up 可能把刚下发的 IP 冲掉。故 MTU 在前、IP 在后。
  92. // MTU 只能在网卡 down 时改;驱动可能不支持 9000(返回 EINVAL),逐级下探取最大值。
  93. // 非致命:GigE 在 1500 下仍可通信,仅带宽利用率下降。
  94. int mtuApplied = 0;
  95. {
  96. QString mtuReason;
  97. const int kMtuCandidates[] = {9000, 4000, 2000, 1500};
  98. for (int mtu : kMtuCandidates) {
  99. const QVariantMap m = EthernetService().setMtu(kIface, mtu);
  100. mtuReason = m.value(QStringLiteral("msg")).toString();
  101. if (m.value(QStringLiteral("ok")).toBool()) {
  102. mtuApplied = mtu;
  103. break;
  104. }
  105. // 无 root → 整项跳过(MTU 只是可选的 Jumbo 帧优化,不影响 GigE 连通)
  106. // 驱动不支持该值(EINVAL) → 继续降档试;两种情况都不该刷报错
  107. if (m.value(QStringLiteral("skipped")).toBool()) {
  108. break;
  109. }
  110. }
  111. if (mtuApplied > 0) {
  112. LOG("setupEth0: MTU 已设置为 {}", mtuApplied);
  113. } else {
  114. // 不是致命问题:GigE 在 MTU 1500 下仍可通信,仅大帧带宽利用率下降
  115. LOG("setupEth0: MTU 未设置({}),GigE 仍可通信,仅大帧带宽受限",
  116. mtuReason.toStdString().c_str());
  117. }
  118. }
  119. // ================= 步骤 2:静态 IP 走 EnjoySDK(主路径,无需 root)=================
  120. // 注意:静态 IP 是 GigE 搜到相机的前提,必须成功。
  121. // 放在 MTU 之后,避免被 ifconfig down/up 冲掉(见步骤 1 说明)。
  122. bool okIp = false;
  123. {
  124. EthernetService eth;
  125. if (!eth.isSupported()) {
  126. WARN("setupEth0: 当前平台不支持 EnjoySDK,静态IP 未能下发。"
  127. "请改走 /system/etc/ethernet/config.xml 的 StaticIPSettings。");
  128. } else {
  129. // 一次性下发 mode=STATIC + IP(分两步提交会被系统拒 -101)
  130. const QVariantMap r = eth.setStaticIp(kIface, kIp, kNetmask, QString(), QString());
  131. if (r.value(QStringLiteral("ok")).toBool()) {
  132. okIp = true;
  133. LOG("setupEth0: EnjoySDK 配置静态IP 成功 {} on {} (方案={})",
  134. kIp.toStdString().c_str(), kIface.toStdString().c_str(),
  135. r.value(QStringLiteral("via")).toString().toStdString().c_str());
  136. // 若厂商服务强制要求网关/DNS,Java 侧会自动补一个同网段网关(.1)和公网 DNS。
  137. // 这会让 eth0 在系统看来是"有默认网关的网络",可能被选为默认网络,
  138. // 从而影响 MQTT/FTP 的出口 —— 必须显式提醒。
  139. if (r.value(QStringLiteral("via")).toString() == QStringLiteral("with-gateway")) {
  140. WARN("setupEth0: 静态配置使用了自动补的网关/DNS(厂商要求必填)。"
  141. "eth0 可能被系统选为默认网络,若 MQTT/FTP 异常请检查路由优先级。");
  142. }
  143. } else {
  144. ERROR("setupEth0: EnjoySDK 配置静态IP 失败 code={} msg={}",
  145. r.value(QStringLiteral("code")).toInt(),
  146. eth.lastError().toStdString().c_str());
  147. }
  148. }
  149. }
  150. // ================= 收尾:打印最终状态 =================
  151. if (!okIp) {
  152. ERROR("setupEth0: eth0 静态IP {} 未配置成功,GigE 相机可能搜不到。"
  153. "请检查 EthernetService 是否运行,或改用 /system/etc/ethernet/config.xml 下发静态IP。",
  154. kIp.toStdString().c_str());
  155. }
  156. {
  157. EthernetService eth;
  158. const QVariantMap st = eth.status(kIface);
  159. LOG("setupEth0: eth0 最终状态 IP配置={} 当前IP={} mode={} linkState={} | MTU={}",
  160. okIp ? "OK" : "FAIL",
  161. st.value(QStringLiteral("ip")).toString().toStdString().c_str(),
  162. st.value(QStringLiteral("mode")).toInt(),
  163. st.value(QStringLiteral("linkState")).toInt(),
  164. mtuApplied > 0 ? QString::number(mtuApplied).toStdString().c_str() : "默认");
  165. }
  166. }
  167. class MyCppClass : public QObject {
  168. Q_OBJECT
  169. public:
  170. void setQmlRootObject(QObject *rootObject) {
  171. m_qmlRootObject = rootObject;
  172. }
  173. void JumpToCamera(){
  174. }
  175. public slots:
  176. void qmlSlot() {
  177. LOG("Received from QML");
  178. emit recvqmlslot();
  179. }
  180. void systemPage(){
  181. LOG("systemPage");
  182. emit tosystempage();
  183. }
  184. void openbar_btnClicked(){
  185. LOG("openbar_btnClicked");
  186. emit opensystembar();
  187. }
  188. void closebar_btnClicked(){
  189. LOG("closebar_btnClicked");
  190. emit closesystembar();
  191. }
  192. void opennav_btnClicked(){
  193. LOG("opennav_btnClicked");
  194. emit opensystemnav();
  195. }
  196. void closenav_btnClicked(){
  197. LOG("closenav_btnClicked");
  198. emit closesystemnav();
  199. }
  200. signals:
  201. void recvqmlslot();
  202. void tosystempage();
  203. void opensystembar();
  204. void closesystembar();
  205. void opensystemnav();
  206. void closesystemnav();
  207. private:
  208. QObject *m_qmlRootObject = nullptr;
  209. };
  210. class GPSInfo : public QObject
  211. {
  212. Q_OBJECT
  213. public:
  214. double nowGroundSpeed=0.0;
  215. double nowVerticalSpeed=0.0;
  216. double nowMagneticVariation=0.0;
  217. double nowHorizontalAccuracy=0.0;
  218. double nowVerticalAccuracy=0.0;
  219. double nowLongitude=0.0;
  220. double nowLatitude=0.0;
  221. double nowDirection=0.0;
  222. double nowAltitude=0.0;
  223. QString nowTimes="";
  224. int recv_cnt = 0;
  225. QGeoPositionInfoSource *positionSource;
  226. //卫星信息源:给主页"定位信息"卡片提供 可视/已用卫星数
  227. //-1 表示尚未收到过卫星数据(QML 侧显示 --)
  228. QGeoSatelliteInfoSource *satelliteSource = nullptr;
  229. int nowSatInView = -1;
  230. int nowSatInUse = -1;
  231. public:
  232. GPSInfo(SqliteOperator *db,QObject *parent = nullptr)
  233. : QObject(parent) // 注入外部数据库对象
  234. , gpsConfig(db)
  235. {
  236. param::gps_state = "0";
  237. positionSource = QGeoPositionInfoSource::createDefaultSource(this);
  238. if (positionSource) {
  239. connect(positionSource, SIGNAL(positionUpdated(QGeoPositionInfo)),
  240. this, SLOT(positionUpdated(QGeoPositionInfo)));
  241. positionSource->setUpdateInterval(1000);//设置刷新时间 单位毫秒
  242. positionSource->startUpdates();//启动设备
  243. }
  244. //启用卫星信息源:可视/已用卫星数持续刷新(独立于定位源,不受定位停止影响;
  245. //面板为市电/蓄电池供电,持续GNSS监听功耗可接受)
  246. satelliteSource = QGeoSatelliteInfoSource::createDefaultSource(this);
  247. if (satelliteSource) {
  248. connect(satelliteSource, &QGeoSatelliteInfoSource::satellitesInViewUpdated,
  249. this, &GPSInfo::onSatellitesInView);
  250. connect(satelliteSource, &QGeoSatelliteInfoSource::satellitesInUseUpdated,
  251. this, &GPSInfo::onSatellitesInUse);
  252. satelliteSource->startUpdates();
  253. } else {
  254. LOG("QGeoSatelliteInfoSource 不可用,卫星数量将显示 --");
  255. }
  256. }
  257. signals:
  258. void position_success();
  259. private:
  260. SqliteOperator *gpsConfig = nullptr; // 不再在内部创建
  261. private slots://槽函数中实现了GPS部分信息的读取
  262. void onSatellitesInView(const QList<QGeoSatelliteInfo> &sats)
  263. {
  264. nowSatInView = sats.size();
  265. param::gps_sat_view = QString::number(nowSatInView);
  266. LOG("可视卫星数:{}",nowSatInView);
  267. }
  268. void onSatellitesInUse(const QList<QGeoSatelliteInfo> &sats)
  269. {
  270. nowSatInUse = sats.size();
  271. param::gps_sat_used = QString::number(nowSatInUse);
  272. LOG("已用卫星数:{}",nowSatInUse);
  273. }
  274. void positionUpdated(const QGeoPositionInfo &info)
  275. {
  276. nowLongitude = info.coordinate().longitude();//经度
  277. nowLatitude = info.coordinate().latitude();//纬度
  278. nowAltitude = info.coordinate().altitude();//海拔(米),无解算时为NaN
  279. nowDirection = info.attribute(QGeoPositionInfo::Direction);
  280. nowGroundSpeed = info.attribute(QGeoPositionInfo::GroundSpeed);
  281. nowVerticalSpeed = info.attribute(QGeoPositionInfo::VerticalSpeed);
  282. nowMagneticVariation = info.attribute(QGeoPositionInfo::MagneticVariation);
  283. nowHorizontalAccuracy = info.attribute(QGeoPositionInfo::HorizontalAccuracy);
  284. nowVerticalAccuracy = info.attribute(QGeoPositionInfo::VerticalAccuracy);
  285. nowTimes = info.timestamp().toString();
  286. //海拔仅在有效解算时写param,避免NaN污染显示;定位源停止后保持最后一次值
  287. if(qIsFinite(nowAltitude)){
  288. param::gps_elevation = QString::number(nowAltitude, 'f', 1);
  289. }
  290. if(param::gps_lat.contains(".")&&param::gps_lat.size()>3){
  291. param::gps_state = "1";
  292. recv_cnt++;
  293. if(recv_cnt==20){ //定位成功后120S把定位信息保存到数据库中
  294. emit position_success();
  295. gpsConfig->OpenDb();
  296. if(gpsConfig->isTableExist(param::table_location)){
  297. gpsConfig->UpdateData(param::table_location,"gps_lat",param::gps_lat);
  298. gpsConfig->UpdateData(param::table_location,"gps_lng",param::gps_lng);
  299. }
  300. gpsConfig->CloseDb();
  301. positionSource->stopUpdates();
  302. }
  303. }
  304. // 保留7位小数(约1厘米精度),避免QString::number默认6位有效数字把经纬度截断到小数点后3位
  305. param::gps_lat = QString::number(nowLatitude, 'f', 7);
  306. param::gps_lng = QString::number(nowLongitude, 'f', 7);
  307. LOG("经度:{:.7f}",nowLongitude);
  308. LOG("纬度:{:.7f}",nowLatitude);
  309. LOG("角度:{}",nowDirection);
  310. LOG("地表速度:{}",nowGroundSpeed);
  311. LOG("垂直速度:{}",nowVerticalSpeed);
  312. LOG("磁偏角:{}",nowMagneticVariation);
  313. LOG("水平精度:{}",nowHorizontalAccuracy);
  314. LOG("垂直精度:{}",nowVerticalAccuracy);
  315. LOG("定位次数:{}",recv_cnt);
  316. }
  317. };
  318. void sendBroadcastFromQt(QString btn_type) {
  319. auto qtContext = QJniObject(QNativeInterface::QAndroidApplication::context()); //activity
  320. //QJniObject qtContext = activity.callObjectMethod("getApplicationContext","()Landroid/content/Context;");
  321. if (qtContext.isValid()) {
  322. if(btn_type=="sleep"){
  323. QJniObject jClass("com/yfkj/bzyv1/Backlight");
  324. //jboolean ret = jClass.callMethod<jboolean>("checkWriteSettingPermission","(Landroid/content/Context;I)Z",qtContext.object(),100);
  325. jClass.callMethod<void>("setScreenLight","(Landroid/content/Context;I)V",qtContext.object(),100);
  326. }
  327. //QJniObject jClass("com/yfkj/bzyv1/StatusBarCtr");
  328. QJniObject jClass("com/yfkj/bzyv1/Backlight");
  329. if(btn_type=="openbar_btn"){
  330. jClass.callMethod<void>("setStatusBar","(Landroid/content/Context;I)V",qtContext.object(),1);
  331. }else if(btn_type=="closebar_btn"){
  332. jClass.callMethod<void>("setStatusBar","(Landroid/content/Context;I)V",qtContext.object(),0);
  333. }else if(btn_type=="closenav_btn"){
  334. jClass.callMethod<void>("setNavigationBar","(Landroid/content/Context;I)V",qtContext.object(),0);
  335. }else if(btn_type=="opennav_btn"){
  336. jClass.callMethod<void>("setNavigationBar","(Landroid/content/Context;I)V",qtContext.object(),1);
  337. }else if(btn_type=="imei"){
  338. QJniObject jClass("com/yfkj/bzyv1/StatusBarCtr");
  339. QJniObject java_imei= jClass.callObjectMethod("getAndroidIMEI","(Landroid/content/Context;)Ljava/lang/String;",qtContext.object());
  340. if(java_imei.isValid()){
  341. QString imei = java_imei.toString();
  342. if(!imei.isEmpty()&&param::imei.isEmpty()){
  343. param::imei = imei;
  344. }
  345. LOG("IMEI:{}",param::imei.toStdString());
  346. }
  347. }else if(btn_type=="csq"){
  348. jint rsrp = QJniObject::callStaticMethod<jint>("com/yfkj/bzyv1/StatusBarCtr",
  349. "getRsrp",
  350. "(Landroid/content/Context;)I",
  351. qtContext.object());
  352. LOG("getRsrp:{}",rsrp);
  353. }else if(btn_type=="iccid"){
  354. QJniObject jClass("com/yfkj/bzyv1/StatusBarCtr");
  355. QJniObject iccid_java = jClass.callObjectMethod("getICCID","(Landroid/content/Context;)Ljava/lang/String;",qtContext.object());
  356. if(iccid_java.isValid()){
  357. QString iccid = iccid_java.toString();
  358. if(!iccid.isEmpty()){
  359. param::iccid = iccid;
  360. }
  361. LOG("ICCID:{}",param::iccid.toStdString());
  362. }
  363. }else if(btn_type=="install"){
  364. QJniObject jClass("com/yfkj/bzyv1/StatusBarCtr");
  365. DEBUG("install process start!");
  366. jClass.callMethod<void>("installApp","(Landroid/content/Context;)V",qtContext.object());
  367. }else if(btn_type=="rebootSystem"){
  368. jClass.callMethod<void>("rebootSystem","(Landroid/content/Context;)V",qtContext.object());
  369. }else if(btn_type=="service"){
  370. DEBUG("启动android服务");
  371. QAndroidIntent serviceIntent(qtContext.object(),
  372. "com/yfkj/bzyv1/QtAndroidService");
  373. QJniObject result = qtContext.callObjectMethod(
  374. "startService",
  375. "(Landroid/content/Intent;)Landroid/content/ComponentName;",
  376. serviceIntent.handle().object());
  377. }
  378. }
  379. }
  380. // 定义函数:设置每日8:00重启的定时器
  381. auto setDailyRebootTimer = []() {
  382. // 获取当前时间(本地时间)
  383. QDateTime currentTime = QDateTime::currentDateTime();
  384. // 构造当天8:00的目标时间(基于本地时间的0点+8小时)
  385. QDateTime targetTime = currentTime.date().startOfDay().addSecs(8 * 3600); // 8:00 = 8 * 3600秒
  386. // 如果当前时间已过今日8:00,目标时间调整为次日8:00
  387. if (currentTime >= targetTime) {
  388. targetTime = targetTime.addDays(1); // 加1天
  389. }
  390. // 计算当前时间到目标时间的毫秒间隔
  391. qint64 intervalMs = currentTime.msecsTo(targetTime);
  392. // 设置单次定时器,触发后执行重启逻辑,并重新设置下一日的定时器
  393. QTimer::singleShot(intervalMs, []() {
  394. LOG("触发每日8:00重启");
  395. sendBroadcastFromQt("rebootSystem"); // 发送重启广播
  396. // 注意:若需要严格每日执行,建议在重启前重新设置定时器(根据实际需求)
  397. // 若系统重启后会自动启动本程序,可省略此处(程序重启后会重新设置定时器)
  398. // setDailyRebootTimer();
  399. });
  400. };
  401. //adb shell input keyevent 26 // 224 关
  402. // ========== 全志A133P缓存清理函数(关键)==========
  403. void clearAllCaches() {
  404. #ifndef WIN32
  405. QDir dir;
  406. // ========== 1. 标准缓存位置 ==========
  407. QStringList cacheLocations = {
  408. QStandardPaths::writableLocation(QStandardPaths::CacheLocation),
  409. QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation),
  410. // QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation),
  411. // QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
  412. };
  413. // ========== 2. Android特定缓存位置 ==========
  414. cacheLocations << QDir::homePath() + "/.cache";
  415. cacheLocations << QDir::homePath() + "/.local/share";
  416. // ========== 3. 所有需要清理的缓存目录 ==========
  417. QStringList cacheDirs = {
  418. "qmlsc", "qml", "rhi", "scenegraph", "shaders", "pipelines",
  419. "graphicsshadercache", "QtShaderCache", "QtQuick", "cache",
  420. "Qt", "shadercache", "textures", "graphics", "RenderCache",
  421. "ShaderCache", "TextureCache"
  422. };
  423. QStringList cacheFileFilters = {"*.qmlc", "*.jsc", "*.cache", "*.tmp"};
  424. // ========== 4. 遍历并清理 ==========
  425. for (const QString &cachePath : cacheLocations) {
  426. QDir cacheDir(cachePath);
  427. if (cacheDir.exists()) {
  428. DEBUG("Scanning cache location: {}", cachePath.toStdString());
  429. // 清理指定目录
  430. for (const QString &subDir : cacheDirs) {
  431. QDir sub(cacheDir.filePath(subDir));
  432. if (sub.exists()) {
  433. sub.removeRecursively();
  434. DEBUG("Cleared cache directory: {}", sub.absolutePath().toStdString());
  435. }
  436. }
  437. // 清理匹配的缓存文件
  438. cacheDir.setNameFilters(cacheFileFilters);
  439. QStringList files = cacheDir.entryList(QDir::Files);
  440. for (const QString &file : files) {
  441. cacheDir.remove(file);
  442. DEBUG("Removed cache file: {}", cacheDir.filePath(file).toStdString());
  443. }
  444. }
  445. }
  446. // ========== 5. 清理临时文件 ==========
  447. QDir tempDir(QDir::tempPath());
  448. if (tempDir.exists()) {
  449. QStringList filters;
  450. filters << "Qt*" << "qml*" << "shader*" << "rhi*";
  451. tempDir.setNameFilters(filters);
  452. QStringList tempFiles = tempDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  453. for (const QString &tempFile : tempFiles) {
  454. QFileInfo info(tempDir.filePath(tempFile));
  455. if (info.isDir()) {
  456. QDir(tempDir.filePath(tempFile)).removeRecursively();
  457. } else {
  458. tempDir.remove(tempFile);
  459. }
  460. DEBUG("Removed temp file/dir: {}", tempDir.filePath(tempFile).toStdString());
  461. }
  462. }
  463. DEBUG("All caches cleared successfully!");
  464. #endif
  465. }
  466. int main(int argc, char *argv[])
  467. {
  468. QtAndroidPrivate::checkPermission("android.permission.WRITE_EXTERNAL_STORAGE");
  469. QtAndroidPrivate::requestPermission("android.permission.WRITE_EXTERNAL_STORAGE");
  470. INITLOG();
  471. sendBroadcastFromQt("sleep");
  472. QGuiApplication app(argc, argv);
  473. // ========== 第二阶段:QGuiApplication创建后再次清理缓存 ==========
  474. // 有些缓存只有在QGuiApplication创建后才能正确访问
  475. clearAllCaches();
  476. LOG("Second cache clear completed!");
  477. // 注:setupEth0() 已移到 engine.load() 之后调用。
  478. // 原因:它现在走 EnjoySDK,需要 Android Context(由 QtAndroidActivity 持有),
  479. // 而 Context 只有在 Activity 创建后才可取;此处 QGuiApplication 刚建好、取不到。
  480. MyCppClass myCppClass;
  481. #if WIN32
  482. QString subDirPath = "logs/run_log.txt";
  483. QString appDataPath ="./";
  484. #else
  485. // 获取应用程序内部存储空间路径
  486. QString appDataPath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + BZY_APP_FILES_DIR;
  487. LOG("appDataPath:{}",appDataPath.toStdString());
  488. QString appPicPath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/Android/data/com.yfkj.bzyv1/files/Pictures";
  489. LOG("appPicPath:{}",appPicPath.toStdString());
  490. #endif
  491. sendBroadcastFromQt("iccid");
  492. sendBroadcastFromQt("csq");
  493. //创建并打开SQLite数据库
  494. QString db_config = "config.db";
  495. // QString db_data = "data.db";
  496. SqliteOperator *sqlConfig;
  497. sqlConfig = new SqliteOperator(db_config);
  498. sqlConfig->OpenDb();
  499. //判断数据表是否存在
  500. config_db_type config_class;
  501. if(!sqlConfig->isTableExist(param::table_mqtt)){
  502. sqlConfig->CreateTable(param::table_mqtt);
  503. //插入数据
  504. //【安全】凭据改由 app_credentials.h 统一提供,不再硬编码散落各处
  505. config_class.mqtt_db = {1,"bzy",CRED_MQTT_HOST,CRED_MQTT_PORT,"",
  506. CRED_MQTT_UID,CRED_MQTT_PWD,"",0,60,
  507. CRED_MQTT_SUB_PREFIX,CRED_MQTT_PUB_PREFIX,
  508. CRED_MQTT_OFF_PREFIX,10};
  509. sqlConfig->InsertData(config_class,param::table_mqtt);
  510. //查询全部数据
  511. sqlConfig->QueryAllData(param::table_mqtt);
  512. }else{
  513. sqlConfig->QueryAllData(param::table_mqtt);
  514. }
  515. if(param::imei.isEmpty()){
  516. sendBroadcastFromQt("imei");
  517. QTimer::singleShot(1000, [&]() {
  518. sqlConfig->OpenDb();
  519. if(sqlConfig->isTableExist(param::table_mqtt)){
  520. LOG("Update imei:{}",param::imei.toStdString());
  521. sqlConfig->UpdateData(param::table_mqtt,"imei",param::imei);
  522. }
  523. sqlConfig->CloseDb();
  524. });
  525. }
  526. if(!sqlConfig->isTableExist(param::table_mqtt_other))
  527. {
  528. sqlConfig->CreateTable(param::table_mqtt_other);
  529. config_class.mqtt_db = {1,"bzy","0.0.0.0",1883,"","uid","pwd","clientid",0,60,"/yfkj/bzy/s2c/","/yfkj/bzy/c2s/","/yfkj/bzy/offline/",10};
  530. sqlConfig->InsertData(config_class,param::table_mqtt_other);
  531. //查询全部数据
  532. sqlConfig->QueryAllData(param::table_mqtt_other);
  533. }else{
  534. sqlConfig->QueryAllData(param::table_mqtt_other);
  535. }
  536. if(!sqlConfig->isTableExist(param::table_ftp))
  537. {
  538. sqlConfig->CreateTable(param::table_ftp);
  539. config_class.ftp_db = {1,CRED_FTP_HOST,CRED_FTP_PORT,"",
  540. CRED_FTP_UID,CRED_FTP_PWD,0};
  541. sqlConfig->InsertData(config_class,param::table_ftp);
  542. sqlConfig->QueryAllData(param::table_ftp);
  543. }else{
  544. sqlConfig->QueryAllData(param::table_ftp);
  545. }
  546. if(!sqlConfig->isTableExist(param::table_ftp_other))
  547. {
  548. sqlConfig->CreateTable(param::table_ftp_other);
  549. config_class.ftp_db = {1,CRED_FTP_OTHER_HOST,21,"",
  550. CRED_FTP_OTHER_UID,CRED_FTP_OTHER_PWD,0};
  551. sqlConfig->InsertData(config_class,param::table_ftp_other);
  552. sqlConfig->QueryAllData(param::table_ftp_other);
  553. }else{
  554. sqlConfig->QueryAllData(param::table_ftp_other);
  555. }
  556. if(!sqlConfig->isTableExist(param::table_location))
  557. {
  558. sqlConfig->CreateTable(param::table_location);
  559. config_class.location_db = {1,"0","0","0","0","0"};
  560. sqlConfig->InsertData(config_class,param::table_location);
  561. sqlConfig->QueryAllData(param::table_location);
  562. }else{
  563. sqlConfig->QueryAllData(param::table_location);
  564. }
  565. //相机图像参数
  566. if(!sqlConfig->isTableExist(param::table_camera)){
  567. sqlConfig->CreateTable(param::table_camera);
  568. config_class.camera_db = {"hikrobot","static",2,1000,1000,"0","f80","b80","f80","b80"};
  569. sqlConfig->InsertData(config_class,param::table_camera);
  570. sqlConfig->QueryAllData(param::table_camera);
  571. }else{
  572. sqlConfig->QueryAllData(param::table_camera);
  573. }
  574. //配置
  575. if(!sqlConfig->isTableExist(param::table_config)){
  576. sqlConfig->CreateTable(param::table_config);
  577. config_class.config_db = {1,1,1000,500,0,0,1,0};
  578. sqlConfig->InsertData(config_class,param::table_config);
  579. sqlConfig->QueryAllData(param::table_config);
  580. }else{
  581. //旧版本库没有 fusion_enable 列(景深融合开关):补列后再读,保证老设备升级后可用
  582. ensureColumnExist(param::table_config,"fusion_enable","fusion_enable INT NOT NULL DEFAULT 1");
  583. //旧版本库没有 focus_algo 列(对焦/融合算法选择):补列,默认 0=SLView 引导滤波融合
  584. ensureColumnExist(param::table_config,"focus_algo","focus_algo INT NOT NULL DEFAULT 0");
  585. ensureConfigRow(); //表被清空时补默认行,保证后续配置 UPDATE 能生效
  586. sqlConfig->QueryAllData(param::table_config);
  587. }
  588. sqlConfig->CloseDb();
  589. //InsertJson_mqtt();
  590. qRegisterMetaType<QByteArray>("QByteArray");
  591. FelgoApplication felgo;
  592. QQmlApplicationEngine engine;
  593. felgo.initialize(&engine);
  594. //felgo.setLicenseKey("6BBDF824AF729C33ECAA6DC917319EDB8A7F76A9EB5217C380F81C28203CF84078DBCEEC5DB44C7DB60373C0FFE65240DA17EAC1C8376F5939F26782D2A3110CFCDB938C557DDAC8C63F942AF917CD7BCD4235973E76002E69BE740BD2FE99BB7F22AD12408FB5EE3D3A538E604803F0947C372A8486E63B5CF101A18B6CEDF7AEDC615273B15ADBCF1DCC54F123FA093609F650378D2F2BC11C74421663CAB7C178C4123AF6C8B6E44EE45A5A790448F85D4039D7EB1C23C3CA97B42E0724B2987C185114E732662A4EFD507EDC0E5DC2DA7A9FF7754678F48BFC8AAFD40B21926B5A1FD427E279FDE44EC0315229371F4D77B918CC4663CB71572051E1E84DCBF8E183C44981C9D921DB7C5A02879E2D9352ECEC03FF21D99F941B9E31E10D6D625D2603135C101658FEA17FB7B397");
  595. LOG("信息(Info)");
  596. TreeModel model;
  597. engine.setOfflineStoragePath(appDataPath); //设置数据库存储路径
  598. engine.rootContext()->setContextProperty("appdir", qApp->applicationDirPath()); //使用QApplication::applicationDirPath()获取,并注册到qml中
  599. engine.rootContext()->setContextProperty("treeModel",&model);
  600. qmlRegisterType<EasyTableModel>("EasyModel",1,0,"EasyTableModel"); //注册C++模块到QML中
  601. qmlRegisterType<DatabaseInterface>("com.example.database", 1, 0, "DatabaseInterface");
  602. qmlRegisterType<CustomItem>("ExampleCustomMaterial",1,0,"CustomItem");
  603. // Set an optional license key from project file
  604. // This does not work if using Felgo Live, only for Felgo Cloud Builds and local builds
  605. //felgo.setLicenseKey(PRODUCT_LICENSE_KEY);
  606. // use this during development
  607. // for PUBLISHING, use the entry point below
  608. felgo.setMainQmlFileName(QStringLiteral("qml/Main.qml"));
  609. // use this instead of the above call to avoid deployment of the qml files and compile them into the binary with qt's resource system qrc
  610. // this is the preferred deployment option for publishing games to the app stores, because then your qml files and js files are protected
  611. // to avoid deployment of your qml files and images, also comment the DEPLOYMENTFOLDERS command in the .pro file
  612. // also see the .pro file for more details
  613. //felgo.setMainQmlFileName(QStringLiteral("qrc:/qml/Main.qml"));
  614. const QUrl url(felgo.mainQmlFileName());
  615. Qt6QCamera::Frames::registerQmlType();
  616. SerialThread serialThread;
  617. serialThread.start();
  618. engine.rootContext()->setContextProperty("serial", &serialThread);
  619. CurlFtpUploader uploader_ftp; // 成员变量
  620. //【安全】凭据改由 app_credentials.h 统一提供
  621. QString remotepath = QString(CRED_FTP_DIR_PREFIX) + param::imei;
  622. uploader_ftp.setFtpParams(CRED_FTP_UID, CRED_FTP_PWD, CRED_FTP_HOST,
  623. CRED_FTP_PORT, remotepath);
  624. //【日志查看/上传】系统设置 -> 查看日志页使用:
  625. // 读取 app 运行日志(run_log*.txt)与 MCU 串口日志(mcu_console*.txt),
  626. // 支持 tail -f 增量刷新;上传复用同一套 FTP 凭据/远端目录,但用独立的上传器实例
  627. // (图片上传器失败时会删除 .txt 文件,日志不能冒这个险)。
  628. LogViewer logViewer;
  629. logViewer.setFtpParams(CRED_FTP_UID, CRED_FTP_PWD, CRED_FTP_HOST,
  630. CRED_FTP_PORT, remotepath);
  631. engine.rootContext()->setContextProperty("logViewer", &logViewer);
  632. MqttHandler mqttHandler;
  633. mqttHandler.storage()->setJsonCacheEnabled(param::jsonCacheEnable);
  634. mqttHandler.storage()->setImageCacheEnabled(param::imageCacheEnable);
  635. mqttHandler.storage()->setMaxJsonEntries(param::maxJsonEntries);
  636. mqttHandler.storage()->setMaxImageEntries(param::maxImageEntries);
  637. CurlHandler curlHandler(CRED_OTA_APP_URL, appDataPath+"/app.apk"); //app升级
  638. NetworkInfoHelper networkMonitor;
  639. //【工作状态卡片】工控机自身 CPU/内存占用:读 /proc/stat 与 /proc/meminfo,
  640. // 2s 采一次,换算成百分比后由 QML 直接显示
  641. SystemMonitor sysMonitor;
  642. engine.rootContext()->setContextProperty("sysMonitor", &sysMonitor);
  643. engine.rootContext()->setContextProperty("mqtt", &mqttHandler);
  644. engine.rootContext()->setContextProperty("curl", &curlHandler);
  645. //engine.rootContext()->setContextProperty("ymodem",serialThread.getYmodem());
  646. engine.rootContext()->setContextProperty("curl_picture",&uploader_ftp);
  647. engine.rootContext()->setContextProperty("networkMonitor", &networkMonitor);
  648. //【运维App】com.rd.client 自动更新/安装/守护:
  649. // 联网成功后每 10 分钟巡检 FTP 目录取最高版本 → 下载 → 静默安装
  650. // → 自动授权 → 自动拉起,并持续守护(掉线自动重启)。
  651. // 该目录与 OTA 同在 _UPDATE_FILE 仓库,用 cbd_user 账号;
  652. // bzy_user(图片上传账号)对该仓库可能被拒(550),这里登记为备用账号。
  653. OaAppManager oaAppManager;
  654. oaAppManager.setServer(CRED_OTA_UID, CRED_OTA_PWD, CRED_OA_APP_URL_BASE,
  655. CRED_OA_APP_PKG, appDataPath + "/oa_app");
  656. oaAppManager.setFallbackAccount(CRED_FTP_UID, CRED_FTP_PWD);
  657. engine.rootContext()->setContextProperty("oaApp", &oaAppManager);
  658. // 注册OpenCV图像融合功能到QML
  659. OpencvFunc opencvFunc;
  660. engine.rootContext()->setContextProperty("opencvFunc", &opencvFunc);
  661. // 注册权限管理到QML(定位/电话/文件与媒体/相机/系统设置修改等)
  662. PermissionBridge permissionBridge;
  663. engine.rootContext()->setContextProperty("permission", &permissionBridge);
  664. // 网飞系统基础服务 AIDL 集成: 绑定 service 并把 wrapper 暴露给 QML.
  665. WifService *wifService = new WifService(&app);
  666. QObject::connect(wifService, &WifService::connectedChanged, [&](bool connected) {
  667. if (connected) {
  668. // 服务已连接,可以安全调用
  669. wifService->setKioskMode(true);
  670. }
  671. });
  672. wifService->bind();
  673. engine.rootContext()->setContextProperty("wifService", wifService);
  674. // 有线网卡配置 (基于 EnjoySDK, 走系统 EthernetService, 无需 root).
  675. // 供 QML 状态界面查询 eth0/eth1 状态并切换 DHCP / 静态 IP。
  676. // 注意:设置静态 IP 时,mode=STATIC 与 IP 参数必须一次性下发(Java 侧已如此实现),
  677. // 分两步提交会被系统 EthernetService 拒为 -101。
  678. EthernetService *ethernetService = new EthernetService(&app);
  679. engine.rootContext()->setContextProperty("ethernet", ethernetService);
  680. //串口到MQTT(信号1参,槽2参,publish_m的默认qos在指针式连接中不生效,必须用lambda补参数)
  681. QObject::connect(&serialThread,&SerialThread::dataUpload,&mqttHandler,[&mqttHandler](const QByteArray &data){ mqttHandler.publish_m(data); });
  682. QObject::connect(&mqttHandler,&MqttHandler::dataReceived,&serialThread,&SerialThread::mqtttoserial);//MQTT到串口
  683. QObject::connect(&networkMonitor,&NetworkInfoHelper::reachabilityChanged,[&](QNetworkInformation::Reachability newReachability){
  684. if(newReachability==QNetworkInformation::Reachability::Online){
  685. WARN("网络连接!");
  686. param::net_alive = 1;
  687. }else{
  688. param::net_alive = 0;
  689. WARN("网络断开!");
  690. mqttHandler.disconnectFromBroker();
  691. }
  692. });
  693. QObject::connect(&uploader_ftp, &CurlFtpUploader::finished,
  694. &mqttHandler,&MqttHandler::storage_Picture);
  695. QObject::connect(&mqttHandler, &MqttHandler::signal_reupload_image,
  696. &uploader_ftp, static_cast<void (CurlFtpUploader::*)(const QString&, const QString&)>(&CurlFtpUploader::uploadFileAsync));
  697. QObject::connect(&mqttHandler, &MqttHandler::signal_upload_log,
  698. &uploader_ftp, static_cast<void (CurlFtpUploader::*)(const QString&)>(&CurlFtpUploader::uploadFileAsync));
  699. QObject::connect(&mqttHandler,&MqttHandler::updateStm32,[&](){
  700. curlHandler.seturl(CRED_OTA_MCU_URL); //【安全】凭据改由 app_credentials.h 统一提供
  701. //升级包仓库是 cbd_user 账号,与图片上传账号不同;用错账号服务器会回 550(code=9)
  702. curlHandler.setuserpwd(CRED_OTA_UID,CRED_OTA_PWD);
  703. //【路径统一】必须与 mserial.cpp / downloadFinished 里传给 ymodem 的路径一致
  704. curlHandler.setfilepath(otaFirmwarePath());
  705. curlHandler.settype("主板升级文件更新");
  706. curlHandler.start();
  707. //sendBroadcastFromQt("install");
  708. });
  709. QObject::connect(&mqttHandler,&MqttHandler::appdownload,[&](){
  710. curlHandler.seturl(CRED_OTA_APP_URL); //【安全】凭据改由 app_credentials.h 统一提供
  711. //升级包仓库是 cbd_user 账号,与图片上传账号不同;用错账号服务器会回 550(code=9)
  712. curlHandler.setuserpwd(CRED_OTA_UID,CRED_OTA_PWD);
  713. //curlHandler.setfilepath(appDataPath+"/app.apk");
  714. curlHandler.setfilepath("/sdcard/app.apk");
  715. curlHandler.settype("App升级文件更新");
  716. curlHandler.start();
  717. //
  718. });
  719. QObject::connect(&mqttHandler,&MqttHandler::sysReboot,[&](){
  720. WARN("系统重启");
  721. sendBroadcastFromQt("rebootSystem");
  722. });
  723. //配置项变更(拼接数量等)持久化到 camera 表
  724. QObject::connect(&mqttHandler,&MqttHandler::configChange,[&](){
  725. sqlConfig->OpenDb();
  726. if(sqlConfig->isTableExist(param::table_camera)){
  727. LOG("UpdateData stitch_photonum !!!!!");
  728. sqlConfig->UpdateData(param::table_camera,"stitch_photonum",QString::number(param::stitch_photonum));
  729. }
  730. sqlConfig->CloseDb();
  731. });
  732. QObject::connect(&mqttHandler,&MqttHandler::signal_imei_change,[&](QString NEW_IMEI){
  733. sqlConfig->OpenDb();
  734. if(sqlConfig->isTableExist(param::table_mqtt)){
  735. LOG("Update Data imei:{}",NEW_IMEI.toStdString());
  736. sqlConfig->UpdateData(param::table_mqtt,"imei",NEW_IMEI);
  737. }
  738. sqlConfig->CloseDb();
  739. });
  740. QObject::connect(&curlHandler,&CurlHandler::downloadFinished,[&](bool result,QString mtype){
  741. LOG("downloadFinished:{}-{}",result,mtype.toStdString());
  742. if(result&&mtype.contains("App")){
  743. // QByteArray download_success("{\"cmd\":\"warn\",\"ext\":{\"status\":\"App DownLoad Success!\"}}");
  744. // mqttHandler.publish_m(download_success);
  745. emit mqttHandler.appInstall();
  746. }
  747. if(result&&mtype.contains("主板升级文件更新")){
  748. //【路径统一】这里原来重新拼的是 GenericDataLocation+"/rtthread.rbl"
  749. //(= /storage/emulated/0/rtthread.rbl), 而 updateStm32 下载保存的是
  750. //appDataPath+"/rtthread.rbl", 两个不是同一个文件: ymodem 一直发的是根目录
  751. //下遗留的旧包 -> 主板 bootloader 判定"版本相同"-> 不搬运 -> 升级后版本号不变。
  752. const QString subDirPath = otaFirmwarePath();
  753. QFileInfo fi(subDirPath);
  754. LOG("升级文件路径:{} (exists={} size={})",subDirPath.toStdString(),
  755. fi.exists()?"1":"0", fi.size());
  756. emit serialThread.updatestart(subDirPath);
  757. }
  758. });
  759. QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
  760. &app, [url](QObject *obj, const QUrl &objUrl) {
  761. if (!obj && url == objUrl)
  762. QCoreApplication::exit(-1);
  763. }, Qt::QueuedConnection);
  764. // 将位置信息源暴露给QML界面
  765. engine.load(QUrl(felgo.mainQmlFileName()));
  766. // 网口相机(GigE)链路配置:eth0 静态IP + Jumbo 帧 MTU。
  767. // 放在 engine.load() 之后:EnjoySDK 需要 Android Context,
  768. // 而 Context 由 QtAndroidActivity 持有,只有 QML 引擎起来后才保证可用。
  769. // 内部对 eth0 做幂等配置,重复执行不会破坏已有网络。
  770. setupEth0();
  771. //FelgoLiveClient liveClient(&engine);
  772. //UserFunc myClass(engine.rootObjects()); // 获取QML对象
  773. #if WIN32
  774. app.installNativeEventFilter(myClass.mySerialEvent); // 安装window串口拔插事件
  775. #endif
  776. //engine.rootContext()->setContextProperty("myClass", &myClass); // 将C++类添加进QML使用
  777. //engine.rootContext()->setContextProperty("mySerial", myClass.serial_main); // 将C++类添加进QML使用
  778. QObject *rootItem = engine.rootObjects().value(0);
  779. //traverseQmlObject(rootItem);
  780. #if 1
  781. if(rootItem)
  782. {
  783. QObject::connect(&mqttHandler,&MqttHandler::autotakephoto,[&](bool stat){
  784. QObject *Navigation_main = rootItem->findChild<QObject*>("Navigation_main");
  785. if(Navigation_main){
  786. DEBUG("Navigation_main is !!!!! {}", stat);
  787. QMetaObject::invokeMethod(Navigation_main, "setCurrentTab", Q_ARG(QVariant, 1));
  788. //打开相机
  789. QObject *autoFocus_Page = rootItem->findChild<QObject*>("autoFocus_Page");
  790. if(autoFocus_Page){
  791. QMetaObject::invokeMethod(autoFocus_Page, "autotake",Q_ARG(QVariant,stat));
  792. //将param::stitchphoto保存
  793. }
  794. }
  795. }); //mqtt到QML,控制qml跳转到自动对焦界面,开始对焦拍照
  796. QObject::connect(&serialThread,&SerialThread::auto_takephoto,[&](){
  797. QObject *Navigation_main = rootItem->findChild<QObject*>("Navigation_main");
  798. if(Navigation_main){
  799. DEBUG("Navigation_main is !!!!!");
  800. QMetaObject::invokeMethod(Navigation_main, "setCurrentTab", Q_ARG(QVariant, 1));
  801. //打开相机
  802. QObject *autoFocus_Page = rootItem->findChild<QObject*>("autoFocus_Page");
  803. if(autoFocus_Page){
  804. QMetaObject::invokeMethod(autoFocus_Page, "autotake",Q_ARG(QVariant,true));
  805. }
  806. }
  807. }); //串口到QML,控制qml跳转到自动对焦界面,结束对焦拍照
  808. //获取按钮点击事件
  809. QObject *systemset_Item = rootItem->findChild<QObject*>("systemset_Item");
  810. if(systemset_Item){
  811. QObject::connect(systemset_Item, SIGNAL(selected()),&myCppClass,SLOT(systemPage()));
  812. QObject::connect(&myCppClass, &MyCppClass::tosystempage,[&](){
  813. QObject *openbar_btn = rootItem->findChild<QObject*>("openbar_btn"); //打开状态栏
  814. if(openbar_btn){
  815. QObject::connect(openbar_btn, SIGNAL(opernBar()),&myCppClass,SLOT(openbar_btnClicked()));
  816. QObject::connect(&myCppClass, &MyCppClass::opensystembar,[&](){
  817. sendBroadcastFromQt("openbar_btn");
  818. });
  819. QObject::connect(openbar_btn, SIGNAL(closeBar()),&myCppClass,SLOT(closebar_btnClicked()));
  820. QObject::connect(&myCppClass, &MyCppClass::closesystembar,[&](){
  821. sendBroadcastFromQt("closebar_btn");
  822. });
  823. }
  824. QObject *opennav_btn = rootItem->findChild<QObject*>("opennav_btn"); //控制导航栏
  825. if(opennav_btn){
  826. QObject::connect(opennav_btn, SIGNAL(opernNav()),&myCppClass,SLOT(opennav_btnClicked()));
  827. QObject::connect(&myCppClass, &MyCppClass::opensystemnav,[&](){
  828. sendBroadcastFromQt("opennav_btn");
  829. });
  830. QObject::connect(opennav_btn, SIGNAL(closeNav()),&myCppClass,SLOT(closenav_btnClicked()));
  831. QObject::connect(&myCppClass, &MyCppClass::closesystemnav,[&](){
  832. sendBroadcastFromQt("closenav_btn");
  833. });
  834. }
  835. });
  836. }
  837. // 获取根 QML 对象
  838. QObject *autofocus_item = rootItem->findChild<QObject*>("autofocus_Item");
  839. if(autofocus_item){
  840. bool isConnect_frame = true;
  841. //const QMetaObject *metaObj = autofocus_item->metaObject();
  842. LOG("Found autofocus_item!");
  843. QObject::connect(autofocus_item, SIGNAL(selected()),&myCppClass,SLOT(qmlSlot()));
  844. QObject::connect(&myCppClass, &MyCppClass::recvqmlslot,[&](){
  845. LOG("connect myCppClass");
  846. Qt6QCamera::Frames *m_frames = qobject_cast<Qt6QCamera::Frames*>(rootItem->findChild<QObject*>("Frames"));
  847. if(!m_frames) {ERROR("m_frames is null!!!");}
  848. if(m_frames&&isConnect_frame){
  849. LOG("m_frames connected!");
  850. //engine.addImageProvider("ucamera",m_frames->getImageProvider());
  851. QObject::connect(m_frames,&Qt6QCamera::Frames::serial_data,&serialThread,&SerialThread::sendData); //Frame到串口
  852. QObject::connect(&serialThread,&SerialThread::takephotodone,m_frames,&Qt6QCamera::Frames::saveImage); //串口到QML,控制qml跳转到自动对焦界面
  853. QObject::connect(&serialThread,&SerialThread::signal_movy,m_frames,&Qt6QCamera::Frames::onMovDone);
  854. //串口 record_stop:停止录制并处理视频流(分析/融合/删除录制文件/上传融合图)
  855. QObject::connect(&serialThread,&SerialThread::recordStop,m_frames,&Qt6QCamera::Frames::handleRecordStop);
  856. //主板对焦完成(auto_focus):步进扫描结束即刻收尾。
  857. // 旧流程靠 RECORD_TIMEOUT_MS 看门狗等超时才处理,最后一步要白等 10 秒;
  858. // 这里直接停止录制并进入"分析最清晰帧 -> 融合 -> 上传"。
  859. // handleRecordStop 内部对"未在录制"有幂等保护,重复触发不会出错。
  860. QObject::connect(&serialThread,&SerialThread::autoFocusDone,m_frames,&Qt6QCamera::Frames::handleRecordStop);
  861. QObject::connect(m_frames,&Qt6QCamera::Frames::dataUpload,&mqttHandler,[&mqttHandler](const QByteArray &data){ mqttHandler.publish_m(data); }); //frames到MQTT(信号1参,槽2参需lambda补默认qos)
  862. // 修改信号槽连接方式
  863. QObject::connect(m_frames, &Qt6QCamera::Frames::signal_wait_upload,
  864. &uploader_ftp, static_cast<void (CurlFtpUploader::*)(const QString&)>(&CurlFtpUploader::uploadFileAsync));
  865. QObject::connect(&uploader_ftp, &CurlFtpUploader::finished,
  866. m_frames,&Qt6QCamera::Frames::handle_reult_upload);
  867. QObject::connect(m_frames, &Qt6QCamera::Frames::signal_cache_image,
  868. &mqttHandler, &MqttHandler::storage_Picture_Takephoto);
  869. isConnect_frame = false;
  870. }else{
  871. ERROR("m_frames no !!!!!");
  872. }
  873. });
  874. }else{
  875. DEBUG("autofocus_item no !!!!!");
  876. }
  877. }else{
  878. ERROR("rootItem is null !!!!!");
  879. }
  880. #endif
  881. LOG("app start!");
  882. // to start your project as Live Client, comment (remove) the lines "felgo.setMainQmlFileName ..." & "engine.load ...",
  883. // and uncomment the line below
  884. //FelgoLiveClient client (&engine);
  885. GPSInfo *gps_start = new GPSInfo(sqlConfig,&app);
  886. QObject::connect(gps_start,&GPSInfo::position_success,[&](){
  887. emit serialThread.gpsSuccess();
  888. });
  889. serialThread.recoverMcuParam();
  890. return app.exec();
  891. }
  892. #include "main.moc"