sort of like a rattlesnake
This is a great topic. The described incidents are great examples of important SD principles. Great job in de-escalating (or in making the undercover cops look a little dopey) what could have become very bad situations.
In addition to communicating your situational awareness (ie., BG have lost their element of surprise), your resolve, and your clear intent to control the situation, your command voice also serves to alert any others around who could then be witnesses (because now they're watching), render assistance, or call for help/police.
The warning clears up any doubt in the BG mind that you might be a willing or easy victim. You've made it abundantly clear that you see him, your defensive posture and command voice makes clear that you'll fight back (with whatever means you might have - they have to be wondering what that would be) and that you consider him (them) a threat. Anyone with innocent intentions would get the message and leave, rather fast; continuing to advance would confirm your reasons for the warning. I'd like to think that most BG would hightail it after you blew their cover and their element of surprise.
Either way you have acted decisively and done what you can to descalate while ready for the STHTF. Great job.