This commit is contained in:
yrx
2026-08-11 13:38:27 +08:00
parent abbf30d7c0
commit 6556cfcf74
39 changed files with 678 additions and 58 deletions
Binary file not shown.
+144
View File
@@ -0,0 +1,144 @@
import importlib.util
from pathlib import Path
import sys
import types
import unittest
from unittest import mock
class _StopMonitor(Exception):
pass
class _FakeTime:
now_ms = 0
stop_at_ms = None
@classmethod
def reset(cls, stop_at_ms=None):
cls.now_ms = 0
cls.stop_at_ms = stop_at_ms
@classmethod
def ticks_ms(cls):
return cls.now_ms
@classmethod
def sleep_ms(cls, milliseconds):
cls.now_ms += milliseconds
if cls.stop_at_ms is not None and cls.now_ms >= cls.stop_at_ms:
raise _StopMonitor()
def _load_power_module():
module_path = Path(__file__).resolve().parents[1] / "power.py"
module_name = "power_charging_shutdown_test"
maix_module = types.ModuleType("maix")
maix_module.time = _FakeTime
previous_maix = sys.modules.get("maix")
sys.modules["maix"] = maix_module
try:
spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
finally:
if previous_maix is None:
sys.modules.pop("maix", None)
else:
sys.modules["maix"] = previous_maix
power = _load_power_module()
class ChargingShutdownTests(unittest.TestCase):
def setUp(self):
self.config_patch = mock.patch.multiple(
power.config,
CHARGING_SHUTDOWN_ENABLED=True,
CHARGING_DIAGNOSTIC_LOG_ENABLED=False,
CHARGING_CHECK_INTERVAL_MS=5000,
CHARGING_CURRENT_THRESHOLD_MA=100.0,
CHARGING_CONFIRM_COUNT=2,
CHARGING_NOTIFY_TIMEOUT_MS=30000,
CHARGING_EXIT_SCRIPT="/tmp/charging_exit.sh",
)
self.config_patch.start()
self.network_manager = mock.Mock()
self.network_manager.safe_enqueue_and_wait.return_value = True
network_module = types.ModuleType("network")
network_module.network_manager = self.network_manager
self.network_module_patch = mock.patch.dict(
sys.modules,
{"network": network_module},
)
self.network_module_patch.start()
_FakeTime.reset()
def tearDown(self):
self.network_module_patch.stop()
self.config_patch.stop()
def test_two_charging_samples_notify_server_and_exit(self):
popen_calls = []
with (
mock.patch.object(power, "get_current", return_value=-200.0),
mock.patch.object(power.os.path, "isfile", return_value=True),
mock.patch.object(
power.subprocess,
"Popen",
side_effect=lambda args: popen_calls.append(args),
),
):
power.charging_shutdown_monitor()
self.assertEqual(_FakeTime.now_ms, 5000)
self.assertEqual(len(popen_calls), 1)
self.network_manager.safe_enqueue_and_wait.assert_called_once_with(
{"poweroff": "充电中"}, 2, high=True, timeout_ms=30000
)
def test_discharging_does_not_notify_or_exit(self):
_FakeTime.reset(stop_at_ms=10000)
popen_calls = []
with (
mock.patch.object(power, "get_current", return_value=200.0),
mock.patch.object(power.os.path, "isfile", return_value=True),
mock.patch.object(
power.subprocess,
"Popen",
side_effect=lambda args: popen_calls.append(args),
),
self.assertRaises(_StopMonitor),
):
power.charging_shutdown_monitor()
self.assertEqual(popen_calls, [])
self.network_manager.safe_enqueue_and_wait.assert_not_called()
def test_failed_sample_resets_confirmation_count(self):
popen_calls = []
currents = iter((-200.0, 0.0, -200.0, -200.0))
with (
mock.patch.object(power, "get_current", side_effect=lambda: next(currents)),
mock.patch.object(power.os.path, "isfile", return_value=True),
mock.patch.object(
power.subprocess,
"Popen",
side_effect=lambda args: popen_calls.append(args),
),
):
power.charging_shutdown_monitor()
self.assertEqual(_FakeTime.now_ms, 15000)
self.assertEqual(len(popen_calls), 1)
self.network_manager.safe_enqueue_and_wait.assert_called_once_with(
{"poweroff": "充电中"}, 2, high=True, timeout_ms=30000
)
if __name__ == "__main__":
unittest.main()
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Read the digital voltage level on the MaixCAM P21 pin.
P21 is a digital GPIO pin, not the MaixCAM analog ADC input. Therefore this
script can only distinguish LOW and HIGH. For a continuous voltage value,
connect the signal to the board's B3/ADC pin and use ADC channel 0 instead.
Do not apply more than 3.3 V to P21. Always connect the signal ground to the
MaixCAM ground.
"""
from maix import app, gpio, pinmap, time
PIN = "P21"
IO_HIGH_VOLTAGE = 3.3
SAMPLE_INTERVAL_MS = 200
def find_gpio_function(pin):
"""Return the GPIO function supported by the requested physical pin."""
functions = pinmap.get_pin_functions(pin)
gpio_functions = [name for name in functions if name.startswith("GPIO")]
print(f"{pin} supported functions: {', '.join(functions)}")
if not gpio_functions:
raise RuntimeError(f"{pin} does not provide a GPIO input function")
return gpio_functions[0]
def main():
gpio_function = find_gpio_function(PIN)
pinmap.set_pin_function(PIN, gpio_function)
voltage_input = gpio.GPIO(gpio_function, gpio.Mode.IN)
print(f"Reading {PIN} through {gpio_function}")
print("P21 only reports LOW/HIGH; displayed voltage is an estimate.")
print("Press the MaixCAM exit key to stop.")
while not app.need_exit():
level = voltage_input.value()
estimated_voltage = IO_HIGH_VOLTAGE if level else 0.0
state = "HIGH" if level else "LOW"
print(
f"{PIN}: level={level}, state={state}, "
f"estimated_voltage={estimated_voltage:.1f} V"
)
time.sleep_ms(SAMPLE_INTERVAL_MS)
if __name__ == "__main__":
try:
main()
except Exception as error:
print(f"P21 voltage detection failed: {error}")
print("Check that this MaixCAM model exposes P21 as a GPIO pin.")
raise
+139
View File
@@ -0,0 +1,139 @@
import json
import sys
import types
import unittest
class _FakeTime:
@staticmethod
def sleep(_seconds):
pass
@staticmethod
def sleep_ms(_milliseconds):
pass
@staticmethod
def ticks_ms():
return 0
@staticmethod
def ticks_diff(left, right):
return left - right
class _FakeLogger:
def debug(self, *_args, **_kwargs):
pass
def info(self, *_args, **_kwargs):
pass
def warning(self, *_args, **_kwargs):
pass
def error(self, *_args, **_kwargs):
pass
class _FakeSocket:
def __init__(self, recv_data=b""):
self.recv_data = recv_data
self.closed = False
def close(self):
self.closed = True
def recv(self, _size, *_flags):
return self.recv_data
class _StopAfterCallback:
def __init__(self):
self.stopped = False
def is_set(self):
return self.stopped
maix_module = types.ModuleType("maix")
maix_module.time = _FakeTime
maix_module.network = types.SimpleNamespace()
maix_module.err = types.SimpleNamespace()
sys.modules.setdefault("maix", maix_module)
sys.modules.setdefault("ujson", json)
netcore_module = types.ModuleType("archery_netcore")
netcore_module.get_config = lambda: {"SERVER_IP": "127.0.0.1", "SERVER_PORT": 1234}
netcore_module.parse_packet = lambda _packet: (0, {})
netcore_module.make_packet = lambda *_args, **_kwargs: b""
netcore_module.actions_for_inner_cmd = lambda *_args, **_kwargs: []
sys.modules["archery_netcore"] = netcore_module
hardware_module = types.ModuleType("hardware")
hardware_module.hardware_manager = types.SimpleNamespace()
sys.modules["hardware"] = hardware_module
power_module = types.ModuleType("power")
power_module.get_bus_voltage = lambda: 0
power_module.voltage_to_percent = lambda _voltage: 0
sys.modules["power"] = power_module
import logger_manager
import wifi
import network
class WiFiFailoverTests(unittest.TestCase):
def setUp(self):
logger_manager.logger_manager._logger = _FakeLogger()
def test_monitor_switches_when_sta_association_is_lost(self):
manager = wifi.wifi_manager
stop_event = _StopAfterCallback()
callbacks = []
manager._wifi_socket = _FakeSocket()
manager._wifi_quality_stop_event = stop_event
manager._network_type_callback = lambda: "wifi"
manager.is_sta_associated = lambda: False
manager._get_wifi_rssi_dbm = lambda: None
def on_poor_quality():
callbacks.append(True)
stop_event.stopped = True
manager._on_poor_quality_callback = on_poor_quality
manager._quality_monitor_loop()
self.assertEqual(callbacks, [True])
self.assertIsNone(manager.last_wifi_rtt_ms)
def test_tls_connection_check_rejects_lost_sta_association(self):
manager = network.network_manager
sock = _FakeSocket()
wifi.wifi_manager._wifi_socket = sock
wifi.wifi_manager._wifi_connected = True
wifi.wifi_manager._wifi_ip = "192.168.1.2"
wifi.wifi_manager.is_sta_associated = lambda: False
manager._tcp_connected = True
self.assertFalse(manager._check_wifi_connection())
self.assertTrue(sock.closed)
self.assertIsNone(wifi.wifi_manager.wifi_socket)
self.assertFalse(manager.tcp_connected)
def test_receive_eof_marks_wifi_tcp_disconnected(self):
manager = network.network_manager
sock = _FakeSocket(recv_data=b"")
wifi.wifi_manager._wifi_socket = sock
manager._tcp_connected = True
self.assertEqual(manager.receive_tcp_data_via_wifi(), b"")
self.assertTrue(sock.closed)
self.assertIsNone(wifi.wifi_manager.wifi_socket)
self.assertFalse(manager.tcp_connected)
if __name__ == "__main__":
unittest.main()