#!/usr/bin/python

import serial
import os
import sys

usbport = -1
usbinfo = open("/proc/tty/driver/usbserial")
for line in usbinfo:
  if "product:683c" in line:
    if usbport == -1:
      if os.path.isfile("/tmp/roamingQueried"):
        usbport = int((line.partition(":"))[0]) + 4
      else:
        usbport = int((line.partition(":"))[0]) + 3
if usbport != -1:
  thistty = "/dev/ttyUSB" + str(usbport)
  ser = serial.Serial(thistty, 115200, timeout=2)
  ser.open ()

  #Used to return the CSQ, signal strength. Value is a positive number from 0? to 31?.
  # Method to conver csq to rssi to be determined. Possibly (-113 + (CSQ * 2))
  # Two possible ranges to use. Will determine which later.
  # Ranges   dbM              Quality       dbM
  #          -75 or greater   Excellent     -60 or greater
  #          -74 to -82       Good          -61 to -73
  #          -83 to -94       Average       -74 to -85
  #          -95 to -105      Poor          -86 to -98
  #          -106 to -110     Very Poor     -99 to -110
  #          -111 or less     No service    -111 or less

  at_command = 'AT+csq\r\n'
  ser.write(at_command)
  ser.sendBreak()
  ser.sendBreak()

  line = ser.read(ser.inWaiting())
  if "CSQ" in line:
    rssi = int(line.partition("CSQ:")[2].partition(",")[0].strip())*2-113

  if os.path.isfile("/tmp/roamingQueried"):
    roamingfile = open("/tmp/roamingQueried", "r")
    metricsfile = open("/tmp/attmetrics", "w")
    metricsfile.write(str(rssi)+'\n')
    metricsfile.write(roamingfile.readline())
    metricsfile.close
    roamingfile.close
  else:
    #Used to gather service status information. Status' are
    # Service availability: 0 No service, 1 Limited Service, 2 Service, 3 Limited regional service, 4 power save mode
    # Service domain: 0 No service, 1 Circuit-switched service only, 2 Packet-switched service only, 3 Circuit and packet-switched service
    # Roaming status indicator: 0 Not roaming, 1 Roaming
    # System mode: 0: No service, 3 GSM/GPRS mode, 5 WCDMA mode
    # SIM status: 0 SIM is not available, 1 SIM is available, 255 No SIM, or the SIM has been PIN-locked.
    at_command = 'AT^sysinfo\r\n'
    ser.write(at_command)
    ser.sendBreak()
    ser.sendBreak()
    line = ser.read(ser.inWaiting())
    print line
    metricsfile = open("/tmp/attmetrics", "w")
    metricsfile.write(str(rssi)+'\n')
    metricsfile.write(line.split(",")[2]+'\n')
    roamingfile = open("/tmp/roamingQueried", "w")
    roamingfile.write(line.split(",")[2]+'\n')
    metricsfile.close
    roamingfile.close

  ser.close
  sys.exit(rssi)
else:
  metricsfile = open("/tmp/attmetrics", "w")
  metricsfile.write("0\n2\n")
  metricsfile.close
  sys.exit(1)
