push_status.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. # -*- coding: UTF-8 -*-
  2. '''
  3. @Project :jh5sonar_newest
  4. @File :push_status.py
  5. @Author :Fang
  6. @Date :2024/8/14
  7. '''
  8. import configparser
  9. import json
  10. import os
  11. import time
  12. from datetime import datetime
  13. import pymysql
  14. # 数据格式化 fields 字段名,result 结果集
  15. def format_data(fields, result):
  16. # 字段数组 ['id', 'name', 'password']
  17. field = []
  18. for i in fields:
  19. field.append(i[0])
  20. # 返回的数组集合 形式[{'id': 1, 'name': 'admin', 'password': '123456'}]
  21. res = []
  22. for iter in result:
  23. line_data = {}
  24. for index in range(0, len(field)):
  25. line_data[field[index]] = iter[index]
  26. res.append(line_data)
  27. return res
  28. # ping声呐
  29. def get_ping_result(ip_list):
  30. # ip_list: 列表:['192.168.1.51','192.168.1.52']
  31. # 返回值;0或1
  32. for ip in ip_list:
  33. # ping左目,-c:尝试次数,-w:等待时间(秒)
  34. result = os.popen('ping -c 1 -w 1 ' + ip)
  35. # ping通后,会有标志性字符串:"1 received",返回子串起始位置,否则返回-1
  36. r1 = result.read().find('1 received')
  37. # ping不通,返回0
  38. if r1 < 0:
  39. return str(0)
  40. # 都能ping通,返回1
  41. return str(1)
  42. def get_message_from_db(config):
  43. message = {}
  44. sections = config.sections()
  45. print(path + "/push.conf")
  46. print(sections)
  47. if 'device_info' in sections:
  48. try:
  49. message['serial_number'] = config.get("device_info", "serial_number")
  50. message['device_name'] = config.get("device_info", "device_name")
  51. message['project_name'] = config.get("device_info", "project_name")
  52. except Exception as e:
  53. print(e)
  54. if 'db' in sections:
  55. try:
  56. db_host = config.get("db", "db_host")
  57. db_user = config.get("db", "db_user")
  58. db_pass = config.get("db", "db_pass")
  59. db_name = config.get("db", "db_name")
  60. # 打开数据库连接
  61. db = pymysql.connect(host=db_host, user=db_user, password=db_pass, database=db_name)
  62. print(db)
  63. except Exception as e:
  64. print(e)
  65. if 'data_rows' in sections:
  66. try:
  67. table_name = config.get("data_rows", "table_name")
  68. date_column_name = config.get("data_rows", "date_column_name")
  69. # 使用cursor()方法获取操作游标
  70. cursor = db.cursor()
  71. # SQL 查询语句
  72. # date = time.strftime('%Y-%m-%d')
  73. # sql = "SELECT count(*) FROM " + table_name + " WHERE DATE_FORMAT(" + date_column_name + " ,'%Y-%m-%d') = '" + date + "';"
  74. sql = "SELECT count(*) FROM " + table_name + " WHERE " + date_column_name + " >= ( NOW( ) - INTERVAL 24 HOUR );"
  75. try:
  76. # 执行SQL语句
  77. cursor.execute(sql)
  78. # 获取所有记录列表
  79. results = cursor.fetchall()
  80. message['data_rows'] = results[0][0]
  81. except:
  82. message['data_rows'] = 0
  83. print("Error: unable to fetch data")
  84. except Exception as e:
  85. print(e)
  86. if 'ping' in sections:
  87. try:
  88. ip_list = config.get("ping", "ip_list")
  89. ip_list = ip_list.split(",")
  90. ping_result = get_ping_result(ip_list)
  91. message['ping'] = ping_result
  92. except Exception as e:
  93. print(e)
  94. if 'latest_data' in sections:
  95. try:
  96. table_name = config.get("latest_data", "table_name")
  97. column_name_list = config.get("latest_data", "column_name_list")
  98. column_order_by = config.get("latest_data", "order_by")
  99. # 使用cursor()方法获取操作游标
  100. cursor = db.cursor()
  101. # SQL 查询语句
  102. date = time.strftime('%Y-%m-%d')
  103. sql = "SELECT " + column_name_list + " FROM " + table_name + " order by " + column_order_by + " desc limit 1;"
  104. try:
  105. # 执行SQL语句
  106. cursor.execute(sql)
  107. result = cursor.fetchall()
  108. fields = cursor.description
  109. res = format_data(fields, result)
  110. message['latest_data'] = res[0]
  111. except:
  112. print("Error: unable to fetch data")
  113. except Exception as e:
  114. print(e)
  115. if message['ping'] == '1':
  116. message['last_offline_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  117. message_json = json.dumps(message, default=str)
  118. return message_json
  119. def save_message(db, message_json):
  120. cursor = db.cursor()
  121. message_json = json.loads(message_json)
  122. up_date = time.strftime('%Y-%m-%d')
  123. serial_number = message_json['serial_number']
  124. device_name = message_json['device_name']
  125. project_name = message_json['project_name']
  126. data_rows = message_json['data_rows']
  127. latest_data = json.dumps(message_json['latest_data'])
  128. device_status = message_json['ping']
  129. if message_json['ping'] == '1':
  130. # SQL 插入语句
  131. sql = "REPLACE INTO device_status (project_name, up_date, device_name, serial_number, data_rows, latest_data, device_status) VALUES ('%s','%s','%s', '%s', %s, '%s', %s)" % (
  132. project_name, up_date, device_name, serial_number, data_rows, latest_data, device_status)
  133. elif message_json['ping'] == '0':
  134. sql = f"SELECT last_offline_time FROM device_status " \
  135. f"WHERE project_name='{project_name}' and device_name='{device_name}' ORDER BY date_time DESC LIMIT 1;"
  136. cursor.execute(sql)
  137. result = cursor.fetchall()
  138. offline_time = result[0][0]
  139. if offline_time ==None:
  140. last_offline_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  141. else:
  142. last_offline_time = offline_time
  143. sql = "REPLACE INTO device_status (project_name, up_date, device_name, serial_number, data_rows, latest_data, device_status,last_offline_time) VALUES ('%s','%s','%s', '%s', %s, '%s', '%s', '%s')" % (
  144. project_name, up_date, device_name, serial_number, data_rows, latest_data, device_status,last_offline_time)
  145. print(sql)
  146. try:
  147. # 执行sql语句
  148. cursor.execute(sql)
  149. # 提交到数据库执行
  150. db.commit()
  151. except Exception as e:
  152. print(e)
  153. # 关闭数据库连接
  154. db.close()
  155. if __name__ == '__main__':
  156. # db_host = "101.43.128.27"
  157. # db_user = "sencott"
  158. # db_pass = "sencott"
  159. db_host = "127.0.0.1"
  160. db_user = "root"
  161. db_pass = "123456"
  162. db_name = "sencott_device_adminer_db"
  163. # 打开数据库连接
  164. db = pymysql.connect(host=db_host, user=db_user, password=db_pass, database=db_name)
  165. path = os.path.abspath(os.path.dirname(__file__))
  166. config = configparser.ConfigParser()
  167. config.read(path + "/push.conf", encoding="utf-8")
  168. print(path + "/push.conf")
  169. print(config.sections())
  170. message_json = get_message_from_db(config)
  171. save_message(db, message_json)
  172. '''
  173. headers = {'Content-Type': 'application/json'}
  174. r = requests.post("http://localhost/sencott_device_adminer/saveMessage.php", data=message_json, headers=headers)
  175. print(r.text)
  176. '''