import os
import sys
import pexpect
import time

class Atport():
	def __init__(self, dev, log=None):
		try:
			self.__dev = dev
			self.pex = pexpect.spawn("picocom %s" % self.__dev)
			if log:
				self.pex.logfile = log
			self.pex.expect("Terminal ready")
			self.pex.send("AT\r\n")
			self.pex.expect("OK")
			self.pex.send("ATE1\r\n")
			self.pex.expect("OK")
			self.pex.send("AT+COPS?\r\n")
			self.pex.expect("OK")
		except Exception as e:
			print(str(e))

	def close(self):
		try:
			self.pex.sendcontrol("a")
			self.pex.sendcontrol("x")
			self.pex.expect("Thanks for using picocom")
		except Exception as e:
			print(str(e))

	def skip_lines(self, lines, target):
		i = 0
		for line in lines:
			if line == target:
				break
			i += 1
		for line in lines[i+1:]:
			if line:
				break;
			i += 1
		if i >= len(lines):
			return None
		return lines[i+1:]

	def get_imei(self):
		try:
			self.pex.send("AT+CGSN\r\n")
			self.pex.expect("OK")
			lines = self.pex.before.splitlines()
			lines = self.skip_lines(lines, "AT+CGSN")
			return lines[0]
		except Exception as e:
			print(str(e))
		return None

	def get_imsi(self):
		try:
			self.pex.send("AT+CIMI\r\n")
			self.pex.expect("OK")
			lines = self.pex.before.splitlines()
			lines = self.skip_lines(lines, "AT+CIMI")
			return lines[0]
		except Exception as e:
			print(str(e))
		return None


class SIM7100port(Atport):
	def get_info(self):
		info = {
			"Manufacturer": "",
			"Model": "",
			"Revision": "",
			"IMEISV": "",
			"+GCAP": "",
		}
		try:
			self.pex.send("ATI\r\n")
			self.pex.expect("OK")
			lines = self.pex.before.splitlines()
			lines = self.skip_lines(lines, "ATI")
			for line in lines:
				try:
					keyval = line.split(":")
					key = keyval[0].strip()
					val = keyval[1].strip()
					info[key] = val
				except:
					continue
		except Exception as e:
			print(str(e))
		return info

	def get_rssi(self):
		rssi = None
		try:
			self.pex.send("AT+CSQ\r\n")
			self.pex.expect("OK")
			lines = self.pex.before.splitlines()
			lines = self.skip_lines(lines, "AT+CSQ")
			for line in lines:
				line = line.strip()
				if line.startswith("+CSQ"):
					rssi = int(line.split(":")[1].split(",")[0].strip())
		except Exception as e:
			print(str(e))
		return rssi

class AK110port(Atport):
	def get_info(self):
		info = {
			"Manufacturer": "",
			"Model": "",
			"Revision": "",
			"IMEI": "",
			"+GCAP": "",
		}
		try:
			self.pex.send("ATI\r\n")
			self.pex.expect("OK")
			lines = self.pex.before.splitlines()
			lines = self.skip_lines(lines, "ATI")
			for line in lines:
				try:
					keyval = line.split(":")
					key = keyval[0].strip()
					val = keyval[1].strip()
					info[key] = val
				except:
					continue
		except Exception as e:
			print(str(e))
		return info

	def get_rssi(self):
		rssi = None
		try:
			self.pex.send("AT+CSQ\r\n")
			self.pex.expect("OK")
			lines = self.pex.before.splitlines()
			lines = self.skip_lines(lines, "AT+CSQ")
			for line in lines:
				line = line.strip()
				if line.startswith("+CSQ"):
					rssi = int(line.split(":")[1].split(",")[0].strip())
		except Exception as e:
			print(str(e))
		return rssi

class WvdialTest():
	def start(self, conf, log=None):
		ret = False
		try:
			confname = "wvdial_tmp.conf"
			f = open(confname, "w")
			f.write(conf)
			f.close()
			self.pex = pexpect.spawn("wvdial --conf=%s SIM7100" % confname)
			if log:
				self.pex.logfile = log
			self.pex.expect("secondary DNS address")
			time.sleep(1)
			self.pex.sendcontrol("c")
			self.pex.expect("Disconnecting at")
			ret = True
		except:
			pass
		try:
			os.unlink(confname)
		except:
			pass
		return ret

