Skip to content

Commit be9782c

Browse files
nkarstensdlech
authored andcommitted
Move PybricksHub client creation into constructor
Moves client creation into the PybricksHub constructor. A future change will move this into a subclass specific for BLE or USB, so configuring this is more appropriately done in the constructor instead of the connect method. The disconnect logic is moved into a class method so that it can be shared by both BLE and USB implementations. Temporarily comments out a message that prints the device name as this is no longer available in the connect method. Signed-off-by: Nate Karstens <[email protected]>
1 parent bae50f7 commit be9782c

File tree

3 files changed

+22
-19
lines changed

3 files changed

+22
-19
lines changed

pybricksdev/cli/__init__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,22 +183,21 @@ async def run(self, args: argparse.Namespace):
183183
print("--name is required for SSH connections", file=sys.stderr)
184184
exit(1)
185185

186-
hub = EV3Connection()
187186
device_or_address = socket.gethostbyname(args.name)
187+
hub = EV3Connection(device_or_address)
188188
elif args.conntype == "ble":
189189
# It is a Pybricks Hub with BLE. Device name or address is given.
190-
hub = PybricksHub()
191190
print(f"Searching for {args.name or 'any hub with Pybricks service'}...")
192191
device_or_address = await find_device(args.name)
192+
hub = PybricksHub(device_or_address)
193193

194194
elif args.conntype == "usb":
195195
hub = REPLHub()
196-
device_or_address = None
197196
else:
198197
raise ValueError(f"Unknown connection type: {args.conntype}")
199198

200199
# Connect to the address and run the script
201-
await hub.connect(device_or_address)
200+
await hub.connect()
202201
try:
203202
with _get_script_path(args.file) as script_path:
204203
await hub.run(script_path, args.wait)

pybricksdev/connections/ev3dev.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,13 @@ class EV3Connection:
1818
_USER = "robot"
1919
_PASSWORD = "maker"
2020

21+
def __init__(self, address: str):
22+
self._address = address
23+
2124
def abs_path(self, path):
2225
return os.path.join(self._HOME, path)
2326

24-
async def connect(self, address):
27+
async def connect(self):
2528
"""Connects to ev3dev using SSH with a known IP address.
2629
2730
Arguments:
@@ -33,9 +36,9 @@ async def connect(self, address):
3336
Connect failed.
3437
"""
3538

36-
print("Connecting to", address, "...", end=" ")
39+
print("Connecting to", self._address, "...", end=" ")
3740
self.client = await asyncssh.connect(
38-
address, username=self._USER, password=self._PASSWORD
41+
self._address, username=self._USER, password=self._PASSWORD
3942
)
4043
print("Connected.", end=" ")
4144
self.client.sftp = await self.client.start_sftp_client()

pybricksdev/connections/pybricks.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ class PybricksHub:
7878
has not been connected yet or the connected hub has Pybricks profile < v1.2.0.
7979
"""
8080

81-
def __init__(self):
81+
def __init__(self, device: BLEDevice):
8282
self.connection_state_observable = BehaviorSubject(ConnectionState.DISCONNECTED)
8383
self.status_observable = BehaviorSubject(StatusFlag(0))
8484
self._stdout_subject = Subject()
@@ -120,6 +120,11 @@ def __init__(self):
120120
# File handle for logging
121121
self.log_file = None
122122

123+
def handle_disconnect(_: BleakClient):
124+
self._handle_disconnect()
125+
126+
self.client = BleakClient(device, disconnected_callback=handle_disconnect)
127+
123128
@property
124129
def stdout_observable(self) -> Observable[bytes]:
125130
"""
@@ -227,18 +232,20 @@ def _pybricks_service_handler(self, _: int, data: bytes) -> None:
227232
if self._enable_line_handler:
228233
self._handle_line_data(payload)
229234

230-
async def connect(self, device: BLEDevice):
231-
"""Connects to a device that was discovered with :meth:`pybricksdev.ble.find_device`
235+
def _handle_disconnect(self):
236+
logger.info("Disconnected!")
237+
self.connection_state_observable.on_next(ConnectionState.DISCONNECTED)
232238

233-
Args:
234-
device: The device to connect to.
239+
async def connect(self):
240+
"""Connects to a device that was discovered with :meth:`pybricksdev.ble.find_device`
235241
236242
Raises:
237243
BleakError: if connecting failed (or old firmware without Device
238244
Information Service)
239245
RuntimeError: if Pybricks Protocol version is not supported
240246
"""
241-
logger.info(f"Connecting to {device.name}")
247+
# TODO: Fix this
248+
# logger.info(f"Connecting to {device.name}")
242249

243250
if self.connection_state_observable.value != ConnectionState.DISCONNECTED:
244251
raise RuntimeError(
@@ -252,12 +259,6 @@ async def connect(self, device: BLEDevice):
252259
self.connection_state_observable.on_next, ConnectionState.DISCONNECTED
253260
)
254261

255-
def handle_disconnect(_: BleakClient):
256-
logger.info("Disconnected!")
257-
self.connection_state_observable.on_next(ConnectionState.DISCONNECTED)
258-
259-
self.client = BleakClient(device, disconnected_callback=handle_disconnect)
260-
261262
await self.client.connect()
262263

263264
stack.push_async_callback(self.disconnect)

0 commit comments

Comments
 (0)