-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhardware.py
More file actions
180 lines (157 loc) · 5.46 KB
/
hardware.py
File metadata and controls
180 lines (157 loc) · 5.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# # #!/usr/bin/env python3
# # """
# # hardware.py - Dongle Verification Utility
# # Phase 1: Mock Version for 50% Milestone
#
# # This module acts as the bridge between our software and the physical Arduino dongle.
# # Currently implements a mock version that simulates hardware detection.
# # """
#
# # def is_dongle_present():
# # """
# # A mock function that simulates the hardware check.
#
# # Returns:
# # bool: Always returns True for mock implementation
# # """
# # print("DEBUG: Hardware check simulated. Always returns True.")
# # return True
#
#
# # def main():
# # """
# # Simple test function to demonstrate the dongle check.
# # """
# # print("=== Dongle Scanner Test ===")
# # print("Checking for hardware dongle...")
#
# # if is_dongle_present():
# # print("✓ Dongle detected!")
# # else:
# # print("✗ Dongle not found!")
#
#
# # if __name__ == "__main__":
# # main()
#
# #!/usr/bin/env python3
# """
# hardware.py - Dongle Verification Utility
# Phase 1: Mock Version for 50% Milestone
#
# This module acts as the bridge between our software and the physical Arduino dongle.
# Currently implements a mock version that simulates hardware detection.
# """
#
# def is_dongle_present():
# """
# A mock function that simulates the hardware check.
#
# Returns:
# bool: Always returns True for mock implementation
# """
# print("DEBUG: Hardware check simulated. Always returns True.")
# return True
#
#
# def main():
# """
# Simple test function to demonstrate the dongle check.
# """
# print("=== Dongle Scanner Test ===")
# print("Checking for hardware dongle...")
#
# if is_dongle_present():
# print("[SUCCESS] Dongle detected!")
# else:
# print("[ERROR] Dongle not found!")
#
#
# if __name__ == "__main__":
# main()
# !/usr/bin/env python3
"""
hardware.py - Real Dongle Verification Utility
This module scans all active COM ports to find a device that
broadcasts the correct, secret Dongle ID.
"""
import serial
import serial.tools.list_ports
import configparser
import os
import logging
def get_dongle_config():
"""Reads the required dongle ID and requirement from the config.ini file."""
try:
config = configparser.ConfigParser()
# Find config.ini relative to this script's location
config_path = os.path.join(os.path.dirname(__file__), 'config.ini')
if not os.path.exists(config_path):
logging.error("[Hardware] config.ini not found. Cannot verify dongle.")
return None, False
config.read(config_path)
dongle_id = config.get('Hardware', 'dongle_id')
hardware_required = config.getboolean('Hardware', 'hardware_required')
return dongle_id, hardware_required
except Exception as e:
logging.error(f"[Hardware] Error reading config.ini: {e}")
return None, False
def is_dongle_present():
"""
Scans all available serial (COM) ports for the hardware dongle.
Returns:
bool: True if the dongle is found and sends the correct ID, False otherwise.
"""
expected_id, hardware_required = get_dongle_config()
# If hardware is not required, just return True (like the mock)
if not hardware_required:
logging.info("[Hardware] Hardware check is disabled in config.ini. Skipping.")
return True
if not expected_id:
logging.warning("[Hardware] Could not read expected dongle ID from config.")
return False
available_ports = serial.tools.list_ports.comports()
if not available_ports:
logging.warning("[Hardware] No serial ports detected.")
return False
for port_info in available_ports:
port = port_info.device
try:
# Connect to the port with a 1-second read timeout
# The baud rate (9600) MUST match your dongle.ino sketch
with serial.Serial(port, 9600, timeout=2) as ser:
# Read a few lines to give the Arduino time to respond
# and to clear any partial data in the buffer
for _ in range(3):
line_bytes = ser.readline()
try:
line = line_bytes.decode('utf-8').strip()
except UnicodeDecodeError:
continue # This port is sending garbage, not our ID
if line == expected_id:
logging.info(f"[Hardware] Dongle verified on port {port}")
return True
except serial.SerialException:
# Port is busy or inaccessible. Ignore and move to the next.
continue
except Exception as e:
logging.error(f"[Hardware] Error checking port {port}: {e}")
continue
# If we finished the loop without finding the dongle
logging.warning("[Hardware] Dongle check failed. ID not found on any port.")
return False
def main():
"""
Simple test function to demonstrate the real dongle check.
"""
# We must configure logging to see the output from this module
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
print("=== Real Dongle Scanner Test ===")
print("This test will check all COM ports for the dongle.")
print("Checking for hardware dongle...")
if is_dongle_present():
print("[SUCCESS] Dongle detected!")
else:
print("[ERROR] Dongle not found!")
if __name__ == "__main__":
main()