import socket
import time
import sys
import datetime
import operator
import math
import bisect
import fnmatch

#
# Copyright Trimble Inc 2018
#
# Simple script to reset the Novatel OEM7
#


if(len(sys.argv) == 3):
  server      = sys.argv[1]
  server_port = int(sys.argv[2])
else:
  print("Usage: python NovatelSetup.py Server Port")
  sys.exit(0)

# ToDo - can more than one reset type be sent at the same time?
commands = ['log versiona once\r\n',
            'freset gpsalmanac\r\n',
            'freset sbasalmanac\r\n',
            'freset gloalmanac\r\n',
            'freset galfnav_alm\r\n',
            'freset galinav_alm\r\n',
            'freset bdsalmanac\r\n']

num = len(commands)

# Loop around sending all the commands. After each command 
# close the TCP/IP connection. We don't need to do this after
# the first command as it doesn't reboot the receiver, the
# rest do. However, it avoids extra logic in the loop
for i in range(0,num):
  if(i > 1):
    # Give the unit time to reboot, the first command
    # to cause a reboot is freset gpsalmanac
    time.sleep(30)

  # Initialize a TCP client socket using SOCK_STREAM
  tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  tcp_client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  # Establish connection to TCP server and exchange data
  tcp_client.connect((server, server_port))

  print(commands[i])
  tcp_client.sendall(commands[i])
  time.sleep(0.5)
  # This is blocking read so should not return until there's data available
  received = tcp_client.recv(4096).rstrip()
  print(received)
  tcp_client.close()

print("Alms have been cleared and RX reset")

# To turn on Novatel's KF
# "pdpfilter enable"
# "saveconfig"
#

