databasethread.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include "databasethread.h"
  2. //#define HostName "172.17.35.51"
  3. //#define HostName "124.71.140.20"
  4. //#define HostName "172.16.120.165"
  5. #define HostName "uskycloud000.mysql.rds.aliyuncs.com"
  6. #define HostPort 3306
  7. #define UserName "usky_admin"
  8. //"usky"
  9. #define PassWord "Usky@2023!@#$_"
  10. //"Yt#75Usky"
  11. #define DatabaseName "usky-data"
  12. DatabaseThread::DatabaseThread(QObject *parent) : QThread(parent)
  13. {
  14. hour = 255;
  15. keep=false;
  16. sqlList.clear();
  17. alarmList.clear();
  18. db = QSqlDatabase::addDatabase("QMYSQL","write_db");
  19. db.setHostName(QString(HostName));
  20. db.setPort(HostPort);
  21. db.setUserName(QString(UserName));
  22. db.setPassword(QString(PassWord));
  23. db.setDatabaseName(QString(DatabaseName));
  24. }
  25. void DatabaseThread::appendSql(QString sql)
  26. {
  27. sqlList.append(sql);
  28. }
  29. void DatabaseThread::appendAlarm(QString sql)
  30. {
  31. alarmList.append(sql);
  32. }
  33. void DatabaseThread::stop()
  34. {
  35. keep = false;
  36. }
  37. void DatabaseThread::run()
  38. {
  39. if(!db.open()){
  40. emit dbdata_log(QString("[%1] writeProcess DatabaseThread db open failed").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")));
  41. }else{
  42. QString ip,port,username,password;
  43. QSqlQuery mqttqry = db.exec(QString("select mqtt_ip,mqtt_port,username,passwd from yt_mqtt where item_name = 'data-write'"));
  44. while (mqttqry.next()) {
  45. ip = mqttqry.value(0).toString();
  46. port = mqttqry.value(1).toString();
  47. username = mqttqry.value(2).toString();
  48. password = mqttqry.value(3).toString();
  49. }
  50. mqttqry.clear();
  51. emit dbdata_log(QString("mqttinfo %1 %2 %3 %4").arg(ip).arg(port).arg(username).arg(password));
  52. emit mqtt_conf(ip,port,username,password);
  53. db.close();
  54. }
  55. keep = true;
  56. while (keep) {
  57. if(!db.open()){
  58. db.open();
  59. }else{
  60. if(sqlList.length()>0){
  61. while (sqlList.length()>0) {
  62. db.exec(sqlList.first());
  63. emit dbdata_log(QString("[%1] sqlList.length() %2 writeProcess sql %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")).arg(sqlList.length()).arg(sqlList.first()));
  64. sqlList.removeFirst();
  65. usleep(1000);
  66. }
  67. }
  68. if(alarmList.length()>0){
  69. while (alarmList.length()>0) {
  70. db.exec(alarmList.first());
  71. emit dbdata_log(QString("[%1] writeProcess alarm sql %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")).arg(alarmList.first()));
  72. alarmList.removeFirst();
  73. usleep(1000);
  74. }
  75. }
  76. }
  77. usleep(50000);
  78. }
  79. }