def load_frames(path):
    frame_size = 220
    frames = np.fromfile(path, dtype = 'uint8')
    return frames[:frames.size//frame_size*frame_size].reshape((-1, frame_size))

frames = load_frames('Bochum_2020-12-02_8463/SDRSharp_20201202_060001Z_8463752190Hz_IQ_2M5_dec8_CE5_frames.u8')

"""
Explanation: In this notebook we analyzed the frames decoded off the low datarate (PCM/PM/PSK 2048baud with 65536Hz subcarrier) signal of the Chang'e 5 lander+ascender combo at 8463.7 MHz transmitted from the lunar surface on 2020-12-02.
End of explanation
"""


aos = [CE5_AOSFrame.parse(f) for f in frames]

collections.Counter([a.primary_header.transfer_frame_version_number for a in aos])

collections.Counter([a.primary_header.spacecraft_id for a in aos
                    if a.primary_header.transfer_frame_version_number == 1])

collections.Counter([a.primary_header.virtual_channel_id for a in aos
                    if a.primary_header.transfer_frame_version_number == 1])

[a.primary_header for a in aos if a.primary_header.virtual_channel_id == 1][:10]

fc = np.array([a.primary_header.virtual_channel_frame_count for a in aos])
t = get_timestamps([a.insert_zone.timestamp for a in aos])

plt.figure(figsize = (10,6), facecolor = 'w')
plt.plot(t, fc, '.')
plt.title("Chang'e 5 spacecraft 91 virtual channel 1 timestamps")
plt.xlabel('AOS frame timestamp')
plt.ylabel('AOS virtual channel frame counter');

plt.figure(figsize = (10,6), facecolor = 'w')
plt.plot(t[1:], np.diff(fc)-1)
plt.title("Chang'e 5 spacecraft 91 virtual channel 1 frame loss")
plt.xlabel('AOS frame timestamp')
plt.ylabel('Frame loss');

vc1_packets = list(ccsds.extract_space_packets(aos, 91, 1, get_timestamps = True))

vc1_sp_headers = [ccsds.SpacePacketPrimaryHeader.parse(p[0]) for p in vc1_packets]

"""
Explanation: AOS frames
AOS frames come from spacecraft 91 and virtual channels 1.
End of explanation
"""


vc1_apids = collections.Counter([p.APID for p in vc1_sp_headers])
vc1_apids

vc1_by_apid = {apid : [p for h,p in zip(vc1_sp_headers, vc1_packets)
                           if h.APID == apid] for apid in vc1_apids}

plot_apids(vc1_by_apid, 91, 1)

"""
Explanation: There are space packets in may APIDs. The contents of each APID are shown belown in plot form, but it's not easy to guess what any of the values mean.
End of explanation
"""


