check_serial.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import os
  2. import re
  3. import requests
  4. # Telegram Configurations
  5. bot_token = '949332240:AAHNsQEmCW4it86Esa7F5o07XxwrotSM7s8'
  6. chat_id = '-914111351'
  7. # Path to the kernel log
  8. log_file = "/var/log/kern.log"
  9. # File to store last line read
  10. last_line_file = "/tmp/last_line_read.txt"
  11. # Error message to look for
  12. error_msg = "pl2303 ttyUSB0: usb_serial_generic_read_bulk_callback - urb stopped:"
  13. def send_telegram(bot_token, chat_id, message):
  14. send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + chat_id + '&parse_mode=Markdown&text=' + message
  15. response = requests.get(send_text)
  16. print(response.json())
  17. return response.json()
  18. def check_log_file(log_file, error_msg, last_line_file):
  19. last_line_read = 0
  20. if os.path.exists(last_line_file):
  21. with open(last_line_file, "r") as f:
  22. last_line_read = int(f.readline().strip())
  23. with open(log_file, "r") as f:
  24. log_lines = f.readlines()
  25. # Check if log file was rotated
  26. if len(log_lines) < last_line_read:
  27. last_line_read = 0
  28. for i, line in enumerate(log_lines[last_line_read:]):
  29. if re.search(error_msg, line):
  30. with open(last_line_file, "w") as f:
  31. f.write(str(last_line_read + i + 1))
  32. return True
  33. with open(last_line_file, "w") as f:
  34. f.write(str(len(log_lines)))
  35. return False
  36. if __name__ == "__main__":
  37. if check_log_file(log_file, error_msg, last_line_file):
  38. send_telegram(bot_token, chat_id, "Error detected: serial2usb")