# Copyright Trimble Inc. 2021
#
# Script to compare BM loading between receivers - update
# rxList[] to add more/different devices

import matplotlib
# Allow running headless from the command line
matplotlib.use("agg")

from pylab import *

import RXTools as rx
import mutils as m
import xmltodict
import os

fig = []
ax  = []
fig.append(figure())
ax.append(fig[0].add_subplot(111))
fig.append(figure())
ax.append(fig[1].add_subplot(111))

user = 'admin' # Use a common username
rxList = [ {'rxType':'Feni - Alloy','ipaddr':'10.1.150.48','password':'password'},
           {'rxType':'eCos - Alloy','ipaddr':'10.1.151.24','password':'tr.imble'} ]

# Loop for each receiver
for thisRX in rxList:
  print(thisRX['ipaddr'],user,thisRX['password'])
  resp = rx.SendHttpGet( thisRX['ipaddr'], '/xml/dynamic/bm_hist.xml', user, thisRX['password'], verbose=False)
  data = xmltodict.parse(resp)

  # Get the percent of total load for BM - do this by 
  # finding the bm_proc() mean load. This is called 2,000
  # times per second, so we can refer to percent.
  BM = data['stinger']['BM']
  for thisElem in BM:
    if(thisElem['name'] == 'bm_proc()'):
      Load = float(thisElem['Mean']) # Microseconds
      Load *= (2000 / 1000000)  # 2000 per second - 1e6 num us in a second
      break

  BMFull = data['stinger']['BMHistFull']
  BMHalf = data['stinger']['BMHistHalf']

  if(len(BMFull['meas']) != len(BMHalf['meas']) ):
    print('Lengths should be the same')
    os.exit(-1)

  Full = []
  Half = []
  Time = []
  Total = []

  for i in range(len(BMFull['meas'])):
    BMFullMeas = BMFull['meas'][i]
    BMHalfMeas = BMHalf['meas'][i]

    Time.append(float(BMFullMeas['time']))
    Full.append(float(BMFullMeas['freq']))
    Half.append(float(BMHalfMeas['freq']))
    
    Total.append( float(BMHalfMeas['freq']) + float(BMFullMeas['freq']))

  # Normalize the data
  Total /= sum(Total)
  Half  /= sum(Half)
  Full  /= sum(Full)

  # The time increment is different on eCos vs Feni, as need to integrate
  # under the curve, we need to account for the x-increment
  TimeDelta = Time[2] - Time[1]
  Total /= TimeDelta
  Half /= TimeDelta
  Full /= TimeDelta
  
  # Scale by the overall BM system loading computed earlier
  Total *= Load
  Half *= Load
  Full *= Load
  
  figure(fig[0].number)
  plot(Time,Total,label=thisRX['rxType'] + '- BM Total')

  figure(fig[1].number)
  plot(Time,Half,label=thisRX['rxType'] + ' - BM Half')
  plot(Time,Full,label=thisRX['rxType'] + ' - BM Full')

for i in range(len(fig)):
  figure(fig[i].number)
  xlabel('Time [us]')
  ylabel('Normalized Load')
  title('BM Loading')
  grid(True)
  xlim([0,500])
  legend(loc='best')
  tight_layout()
  # Prevent the axis numers having an offset
  ax[i].get_xaxis().get_major_formatter().set_useOffset(False)
  # Save the data as a PNG file
  if(i == 0):
    m.save_compressed_png('BMLoad_Total_Linear.png',dpi=150)
    ax[i].set_yscale('log')
    tight_layout()
    m.save_compressed_png('BMLoad_Total_Log.png',dpi=150)
  else:
    m.save_compressed_png('BMLoad_HalfFull_Linear.png',dpi=150)
    ax[i].set_yscale('log')
    tight_layout()
    m.save_compressed_png('BMLoad_HalfFull_Log.png',dpi=150)
    


