I think you are all giving too much importance to his sons' deaths as a cause of his depression. Sure, it was a source of it, but not the only one. It probably was caused by his education. When he was a child he his mother when he was only one year old, and later his father left him when he was only 5.
Since he became an Emperor, in order to make him the complete opposite of his father (uneducated, womaniser, bohemian and authoritarian) he was groomed to be the "perfect Emperor". Such education made him a very cult man, a polyglote who liked to study Sanskrit and Hebraic for example, but who had to leave his intelectual interests aside as he needed to face the burden of government since he was only 14.
The death of his sons in the 1840's made him depressed, but by the 1860's he had overcame it. What changed everything after the 1870's was basically three facts. The first was his first travel abroad, when he finally could pursue his intelectual interests (meeting artists, visiting museums and touristic places in Europe). After this, when he came back to Brazil, all he wanted was to plan other travels.
Then there the problems regarding his succession. He knew that his eldest daughter was disliked by the Brazilian elite (as she was too much religious, abolitionist, married with a hated Frenchman, among other things). The doubts about giving the throne to her or passing it directly to her first son or even to his grandson by his other daughter Leopoldina were a burden to him.
Finally, there was his diabetes, that by the end of the 1880's were causing him so much problems (especially somnolence during the day) that he was avoiding most of his public duties.
Also, while a son as a heir could probably help to keep the monarchy it wouldn't avoid the economical and political changes brought by the War of the Tripple Alliance and by Abolitionism. My oppinion is that if you want to keep the Empire the best bet would be avoid the war entirely. Having "Peter III" to succeed his father could delay the fall, but the social forces that made the Republic would still be there.