#!/usr/bin/env python
#*******************************************
#            listen_for_events.py
# 
# To execute this script type:
# python3 listen_for_events.py
#*******************************************
import time
import serial
import io
import sys
import os
import threading
ser=serial.Serial('/dev/ttyUSB3',115200,timeout=1)
event_port=serial.Serial('/dev/ttyUSB2',115200,timeout=1)

def send(command):
   #This function sends the command to the modem
   command=command+"\r"
   ser.write(command.encode())
   time.sleep(.1)  

def listen_for_events():
   #checks for events every 2 seconds
   threading.Timer(2.0, listen_for_events).start()
   eventbuf=event_port.read(1000)
   eventbuffer=eventbuf.decode("utf-8").strip()
   #---check for an incoming voice call
   if (eventbuffer.find('+CRING: VOICE') != -1):
      #extract the number from the incoming call
      b=eventbuffer.split('"')
      print("Incoming Call")
      eventbuffer=""
   #---check to see if the remote phone hung up
   if (eventbuffer.find('NO CARRIER') != -1):
       print("NO CARRIER - Call disconnected")
   #---check to see if there was an incoming text 
   if (eventbuffer.find("+CMTI:") != -1):
      print("You received a text.")


send("ATE0") #set no echo 
send("AT+CRC=1")  #set extended call format
send("AT+CLIP=1") #enable caller ID
listen_for_events()
