From 66290e9b51de36b57774fef18df8556d0bd494cf Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Fri, 7 Feb 2025 21:03:31 -0500 Subject: [PATCH] sorted code --- app.py | 97 ++++++++++++++++++++++++++++----------------------- index.html | 12 ++++--- static/app.js | 48 +++++++++++++++++-------- 3 files changed, 94 insertions(+), 63 deletions(-) diff --git a/app.py b/app.py index c0eedc9..94ce4b5 100644 --- a/app.py +++ b/app.py @@ -1,35 +1,37 @@ -from flask import Flask, render_template, jsonify -import subprocess -import platform +import logging import json +import platform +import subprocess import threading import time +from datetime import datetime +from flask import Flask, render_template, jsonify +import requests +from urllib3.exceptions import InsecureRequestWarning +# Configure logging +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + +# Disable InsecureRequestWarning +requests.packages.urllib3.disable_warnings(InsecureRequestWarning) + +# Initialize Flask app app = Flask(__name__) -def ping(host): - param = '-n' if platform.system().lower() == 'windows' else '-c' - command = ['ping', param, '1', host] - return subprocess.call(command, stdout=subprocess.DEVNULL) == 0 +# Global state +device_status = {} +# Configuration functions def load_config(): with open('config.json') as f: return json.load(f) -device_status = {} -def update_status(): - while True: - config = load_config() - for device in config['devices']: - current_status = ping(device['ip']) - previous_status = device_status.get(device['name'], True) - - if current_status != previous_status: - diagnostics = run_diagnostics(device) - send_webhook(device, current_status, diagnostics) - - device_status[device['name']] = current_status - time.sleep(config['check_interval']) +# Network utility functions +def ping(host): + param = '-n' if platform.system().lower() == 'windows' else '-c' + command = ['ping', param, '1', host] + return subprocess.call(command, stdout=subprocess.DEVNULL) == 0 def send_webhook(device, status, diagnostics): config = load_config() @@ -41,10 +43,7 @@ def send_webhook(device, status, diagnostics): } requests.post(config['webhook_url'], json=webhook_data) -import requests -from urllib3.exceptions import InsecureRequestWarning -requests.packages.urllib3.disable_warnings(InsecureRequestWarning) - +# UniFi API integration class UnifiAPI: def __init__(self, config): self.base_url = config['unifi']['controller'] @@ -65,7 +64,7 @@ class UnifiAPI: except requests.exceptions.RequestException as e: logging.error(f"Failed to get device details: {e}") return None - + def get_device_diagnostics(self, device): details = self.get_device_details(device['device_id']) if not details: @@ -88,7 +87,6 @@ class UnifiAPI: 'interfaces': {} } - # Add interface details if 'interfaces' in details: diagnostics['interfaces'] = self._parse_interfaces(details['interfaces']) @@ -119,8 +117,7 @@ class UnifiAPI: return result - - +# Monitoring functions def run_diagnostics(device): config = load_config() unifi = UnifiAPI(config) @@ -134,6 +131,31 @@ def run_diagnostics(device): return diagnostics +def update_status(): + while True: + config = load_config() + for device in config['devices']: + current_status = ping(device['ip']) + previous_status = device_status.get(device['name'], True) + + if current_status != previous_status: + diagnostics = run_diagnostics(device) + send_webhook(device, current_status, diagnostics) + + device_status[device['name']] = current_status + time.sleep(config['check_interval']) + +# Flask routes +@app.route('/') +def home(): + config = load_config() + logger.debug(f"Loaded devices: {config['devices']}") + return render_template('index.html', devices=config['devices']) + +@app.route('/api/status') +def status(): + return jsonify(device_status) + @app.route('/api/diagnostics') def get_diagnostics(): config = load_config() @@ -141,21 +163,10 @@ def get_diagnostics(): for device in config['devices']: if device['device_id']: diagnostics[device['name']] = run_diagnostics(device) - return jsonify(diagnostics)@app.route('/') -def home(): - return render_template('index.html') - -@app.route('/api/status') -def status(): - return jsonify(device_status) + return jsonify(diagnostics) +# Application entry point if __name__ == '__main__': status_thread = threading.Thread(target=update_status, daemon=True) status_thread.start() - app.run(debug=True) - - -@app.route('/') -def home(): - config = load_config() - return render_template('index.html', devices=config['devices']) \ No newline at end of file + app.run(debug=True) \ No newline at end of file diff --git a/index.html b/index.html index 3ba186f..d2fb2d8 100644 --- a/index.html +++ b/index.html @@ -16,21 +16,23 @@

Network Overview

- {% for device in devices %} -
+ {%- for device in devices %} +
{{ device.name }} {{ device.ip }} {{ device.type }} ({{ device.connection_type }}) + {% if device.critical %} + Critical + {% endif %}
- {% endfor %} + {%- endfor %}
- - \ No newline at end of file + \ No newline at end of file diff --git a/static/app.js b/static/app.js index b68d081..e96d686 100644 --- a/static/app.js +++ b/static/app.js @@ -1,3 +1,24 @@ +// Initialization +const UPDATE_INTERVALS = { + deviceStatus: 30000, + diagnostics: 60000 +}; + +// Core update functions +function updateDeviceStatus() { + console.log('Updating device status...'); + fetch('/api/status') + .then(response => response.json()) + .then(data => { + console.log('Received status data:', data); + Object.entries(data).forEach(([deviceName, status]) => { + console.log(`Updating ${deviceName} status to ${status}`); + updateDeviceIndicator(deviceName, status); + }); + }) + .catch(error => console.error('Error updating status:', error)); +} + function updateDiagnostics() { fetch('/api/diagnostics') .then(response => response.json()) @@ -12,6 +33,7 @@ function updateDiagnostics() { }); } +// Element creation functions function createDiagnosticElement(device, diagnostics) { const element = document.createElement('div'); element.className = `diagnostic-item ${diagnostics.connection_type}-diagnostic`; @@ -63,20 +85,16 @@ function createInterfaceHTML(interfaces) { return html; } -function updateDeviceStatus() { - fetch('/api/status') - .then(response => response.json()) - .then(data => { - Object.entries(data).forEach(([deviceName, status]) => { - updateDeviceIndicator(deviceName, status); - }); - }); +// Initialize updates +function initializeUpdates() { + // Set update intervals + setInterval(updateDeviceStatus, UPDATE_INTERVALS.deviceStatus); + setInterval(updateDiagnostics, UPDATE_INTERVALS.diagnostics); + + // Initial updates + updateDeviceStatus(); + updateDiagnostics(); } -// Update intervals -setInterval(updateDeviceStatus, 30000); -setInterval(updateDiagnostics, 60000); - -// Initial updates -updateDeviceStatus(); -updateDiagnostics(); +// Start the application +initializeUpdates(); \ No newline at end of file