diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..dc26718d2a06f024b1253c66f65b627dcef5898a --- /dev/null +++ b/.env.example @@ -0,0 +1,7 @@ +THINGSBOARD_HOST=iot.acte.ltd +THINGSBOARD_USER=xxxx@acte.ltd +THINGSBOARD_PASS=xxxxx + +ACCESS_TOKEN_WINDOWS=YOUR_WINDOWS_TOKEN_HERE +ACCESS_TOKEN_LINUX=YOUR_LINUX_TOKEN_HERE +ACCESS_TOKEN_MAC=YOUR_MAC_TOKEN_HERE diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7de98e7ac05a3d84ab3364aa524153a25285ed1d --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +.env + +# Python bytecode +__pycache__/ +*.py[cod] +*$py.class + +# Virtual environment +venv/ +.env/ # If you use an env folder instead of .env file + +# OS files +.DS_Store # macOS Finder +Thumbs.db # Windows thumbnail cache + +# Logs +*.log + +# IDE/editor settings +.vscode/ +.idea/ + +# pytest cache +.pytest_cache/ + +# Jupyter Notebook checkpoints +.ipynb_checkpoints/ + +# Build artifacts +dist/ +build/ +*.egg-info/ + +# mypy / Pyright / Pylint +.mypy_cache/ +.pyre/ +.pytype/ +pylint-report.txt diff --git a/README.md b/README.md index 23f633d1a870f6b7b46d9c6eac508e7ccc99c561..2dacea31c256af3a2fa9d4db73bed8938b4ebe03 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,144 @@ -# acte-tb-dashboard-tutorial +# Cross-Platform CPU Temperature Monitor for ThingsBoard +A comprehensive solution to monitor CPU temperature from **Windows**, **macOS**, and **Linux** machines and visualize the data in real-time on a **ThingsBoard** dashboard. -## Getting started +## Project Structure -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +``` +acte-tb-dashboard-tutorial/ +├── .env.example # Example environment file +├── requirements.txt # All Python dependencies +├── linux/ +│ └── cpu_temp_linux.py # Script for Linux systems +├── macos/ +│ └── cpu_temp_mac.py # Script for macOS systems +└── win/ + └── cpu_temp_win.py # Script for Windows systems +``` + +## Prerequisites -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +Before you start, ensure you have: -## Add your files +- **Git**: To clone the repository. +- **Python 3.7+ and Pip** +- A **ThingsBoard Account** (either ThingsBoard Cloud or self-hosted) -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +## Installation and Configuration +### 1. Clone the Repository + +```bash +git clone https://gitlab.acte.ltd/acte-public/acte-tb-dashboard-tutorial.git +cd acte-tb-dashboard-tutorial ``` -cd existing_repo -git remote add origin https://gitlab.acte.ltd/acte-public/acte-tb-dashboard-tutorial.git -git branch -M main -git push -uf origin main + +### 2. Set Up a Python Virtual Environment + +```bash +# Create a virtual environment +python -m venv venv + +# Activate the environment +# On Windows: +venv\Scripts\activate +# On macOS/Linux: +source venv/bin/activate ``` -## Integrate with your tools +### 3. Install Dependencies -- [ ] [Set up project integrations](https://gitlab.acte.ltd/acte-public/acte-tb-dashboard-tutorial/-/settings/integrations) +```bash +pip install -r requirements.txt +``` -## Collaborate with your team +### 4. Configure Your Credentials -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) +Copy the example `.env` file: -## Test and Deploy +```bash +# On Windows (Command Prompt) +copy .env.example .env -Use the built-in continuous integration in GitLab. +# On macOS/Linux +cp .env.example .env +``` -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) +Edit the `.env` file with your ThingsBoard details: -*** +```env +# ThingsBoard server address (without http:// or https://) +THINGSBOARD_HOST=iot.acte.ltd -# Editing this README +# Access tokens for each OS-specific device (from ThingsBoard) +ACCESS_TOKEN_WINDOWS=YOUR_WINDOWS_TOKEN_HERE +ACCESS_TOKEN_LINUX=YOUR_LINUX_TOKEN_HERE +ACCESS_TOKEN_MAC=YOUR_MAC_TOKEN_HERE +``` -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. +--- -## Suggestions for a good README +## How to Get ThingsBoard Access Tokens -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +1. Log in to your ThingsBoard account. +2. Navigate to **Devices**. +3. Click the **"+"** icon to add a new device. +4. Name the device (e.g., "My Windows PC"). +5. After creating the device, open its details page. +6. Copy the **access token** and paste it into your `.env` file. +7. Repeat for each machine. -## Name -Choose a self-explaining name for your project. +--- -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +## Platform-Specific Setup and Usage -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +### 🖥️ Windows -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. +#### Setup: +1. Download **Open Hardware Monitor** from the official site. +2. Run `OpenHardwareMonitor.exe` as Adminstrator. +3. Go to **Options → WMI → Enable**. +4. Leave the app running in the background. -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. +#### Usage: -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. +```bash +python win/cpu_temp_win.py +``` -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +--- -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +### 🍏 macOS -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +#### Setup: -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +1. Install **Homebrew** (if not already installed). +2. Install the temperature utility: -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +```bash +brew install osx-cpu-temp +``` + +#### Usage: + +```bash +python macos/cpu_temp_mac.py +``` + +--- -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +### 🐧 Linux + +#### Setup: + +No special setup required for most Linux systems. + +#### Usage: + +```bash +python linux/cpu_temp_linux.py +``` -## License -For open source projects, say how it is licensed. +--- -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/linux/cpu_temp_linux.py b/linux/cpu_temp_linux.py new file mode 100644 index 0000000000000000000000000000000000000000..c9598c525bd4a97f8e1949725e5517aa63d3a696 --- /dev/null +++ b/linux/cpu_temp_linux.py @@ -0,0 +1,40 @@ +import os +import time +import json +import paho.mqtt.client as mqtt +from dotenv import load_dotenv + +load_dotenv() # Load .env file variables + +THINGSBOARD_HOST = os.getenv('THINGSBOARD_HOST') +ACCESS_TOKEN = os.getenv('ACCESS_TOKEN_LINUX') + +client = mqtt.Client(protocol=mqtt.MQTTv311) +client.username_pw_set(ACCESS_TOKEN) + +try: + client.connect(THINGSBOARD_HOST, 1883, 60) +except Exception as e: + print(f"Could not connect to ThingsBoard: {e}") + exit() + +def get_cpu_temperature(): + try: + with open("/sys/class/thermal/thermal_zone0/temp", "r") as f: + return float(f.readline()) / 1000 + except FileNotFoundError: + print("CPU temperature file not found!") + return None + +try: + while True: + temp = get_cpu_temperature() + if temp is not None: + payload = json.dumps({"temperature": temp}) + client.publish('v1/devices/me/telemetry', payload) + print(f"Published: {payload}") + time.sleep(5) +except KeyboardInterrupt: + print("Stopped by User") +finally: + client.disconnect() diff --git a/macos/cpu_temp_mac.py b/macos/cpu_temp_mac.py new file mode 100644 index 0000000000000000000000000000000000000000..269bd0d06ab2cf379e6feceee7f05fa1eb4078e5 --- /dev/null +++ b/macos/cpu_temp_mac.py @@ -0,0 +1,37 @@ +import os +import time +import json +import subprocess +import paho.mqtt.client as mqtt +from dotenv import load_dotenv + +load_dotenv() + +THINGSBOARD_HOST = os.getenv('THINGSBOARD_HOST') +ACCESS_TOKEN = os.getenv('ACCESS_TOKEN_MAC') + +client = mqtt.Client(protocol=mqtt.MQTTv311) +client.username_pw_set(ACCESS_TOKEN) +client.connect(THINGSBOARD_HOST, 1883, 60) + +def get_cpu_temperature(): + try: + output = subprocess.check_output(["osx-cpu-temp"]).decode("utf-8") + temp_str = output.strip().split("°")[0] + return float(temp_str) + except Exception as e: + print(f"Error reading temperature: {e}") + return None + +try: + while True: + temp = get_cpu_temperature() + if temp is not None: + payload = json.dumps({"temperature": temp}) + client.publish('v1/devices/me/telemetry', payload) + print(f"macOS Temp Published: {payload}") + time.sleep(5) +except KeyboardInterrupt: + pass +finally: + client.disconnect() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b9d31e1f7c98926bb2cfe64471c6fc7ab2f8b9f5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +paho-mqtt +python-dotenv +psutil +pythonnet +wmi \ No newline at end of file diff --git a/win/cpu_temp_win.py b/win/cpu_temp_win.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba36ce8e44f2f0614a8525d292b50af44073748 --- /dev/null +++ b/win/cpu_temp_win.py @@ -0,0 +1,137 @@ +import time +import json +import sys +import platform +import os +# Load environment variables from .env file +from dotenv import load_dotenv +load_dotenv() + +# Import WMI only on Windows +if platform.system() == "Windows": + try: + import wmi + except ImportError: + print("WMI library not found. Please install it using: pip install WMI") + sys.exit(1) + +import paho.mqtt.client as mqtt + +# --- ThingsBoard Configuration --- +# TODO: Replace with your ThingsBoard host. +# If you are using ThingsBoard Cloud, it will be 'mqtt.thingsboard.cloud' +THINGSBOARD_HOST = os.getenv('THINGSBOARD_HOST') +ACCESS_TOKEN = os.getenv('ACCESS_TOKEN_WINDOWS') + +# Default MQTT port for ThingsBoard +THINGSBOARD_PORT = 1883 + +# Interval in seconds to read and send data +SEND_INTERVAL = 5 # 5 seconds + +def get_cpu_temperature_windows(): + """ + Gets the CPU temperature on Windows by connecting to Open Hardware Monitor's WMI interface. + + IMPORTANT: Open Hardware Monitor must be running with WMI enabled. + (Options -> WMI -> Enable) + + Returns: + float: The average CPU temperature in Celsius, or None if it can't be read. + """ + try: + w = wmi.WMI(namespace="root\\OpenHardwareMonitor") + sensors = w.Sensor() + cpu_temps = [] + for sensor in sensors: + # We are looking for Temperature sensors that are related to the CPU + if sensor.SensorType == 'Temperature' and 'cpu' in sensor.Name.lower(): + cpu_temps.append(sensor.Value) + + if not cpu_temps: + print("Warning: Could not find CPU temperature sensor in Open Hardware Monitor.") + print("Please ensure Open Hardware Monitor is running and 'CPU' is listed.") + return None + + # Return the average of all found CPU temperature sensors + return sum(cpu_temps) / len(cpu_temps) + + except wmi.x_wmi as e: + print("Error: Could not connect to Open Hardware Monitor's WMI interface.") + print("Please make sure Open Hardware Monitor is running with WMI enabled (Options -> WMI -> Enable).") + return None + except Exception as e: + print(f"An unexpected error occurred while reading CPU temperature: {e}") + return None + + +def on_connect(client, userdata, flags, rc): + """Callback for when the client connects to the MQTT broker.""" + if rc == 0: + print("Connected to ThingsBoard MQTT Broker!") + else: + print(f"Failed to connect, return code {rc}\n") + if rc == 5: + print("Authorization error. Please check your device access token.") + elif rc == 3: + print("Connection error. Please check your ThingsBoard host and port.") + sys.exit(1) + + +def main(): + """ + Main function to run the script. + Connects to ThingsBoard and sends CPU temperature data periodically. + """ + # This script is designed for Windows + if platform.system() != "Windows": + print(f"This script is designed for Windows. You are running {platform.system()}.") + sys.exit(1) + + if 'YOUR_THINGSBOARD_HOST' in THINGSBOARD_HOST or 'YOUR_DEVICE_ACCESS_TOKEN' in ACCESS_TOKEN: + print("Error: Please update the placeholders for THINGSBOARD_HOST and ACCESS_TOKEN in the script.") + sys.exit(1) + + client = mqtt.Client() + client.on_connect = on_connect + client.username_pw_set(ACCESS_TOKEN) + + try: + client.connect(THINGSBOARD_HOST, THINGSBOARD_PORT, 60) + client.loop_start() + + while True: + cpu_temp = get_cpu_temperature_windows() + + if cpu_temp is not None: + temp_formatted = f"{cpu_temp:.2f}" + print(f"CPU Temperature: {temp_formatted}°C") + + payload = json.dumps({"temperature": temp_formatted}) + result = client.publish("v1/devices/me/telemetry", payload) + + status = result.rc + if status == 0: + print(f"Successfully sent data to ThingsBoard: {payload}") + else: + print(f"Failed to send message. MQTT Error Code: {status}") + else: + print("Could not retrieve CPU temperature. Will try again.") + + time.sleep(SEND_INTERVAL) + + except KeyboardInterrupt: + print("Script interrupted by user.") + except Exception as e: + print(f"An error occurred: {e}") + finally: + client.loop_stop() + client.disconnect() + print("Disconnected from ThingsBoard.") + + +if __name__ == '__main__': + # Before running, make sure you have the required libraries installed: + # pip install WMI paho-mqtt + # AND Open Hardware Monitor is running with WMI enabled. + main()