import logging import serial import time logging.basicConfig(level=logging.DEBUG) class Gsm: def __init__(self, port, msisdn, imei=None, pin=None): self.port = port logging.info('Initializing Gsm class for port ' + port) try: self.console = serial.Serial(self.port, 115200, timeout=3) if not self.console.isOpen(): self.console.open() except: logging.error('Error connecting to ' + self.port) self.msisdn = msisdn #self.cmd("AT+CMGF=1") logging.info('Connection established') self.status = self.check_status() self.unlock_sim(pin) logging.info("Current status: " + str(self.status)) if imei is not None: r = self.set_imei(imei) if r: self.imei = imei logging.info("IMEI Changed") def cmd(self, cmd): cmd += "\r\n" self.console.write(cmd.encode("ascii")) time.sleep(1) output = self.console.readlines() return ''.join(l.decode('ascii') for l in output) def check_status(self): r = self.cmd("ATI") if "OK" in r: return True else: return False def unlock_sim(self, pin): status = self.cmd("AT+CPIN?") logging.info(status) if "+CPIN:READY" in status: return True elif "+CME ERROR:10" in status: logging.error("Sim not inserted") return False elif "+CPIN:SIM PIN" in status: auth = self.cmd('AT+CPIN="' + pin + '"') if "OK" in auth: logging.info("Pin correct") return True else: logging.error("Wrong PIN") return False else: logging.error("Unknown PIN error") return False def set_imei(self, imei): r = self.cmd('AT+EMGR=1,7,"' + imei + '"') if "OK" in r: return True else: return False def fetch_messages(self): r = self.cmd("AT+CMGL=REC UNREAD") print(r) def delete_messages(self): r = self.cmd("") def parse_message(self, message): return True