A characterization of semiprojectivity for subhomogeneous $C^*$-algebras