I’d recommend looking into the segmented regression aka piecewise regression
I’ve got a notebook on this (in the Julia language) here, though coming back to this years later the images aren’t rendering properly. The code might be enough to get the idea though.
EDIT: Looking at your simulated data, the piecewise constant approach might be better than the piecewise linear