1 Commits

Author SHA1 Message Date
8830d1cfa0 add example script
Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
2025-11-19 15:36:12 +09:00
10 changed files with 15 additions and 221 deletions

View File

@@ -78,12 +78,3 @@ sudo apt install nodejs npm nanopb
2. Check the serial monitor logs to find the IP address assigned to the device in STA mode, or the default AP address (usually `192.168.4.1`). 2. Check the serial monitor logs to find the IP address assigned to the device in STA mode, or the default AP address (usually `192.168.4.1`).
3. Open a web browser and navigate to the device's IP address. 3. Open a web browser and navigate to the device's IP address.
4. You should now see the ODROID Remote control panel. 4. You should now see the ODROID Remote control panel.
## Docs
- Hardkernel WiKi: [https://wiki.odroid.com/accessory/powermate](https://wiki.odroid.com/accessory/powermate)
## Repo
- Hardkernel Github: [https://github.com/hardkernel/odroid-powermate](https://github.com/hardkernel/odroid-powermate)
- Original Repo: [https://github.com/shinys000114/odroid-powermate](https://github.com/shinys000114/odroid-powermate)

View File

@@ -1,5 +0,0 @@
/.venv/
/venv/
status_pb2.py
test.csv
plot.png

View File

@@ -9,13 +9,13 @@ Based on this script, you can monitor power consumption and implement graph plot
```shell ```shell
sudo apt install virtualenv sudo apt install virtualenv
virtualenv venv virtualenv venv
source venv/bin/activate . venv/bin/activate
``` ```
### Install require package ### Install require package
```shell ```shell
pip install grpcio-tools requests websockets protobuf pandas matplotlib pip install grpcio-tools requests websockets protobuf
``` ```
### Build `status_pb2.py` ### Build `status_pb2.py`
@@ -26,16 +26,7 @@ python -m grpc_tools.protoc -I ../../proto --python_out=. status.proto
### Execute script ### Execute script
#### Power consumption collection
```shell ```shell
# python3 logger.py -u <username> -o <name.csv> -p <password> <address> # python3 logger.py -u <username> -p <password> <address>
python3 logger.py -u admin -p password -o test.csv 192.168.30.5 python3 logger.py -u admin -p password 192.168.30.5
``` ```
#### Plot data
```shell
python3 csv_2_plot.py test.csv plot.png [--type power voltage current]
```
![plot.png](plot.png)

View File

@@ -1,108 +0,0 @@
import argparse
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
def plot_power_data(csv_path, output_path, plot_types):
"""
Reads power data from a CSV file and generates a plot image.
Args:
csv_path (str): The path to the input CSV file.
output_path (str): The path to save the output plot image.
plot_types (list): A list of strings indicating which plots to generate
(e.g., ['power', 'voltage', 'current']).
"""
try:
# Read the CSV file into a pandas DataFrame
# The 'timestamp' column is parsed as dates
df = pd.read_csv(csv_path, parse_dates=['timestamp'])
print(f"Successfully loaded {len(df)} records from '{csv_path}'")
except FileNotFoundError:
print(f"Error: The file '{csv_path}' was not found.")
return
except Exception as e:
print(f"An error occurred while reading the CSV file: {e}")
return
# --- Plotting Configuration ---
plot_configs = {
'power': {'title': 'Power Consumption', 'ylabel': 'Power (W)',
'cols': ['vin_power', 'main_power', 'usb_power']},
'voltage': {'title': 'Voltage', 'ylabel': 'Voltage (V)',
'cols': ['vin_voltage', 'main_voltage', 'usb_voltage']},
'current': {'title': 'Current', 'ylabel': 'Current (A)', 'cols': ['vin_current', 'main_current', 'usb_current']}
}
channel_labels = ['VIN', 'MAIN', 'USB']
channel_colors = ['red', 'green', 'blue']
num_plots = len(plot_types)
if num_plots == 0:
print("No plot types selected. Exiting.")
return
# Create a figure and a set of subplots based on the number of selected plot types.
# sharex=True makes all subplots share the same x-axis (time)
# squeeze=False ensures that 'axes' is always a 2D array, even if num_plots is 1.
fig, axes = plt.subplots(num_plots, 1, figsize=(15, 6 * num_plots), sharex=True, squeeze=False)
axes = axes.flatten() # Flatten the 2D array to 1D for easier iteration
# --- Loop through selected plot types and generate plots ---
for i, plot_type in enumerate(plot_types):
ax = axes[i]
config = plot_configs[plot_type]
for j, col_name in enumerate(config['cols']):
ax.plot(df['timestamp'], df[col_name], label=channel_labels[j], color=channel_colors[j])
ax.set_title(config['title'])
ax.set_ylabel(config['ylabel'])
ax.legend()
ax.grid(True, which='both', linestyle='--', linewidth=0.5)
# --- Formatting the x-axis (Time) ---
# Improve date formatting on the x-axis
# Apply formatting to the last subplot's x-axis
last_ax = axes[-1]
last_ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
last_ax.xaxis.set_major_locator(plt.MaxNLocator(15)) # Limit the number of ticks
plt.xlabel('Time')
plt.xticks(rotation=45)
# Add a main title to the figure
start_time = df['timestamp'].iloc[0].strftime('%Y-%m-%d %H:%M:%S')
end_time = df['timestamp'].iloc[-1].strftime('%H:%M:%S')
fig.suptitle(f'ODROID Power Log ({start_time} to {end_time})', fontsize=16, y=0.95)
# Adjust layout to prevent titles/labels from overlapping
plt.tight_layout(rect=[0, 0, 1, 0.94])
# --- Save the plot to a file ---
try:
plt.savefig(output_path, dpi=150)
print(f"Plot successfully saved to '{output_path}'")
except Exception as e:
print(f"An error occurred while saving the plot: {e}")
def main():
parser = argparse.ArgumentParser(description="Generate a plot from an Odroid PowerMate CSV log file.")
parser.add_argument("input_csv", help="Path to the input CSV log file.")
parser.add_argument("output_image", help="Path to save the output plot image (e.g., plot.png).")
parser.add_argument(
"-t", "--type",
nargs='+',
choices=['power', 'voltage', 'current'],
default=['power', 'voltage', 'current'],
help="Types of plots to generate. Choose from 'power', 'voltage', 'current'. "
"Default is to generate all three."
)
args = parser.parse_args()
plot_power_data(args.input_csv, args.output_image, args.type)
if __name__ == "__main__":
main()

View File

@@ -1,13 +1,11 @@
import argparse import argparse
import asyncio import asyncio
import csv
import requests import requests
import websockets
from datetime import datetime
# Import the status_pb2.py file generated by `protoc`. # Import the status_pb2.py file generated by `protoc`.
# This file must be in the same directory as logger.py. # This file must be in the same directory as logger.py.
import status_pb2 import status_pb2
import websockets
from datetime import datetime
class OdroidPowerLogger: class OdroidPowerLogger:
@@ -18,13 +16,12 @@ class OdroidPowerLogger:
3. Receives and decodes binary data in Protobuf format, then prints it. 3. Receives and decodes binary data in Protobuf format, then prints it.
""" """
def __init__(self, host, username, password, output_file=None): def __init__(self, host, username, password):
self.host = host self.host = host
self.username = username self.username = username
self.password = password self.password = password
self.base_url = f"http://{self.host}" self.base_url = f"http://{self.host}"
self.ws_url = f"ws://{self.host}/ws" self.ws_url = f"ws://{self.host}/ws"
self.output_file = output_file
self.token = None self.token = None
def login(self): def login(self):
@@ -57,33 +54,7 @@ class OdroidPowerLogger:
# Add the authentication token as a query parameter # Add the authentication token as a query parameter
uri = f"{self.ws_url}?token={self.token}" uri = f"{self.ws_url}?token={self.token}"
csv_file = None
csv_writer = None
try: try:
# --- CSV File Handling ---
if self.output_file:
try:
# Open the file in write mode, with newline='' to prevent extra blank rows
csv_file = open(self.output_file, 'w', newline='', encoding='utf-8')
csv_writer = csv.writer(csv_file)
# Write header
header = [
'timestamp', 'uptime_sec',
'vin_voltage', 'vin_current', 'vin_power',
'main_voltage', 'main_current', 'main_power',
'usb_voltage', 'usb_current', 'usb_power'
]
csv_writer.writerow(header)
print(f"Logging data to {self.output_file}")
except IOError as e:
print(f"Error opening CSV file: {e}")
# If file can't be opened, disable CSV writing
csv_file = None
csv_writer = None
# --- End CSV File Handling ---
async with websockets.connect(uri) as websocket: async with websockets.connect(uri) as websocket:
print(f"Connected to WebSocket: {uri}") print(f"Connected to WebSocket: {uri}")
while True: while True:
@@ -97,10 +68,9 @@ class OdroidPowerLogger:
# Process only if the payload type is 'sensor_data' # Process only if the payload type is 'sensor_data'
if status_message.WhichOneof('payload') == 'sensor_data': if status_message.WhichOneof('payload') == 'sensor_data':
sensor_data = status_message.sensor_data sensor_data = status_message.sensor_data
ts_dt = datetime.fromtimestamp(sensor_data.timestamp) ts = datetime.fromtimestamp(sensor_data.timestamp).strftime('%Y-%m-%d %H:%M:%S')
ts_str = ts_dt.strftime('%Y-%m-%d %H:%M:%S')
print(f"--- {ts_str} (Uptime: {sensor_data.uptime_sec}s) ---") print(f"--- {ts} (Uptime: {sensor_data.uptime_sec}s) ---")
# Print data for each channel # Print data for each channel
for name, channel in [('VIN', sensor_data.vin), ('MAIN', sensor_data.main), for name, channel in [('VIN', sensor_data.vin), ('MAIN', sensor_data.main),
@@ -108,24 +78,10 @@ class OdroidPowerLogger:
print( print(
f" {name:<4}: {channel.voltage:5.2f} V | {channel.current:5.3f} A | {channel.power:5.2f} W") f" {name:<4}: {channel.voltage:5.2f} V | {channel.current:5.3f} A | {channel.power:5.2f} W")
# Write to CSV if enabled
if csv_writer:
row = [
ts_dt.isoformat(), sensor_data.uptime_sec,
sensor_data.vin.voltage, sensor_data.vin.current, sensor_data.vin.power,
sensor_data.main.voltage, sensor_data.main.current, sensor_data.main.power,
sensor_data.usb.voltage, sensor_data.usb.current, sensor_data.usb.power
]
csv_writer.writerow(row)
except websockets.exceptions.ConnectionClosed as e: except websockets.exceptions.ConnectionClosed as e:
print(f"WebSocket connection closed: {e}") print(f"WebSocket connection closed: {e}")
except Exception as e: except Exception as e:
print(f"Error during WebSocket processing: {e}") print(f"Error during WebSocket processing: {e}")
finally:
if csv_file:
csv_file.close()
print(f"\nCSV file '{self.output_file}' saved.")
async def run(self): async def run(self):
"""Runs the logger.""" """Runs the logger."""
@@ -138,10 +94,9 @@ async def main():
parser.add_argument("host", help="Server's host address or IP (e.g., 192.168.1.10)") parser.add_argument("host", help="Server's host address or IP (e.g., 192.168.1.10)")
parser.add_argument("-u", "--username", required=True, help="Login username") parser.add_argument("-u", "--username", required=True, help="Login username")
parser.add_argument("-p", "--password", required=True, help="Login password") parser.add_argument("-p", "--password", required=True, help="Login password")
parser.add_argument("-o", "--output", help="Path to the output CSV file.")
args = parser.parse_args() args = parser.parse_args()
logger = OdroidPowerLogger(host=args.host, username=args.username, password=args.password, output_file=args.output) logger = OdroidPowerLogger(host=args.host, username=args.username, password=args.password)
await logger.run() await logger.run()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 272 KiB

View File

@@ -8,6 +8,5 @@
void wifi_init_sta(void); void wifi_init_sta(void);
void wifi_init_ap(void); void wifi_init_ap(void);
void initialize_sntp(void); void initialize_sntp(void);
void wifi_set_auto_reconnect(bool enable);
#endif // ODROID_POWER_MATE_PRIV_WIFI_H #endif // ODROID_POWER_MATE_PRIV_WIFI_H

View File

@@ -81,14 +81,6 @@ void wifi_scan_aps(wifi_ap_record_t** ap_records, uint16_t* count)
*count = 0; *count = 0;
*ap_records = NULL; *ap_records = NULL;
wifi_set_auto_reconnect(false);
wifi_ap_record_t ap_info;
if (esp_wifi_sta_get_ap_info(&ap_info) != ESP_OK)
{
esp_wifi_disconnect();
}
// Start scan, this is a blocking call // Start scan, this is a blocking call
if (esp_wifi_scan_start(NULL, true) == ESP_OK) if (esp_wifi_scan_start(NULL, true) == ESP_OK)
{ {
@@ -108,16 +100,6 @@ void wifi_scan_aps(wifi_ap_record_t** ap_records, uint16_t* count)
} }
} }
} }
wifi_set_auto_reconnect(true);
if (esp_wifi_sta_get_ap_info(&ap_info) != ESP_OK)
{
if (!nconfig_value_is_not_set(WIFI_SSID))
{
wifi_connect();
}
}
} }
esp_err_t wifi_get_current_ap_info(wifi_ap_record_t* ap_info) esp_err_t wifi_get_current_ap_info(wifi_ap_record_t* ap_info)

