databasethread.cpp 2.7 KB

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