Ver código fonte

Improved Sink API

Now the port is not part of the API, there's a method to close it,
__init__ can take a string in addition to the objects it used to take,
and the class is a context manager for the with statement.  I can
confidently say that these are all great changes.
Clara Hobbs 7 anos atrás
pai
commit
c561b2f181
1 arquivos alterados com 17 adições e 4 exclusões
  1. 17
    4
      pdbuddy/__init__.py

+ 17
- 4
pdbuddy/__init__.py Ver arquivo

@@ -17,7 +17,16 @@ class Sink:
17 17
         :param sp: the serial port of the device
18 18
         :type sp: str or `serial.tools.list_ports.ListPortInfo`
19 19
         """
20
-        self.port = serial.Serial(sp.device, baudrate=115200)
20
+        try:
21
+            self._port = serial.Serial(sp, baudrate=115200)
22
+        except ValueError:
23
+            self._port = serial.Serial(sp.device, baudrate=115200)
24
+
25
+    def __enter__(self):
26
+        return self
27
+
28
+    def __exit__(self, exc_type, exc_value, traceback):
29
+        self._port.close()
21 30
 
22 31
     def send_command(self, cmd):
23 32
         """Send a command to the PD Buddy Sink, returning the result
@@ -29,19 +38,23 @@ class Sink:
29 38
             printed as a response to the command.
30 39
         """
31 40
         # Send the command
32
-        self.port.write(bytes(cmd, "utf-8") + b"\r\n")
33
-        self.port.flush()
41
+        self._port.write(bytes(cmd, "utf-8") + b"\r\n")
42
+        self._port.flush()
34 43
 
35 44
         # Read the result
36 45
         answer = b""
37 46
         while not answer.endswith(b"PDBS) "):
38
-            answer += self.port.read(1)
47
+            answer += self._port.read(1)
39 48
         answer = answer.split(b"\r\n")
40 49
 
41 50
         # Remove the echoed command and prompt
42 51
         answer = answer[1:-1]
43 52
         return answer
44 53
 
54
+    def close(self):
55
+        """Close the serial port"""
56
+        self._port.close()
57
+
45 58
     def help(self):
46 59
         """Returns the help text from the PD Buddy Sink"""
47 60
         return self.send_command("help")

Carregando…
Cancelar
Salvar