import json
import matplotlib.pyplot as plt
import statistics
import math

#"20m1000pIndoorClear0_0005.json"
#"28m1000pOutdoorClear0_1.json"
#"10m1000pIndoorClear0_0005.json"
#"5m1000pIndoorClear0_0005.json"
#"10m1000pOutdoor0_5(roh5m).json"

file = "10m1000pIndoorClear0_0005.json"
meters_txt = file.split('m')[0]
packets_txt = file.split('m')[1]
packets_txt = packets_txt.split('p')[0]

f = open(file, "r")   
data = json.loads(f.read())
f.close()

iterator = 0
lost = 0
counter = 0
latency = []
period_time = []
canceled = 0

treshhold = 100

while iterator < len(data) - 1:
    if data[iterator]['_source']['layers']['frame']['frame.protocols'] == "wpan:zbee_nwk:data":
        packet = data[iterator]
        period_time.append(data[iterator]['_source']['layers']['frame']['frame.time_epoch'])
        search = True
        i = 1
        while search:
            if iterator + i > len(data)-1:
                search = False
                lost = lost + 1
                break
            if data[iterator+i]['_source']['layers']['frame']['frame.protocols'] == "wpan":
                if data[iterator]['_source']['layers']['wpan']['wpan.seq_no'] == data[iterator+i]['_source']['layers']['wpan']['wpan.seq_no']:
                    if float(data[iterator+i]['_source']['layers']['frame']['frame.time_epoch']) - float(data[iterator]['_source']['layers']['frame']['frame.time_epoch']) < treshhold:
                        latency.append((float(data[iterator+i]['_source']['layers']['frame']['frame.time_epoch']) - float(data[iterator]['_source']['layers']['frame']['frame.time_epoch'])))
                    else:
                        canceled = canceled + 1
                    counter = counter + 1
                    search = False
                elif data[iterator]['_source']['layers']['wpan']['wpan.seq_no'] < data[iterator+i]['_source']['layers']['wpan']['wpan.seq_no']:
                    search = False
                    lost = lost + 1
                else:
                    i = i + 1
            else:
                i = i + 1
        iterator = iterator + 1
    else:
        iterator = iterator + 1
        
print(f"succesful packets: {counter}")
print(f"lost: {lost}")
print(f"doubled packets: {(counter + lost) - 1000}")

jitter = statistics.stdev(latency)*1000000
print(f"jitter: {jitter} us")

period = 0
while i < len(period_time)-1:
    period = period + (float(period_time[i+1]) - float(period_time[i]))
    i = i + 2

period = period/(len(period_time)/2)
print(f"period: {period}")

plt.plot(latency)
plt.ylabel(f'zpoždění [s]\n(střední hodnota: {round((statistics.mean(latency))*1000,5)} ms)')
if canceled > 0:
    plt.xlabel(f'úspěšné packety({counter-canceled})\n({canceled} zrušené - velmi nepřesné měření)')
else:
    plt.xlabel(f'úspěšné packety({counter})')
if (counter + lost) - 1000 < 0:
    lost = lost + abs((counter + lost) - 1000)
    plt.title(f"Překážka - venku\n({meters_txt} m, {packets_txt} packetů, průměrná perioda: {round(period,4)} s)\njitter: {jitter} us, ztracené: {lost}")
else:
    plt.title(f"Překážka - venku\n({meters_txt} m, {packets_txt} packetů, průměrná perioda: {round(period,4)} s)\njitter: {jitter} us, ztracené: {lost}, zdvojené: {(counter + lost) - 1000}")
plt.grid(True)
plt.show()


######################
### LQI - scenar 1 ### 
plt.figure()
plt.subplot(211)
plt.scatter([20, 10, 5], [104, 114, 125.6])
plt.ylabel("LQI koordinátor -> Zigbee zařízení")
plt.xlabel("Vzdálenost [m]")
plt.grid(True)

plt.subplot(212)
plt.scatter([20, 10, 5], [175.6, 172.2, 193.5])
plt.ylabel("LQI Zigbee zařízení -> koordinátor")
plt.xlabel("Vzdálenost [m]")
plt.grid(True)

### Zpoždění v závislosti na periodě - scenar 1 ###
plt.figure()
plt.plot([0.5, 0.25, 0.1, 0.05],[0.54501, 0.54501, 0.545, 0.545])
plt.plot([0.5, 0.25, 0.1, 0.05],[0.54492, 0.54496, 0.54495, 0.54495])
plt.plot([0.5, 0.25, 0.1, 0.05],[0.54489, 0.54489, 0.54487, 0.54492])
plt.ylabel("Střední hodnota zpoždění [ms]")
plt.xlabel("Perioda mezi packety [s]")
plt.title("Zpoždění Zigbee sítě pro scénář 1")
plt.legend(["20 m", "10 m", "5 m"])
plt.grid(True)

### Jitter v závislosti na periodě - scenar 1 ###
plt.figure()
plt.plot([0.5, 0.25, 0.1, 0.05],[0.54517, 0.52246, 0.50613, 0.53151])
plt.plot([0.5, 0.25, 0.1, 0.05],[0.54262, 0.52171, 0.55945, 0.51842])
plt.plot([0.5, 0.25, 0.1, 0.05],[0.53806, 0.52969, 0.52599, 0.52288])
plt.ylabel("Jitter [µs]")
plt.xlabel("Perioda mezi packety [s]")
plt.title("Jitter Zigbee sítě pro scénář 1")
plt.legend(["20 m", "10 m", "5 m"])
plt.grid(True)

### Ztrátovost packetů - scenar 1 ###
plt.figure()
plt.plot([0.05, 0.1, 0.25, 0.5],[32, 54.9, 19.4, 24.9])
plt.plot([0.05, 0.1, 0.25, 0.5],[10.8, 36.2, 16.9, 9.6])
plt.plot([0.05, 0.1, 0.25, 0.5],[2.4, 0.9, 0.1, 0.5])
plt.ylabel("Ztrátovost [%]")
plt.xlabel("Perioda mezi packety [s]")
plt.title("Ztrátovost packetů pro scénář 1")
plt.legend(["20 m", "10 m", "5 m"])
plt.grid(True)
plt.show()

######################
### LQI - scenar 2 ### 
plt.figure()
plt.subplot(211)
plt.plot([5,10,15,20,23,24,25,26,27,29], [110.8, 88.8, 56.4, 15.6, 13.2, 34, 6, 31.6, 31.6, 7.2])
plt.ylabel("LQI koordinátor -> Zigbee zařízení")
plt.xlabel("Vzdálenost [m]")
plt.grid(True)

plt.subplot(212)
plt.plot([5,10,15,20,23,24,25,26,27,29], [217.2, 171.7, 139.7, 107, 73.8, 93, 88.9, 87.3, 96.6, 80.5])
plt.ylabel("LQI Zigbee zařízení -> koordinátor")
plt.xlabel("Vzdálenost [m]")
plt.grid(True)
plt.show()