View File

@@ -16,13 +16,9 @@
#include "wifi.h" #include "wifi.h"
#include "indicator.h" #include "indicator.h"
static bool s_auto_reconnect = true;
static const char* TAG = "WIFI"; static const char* TAG = "WIFI";
void wifi_set_auto_reconnect(bool enable) { s_auto_reconnect = enable; }
static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{ {
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED) if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED)
@@ -50,18 +46,10 @@ static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t e
} }
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
{ {
led_set(LED_BLU, BLINK_TRIPLE); led_set(LED_RED, BLINK_TRIPLE);
wifi_event_sta_disconnected_t* event = (wifi_event_sta_disconnected_t*)event_data; wifi_event_sta_disconnected_t* event = (wifi_event_sta_disconnected_t*)event_data;
ESP_LOGW(TAG, "Disconnected from AP, reason: %s", wifi_reason_str(event->reason)); ESP_LOGW(TAG, "Disconnected from AP, reason: %s", wifi_reason_str(event->reason));
// ESP-IDF will automatically try to reconnect by default.
if (event->reason != WIFI_REASON_ASSOC_LEAVE)
{
if (s_auto_reconnect && !nconfig_value_is_not_set(WIFI_SSID))
{
ESP_LOGI(TAG, "Connection lost, attempting to reconnect...");
esp_wifi_connect();
}
}
} }
else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
{ {

View File

@@ -3,3 +3,4 @@
nvs,data,nvs,0x9000,24K, nvs,data,nvs,0x9000,24K,
phy_init,data,phy,0xf000,4K, phy_init,data,phy,0xf000,4K,
factory,app,factory,0x10000,2M, factory,app,factory,0x10000,2M,
littlefs, data, littlefs, ,1536K,
1 # ESP-IDF Partition Table
3 nvs,data,nvs,0x9000,24K,
4 phy_init,data,phy,0xf000,4K,
5 factory,app,factory,0x10000,2M,
6 littlefs, data, littlefs, ,1536K,