What you've got is a poor connection in the brake wiring. And it's about 50/50 odds on it being the truck or the trailer. Most often it is the connector at the bumper that gets wet or corroded.
It will be the brake system, not the lighting system. Your truck checks the brake system by monitoring resistance through the wiring. Intermittently it is not seeing the correct resistance. Either because of a poor connection, or because it is shorting to ground. You'll just have to find that bad connection, and you want to start at the bumper plug. Then work your way back to the brakes.