This sort of thing is much easier if you use entity IDs rather than device IDs. There’s an example here which you may be able to build on: