Newly fixed version, works for multiple sensors and keeps state