Browse Source

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 years ago
parent
commit
c561b2f181
1 changed files with 17 additions and 4 deletions
  1. 17
    4
      pdbuddy/__init__.py

+ 17
- 4
pdbuddy/__init__.py View File

17
         :param sp: the serial port of the device
17
         :param sp: the serial port of the device
18
         :type sp: str or `serial.tools.list_ports.ListPortInfo`
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
     def send_command(self, cmd):
31
     def send_command(self, cmd):
23
         """Send a command to the PD Buddy Sink, returning the result
32
         """Send a command to the PD Buddy Sink, returning the result
29
             printed as a response to the command.
38
             printed as a response to the command.
30
         """
39
         """
31
         # Send the command
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
         # Read the result
44
         # Read the result
36
         answer = b""
45
         answer = b""
37
         while not answer.endswith(b"PDBS) "):
46
         while not answer.endswith(b"PDBS) "):
38
-            answer += self.port.read(1)
47
+            answer += self._port.read(1)
39
         answer = answer.split(b"\r\n")
48
         answer = answer.split(b"\r\n")
40
 
49
 
41
         # Remove the echoed command and prompt
50
         # Remove the echoed command and prompt
42
         answer = answer[1:-1]
51
         answer = answer[1:-1]
43
         return answer
52
         return answer
44
 
53
 
54
+    def close(self):
55
+        """Close the serial port"""
56
+        self._port.close()
57
+
45
     def help(self):
58
     def help(self):
46
         """Returns the help text from the PD Buddy Sink"""
59
         """Returns the help text from the PD Buddy Sink"""
47
         return self.send_command("help")
60
         return self.send_command("help")

Loading…
Cancel
Save