If you consider that hex values for color range from 00 to FF for each color, it seems as though it would not be too difficult to check the relative brightness of any hex value.
Since 00 is dark and FF is light, the mid point would be about 88. So, if you have a string of hex values like #404040, you know that each RGB value is less than 88, which would mean the color is on the dark side.
The problem lies when you have, for instance a color like FF0088. As you can tell red is very light, green is very dark but blue is right in the middle, which would mean the color is somewhere near the middle of your scale.
You would need to determine which value is your cutoff point. I woud say to break the hex string into 3 parts and assign a value to each part depending on where it lies in the scale. Then add up all three values to get the final result. If the color ends up being right in the middle, you would probably be ok with black or white text on it.