__init__.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import logging
  2. import serial
  3. import time
  4. logging.basicConfig(level=logging.DEBUG)
  5. class Gsm:
  6. def __init__(self, port, msisdn, imei=None, pin=None):
  7. self.port = port
  8. logging.info('Initializing Gsm class for port ' + port)
  9. try:
  10. self.console = serial.Serial(self.port, 115200, timeout=3)
  11. if not self.console.isOpen():
  12. self.console.open()
  13. except:
  14. logging.error('Error connecting to ' + self.port)
  15. self.msisdn = msisdn
  16. #self.cmd("AT+CMGF=1")
  17. logging.info('Connection established')
  18. self.status = self.check_status()
  19. self.unlock_sim(pin)
  20. logging.info("Current status: " + str(self.status))
  21. if imei is not None:
  22. r = self.set_imei(imei)
  23. if r:
  24. self.imei = imei
  25. logging.info("IMEI Changed")
  26. def cmd(self, cmd):
  27. cmd += "\r\n"
  28. self.console.write(cmd.encode("ascii"))
  29. time.sleep(1)
  30. output = self.console.readlines()
  31. return ''.join(l.decode('ascii') for l in output)
  32. def check_status(self):
  33. r = self.cmd("ATI")
  34. if "OK" in r:
  35. return True
  36. else:
  37. return False
  38. def unlock_sim(self, pin):
  39. status = self.cmd("AT+CPIN?")
  40. logging.info(status)
  41. if "+CPIN:READY" in status:
  42. return True
  43. elif "+CME ERROR:10" in status:
  44. logging.error("Sim not inserted")
  45. return False
  46. elif "+CPIN:SIM PIN" in status:
  47. auth = self.cmd('AT+CPIN="' + pin + '"')
  48. if "OK" in auth:
  49. logging.info("Pin correct")
  50. return True
  51. else:
  52. logging.error("Wrong PIN")
  53. return False
  54. else:
  55. logging.error("Unknown PIN error")
  56. return False
  57. def set_imei(self, imei):
  58. r = self.cmd('AT+EMGR=1,7,"' + imei + '"')
  59. if "OK" in r:
  60. return True
  61. else:
  62. return False
  63. def fetch_messages(self):
  64. r = self.cmd("AT+CMGL=REC UNREAD")
  65. print(r)
  66. def delete_messages(self):
  67. r = self.cmd("")
  68. def parse_message(self, message):
  69. return True