Add a .close() method to port interfaces
authorDan White <dan@whiteaudio.com>
Fri, 2 Nov 2012 23:39:58 +0000 (18:39 -0500)
committerDan White <dan@whiteaudio.com>
Fri, 2 Nov 2012 23:39:58 +0000 (18:39 -0500)
python-lib/usbio.py

index 3b8d28be87289982a9171b46159bd7be2eb2fbc1..65c1eab1acb0458c3b81693bde7cad718fbdf3c6 100644 (file)
@@ -138,6 +138,25 @@ class I2C(object):
         self.set_pindir(pindir)
         self.set_pinstate(pinstate)
 
+    def close(self):
+        """Set all pins to input and release the port.  Class is useless after
+        calling this method.
+        """
+        cmd = chr(self.ftdi.SET_BITS_LOW) + chr(0) + chr(0)
+        self._raw_write(cmd)
+        self.ftdi.usb_close(self.context)
+
+    def _raw_write(self, data):
+        """Write data as
+        """
+        #translate data to a string
+        if not isinstance(data, str):
+            data = ''.join(map(chr, data))
+        ret = self.ftdi.write_data(self.context, data, len(data))
+        if ret < 0:
+            raise FTDI_Error(self.ftdi.get_error_string(self.context))
+
+
     def _clear_scl(self):
         self.io[self.scl] = 1
         self.ftdi.set_bitmode(self.context, int(self.io), self.ftdi.BITMODE_BITBANG)
@@ -405,6 +424,14 @@ class SPI(object):
 
         self.ftdi.usb_purge_buffers(self.context)
 
+    def close(self):
+        """Set all pins to input and release the port.  Class is useless after
+        calling this method.
+        """
+        cmd = chr(self.ftdi.SET_BITS_LOW) + chr(0) + chr(0)
+        self._raw_write(cmd)
+        self.ftdi.usb_close(self.context)
+
     def _raw_write(self, data):
         """Write data as
         """