Introduce the concept of shadow pin state.  This is needed because some of the devices attached to GPIOs will switch at relatively low voltages, which is desirable (inevitable in the case of two of my large relay boards where I think it is a consequence of their 3.3V compatibility), but then when the GPIO reads-back the pin state it thinks the device is on when it is actually off.