Device query: fix some bugs, add helper functions