def main(): print("Iniciando modem...") logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE) modem.smsTextMode = False modem.connect(PIN) sms=text() modem.sendSms('649886178',sms )
class Modem(threading.Thread): def __init__(self, smsq, device, *a,**kw): self.modem = GsmModem(device,9600,dsrdtr=True,rtscts=True) self.smsq = smsq return super(Modem,self).__init__(*a,**kw) def run(self): while True: try: self.modem.connect() except (TimeoutException,IOError) as e: self.modem.close() exc_type, exc_value, exc_traceback = sys.exc_info() logging.debug(traceback.format_tb(exc_traceback)) time.sleep(10) continue try: while True: phone,text = self.smsq.get() logging.debug(u'modem to {} text: {}'.format(phone,text)) sms = self.modem.sendSms(phone,text) self.smsq.task_done() time.sleep(10) except Exception as e: self.modem.close() exc_type, exc_value, exc_traceback = sys.exc_info() logging.error(type(e)) logging.error(e.message) logging.debug(traceback.format_tb(exc_traceback))
class SMSHandler: def __init__(self): print('Initializing modem...') fHelper = FileHandler() contents = fHelper.readSmsSettings() arr = contents.split(",") PORT = arr[0] BAUDRATE = int(arr[1]) PIN = None print(PORT, BAUDRATE) # Uncomment the following line to see what the modem is doing: logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) self.modem = GsmModem(PORT, BAUDRATE) self.modem.smsTextMode = False self.modem.connect(PIN) def sendSms(self, destination, body): try: self.modem.sendSms(destination, body, True, 15, False) print("Sms sent to: " + destination) return True except Exception as e: print("An error occurred while sending the message: " + str(e)) raise e
def send_sms(phone_num, context): modem = GsmModem(port=PORT) modem.connect(PIN) for i in range(len(phone_num)): modem.sendSms(phone_num[i], context) # modem.smsTextMode = False modem.close()
def main(): # sendsms("+972549766158", "Hello") print('Initializing modem...') # Uncomment the following line to see what the modem is doing: # logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) # modem = GsmModem(PORT) # modem.connect() # modem.smsc = "+972586279099" # modem.sendSms("+972549766158", "before") # modem.close() numOfSeats = 4 message = "זוהי הודעה מגבאי בית הכנסת : נשמח אם תוכל להחזיר הודעה עם מספר המושבים הפנויים שמוקצים לך ולמשפחתך בשבת הקרובה." + "\nמקסימום: " + str( numOfSeats) modem = GsmModem(PORT, BAUDRATE, smsReceivedCallbackFunc=handleSms) modem.smsTextMode = False modem.connect(PIN) # modem.smsc = "+972586279099" #golan telecom modem.smsc = "+972521100059" #cellcom # modem.sendSms("+972549766158", "שלום מדבר אמיתי מלכה תוכל להגיב לי בבקשה?") modem.sendSms("+972587766185", message) # modem.smsc = "+972586279099" print('Waiting for SMS message...') try: modem.rxThread.join( 2**31 ) # Specify a (huge) timeout so that it essentially blocks indefinitely, but still receives CTRL+C interrupt signal finally: modem.close()
def main(): print("Iniciando modem...") logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE) modem.smsTextMode = True modem.connect(PIN) modem.sendSms('638070483', text())
def main(): print("Iniciando modem...") logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE) modem.smsTextMode = False modem.connect(PIN) sms = text() modem.sendSms('649886178', sms)
def main(): print('Initializing modem...') modem = GsmModem(PORT, SPEED) modem.smsTextMode = False modem.connect(PIN) try: number_request = '+79372219943' #number_request = '+79179812832' #number_request = '+79272294597' message = "/00000 INS OUTS" modem.sendSms(number_request, message) #modem.status() finally: modem.close()
class Modem(threading.Thread): def __init__(self, smsq, device, *a, **kw): self.modem = GsmModem(device, 9600, dsrdtr=True, rtscts=True) self.smsq = smsq return super(Modem, self).__init__(*a, **kw) def run(self): while True: try: self.modem.connect() except (TimeoutException, IOError) as e: self.modem.close() exc_type, exc_value, exc_traceback = sys.exc_info() logging.debug(traceback.format_tb(exc_traceback)) time.sleep(10) continue try: while True: phone, text = self.smsq.get() logging.debug(u'modem to {} text: {}'.format(phone, text)) sms = self.modem.sendSms(phone, text) self.smsq.task_done() time.sleep(10) except Exception as e: self.modem.close() exc_type, exc_value, exc_traceback = sys.exc_info() logging.error(type(e)) logging.error(e.message) logging.debug(traceback.format_tb(exc_traceback))
def text(number, message, key): if key.strip() == '9703BB8D5A': print "Creating modem instance" modem = GsmModem('/dev/ttyUSB0', 9600) try: print "Connecting modem" modem.connect() except PinRequiredError: print "Pin required" try: print "Waiting for Network coverage info" modem.waitForNetworkCoverage(5) except TimeoutException: print "Signal strength not strong enough" return "No signal" else: try: print "Sending %s to %s" % (message, number) sms = modem.sendSms(number, message) except TimeoutException: print "Failed to send message" return 'Error encountered' print "Closing modem" modem.close() return True else: return 'Key is not correct'
def send_sms(args): modem = GsmModem(args.port, args.baud, AT_CNMI=args.CNMI) if args.debug: # enable dump on serial port logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.DEBUG) print("Connecting to GSM modem on {0}...".format(args.port)) try: modem.connect(args.pin, waitingForModemToStartInSeconds=args.wait) except PinRequiredError: sys.stderr.write( "Error: SIM card PIN required. Please specify a PIN with the -p argument.\n" ) sys.exit(1) except IncorrectPinError: sys.stderr.write("Error: Incorrect SIM card PIN entered.\n") sys.exit(1) print("Checking for network coverage...") try: modem.waitForNetworkCoverage(5) except TimeoutException: print( "Network signal strength is not sufficient, please adjust modem position/antenna and try again." ) modem.close() sys.exit(1) else: if args.message is None: print("\nPlease type your message and press enter to send it:") text = raw_input("> ") else: text = args.message if args.deliver: print("\nSending SMS and waiting for delivery report...") else: print("\nSending SMS message...") try: sms = modem.sendSms( args.destination, text, waitForDeliveryReport=args.deliver ) except TimeoutException: print("Failed to send message: the send operation timed out") modem.close() sys.exit(1) else: modem.close() if sms.report: print( "Message sent{0}".format( " and delivered OK." if sms.status == SentSms.DELIVERED else ", but delivery failed." ) ) else: print("Message sent.")
def main(): args = parseArgsPy26( ) if sys.version_info[0] == 2 and sys.version_info[1] < 7 else parseArgs() if args.port == None: sys.stderr.write( 'Error: No port specified. Please specify the port to which the GSM modem is connected using the -i argument.\n' ) sys.exit(1) modem = GsmModem(args.port, args.baud, AT_CNMI=args.CNMI) # Uncomment the following line to see what the modem is doing: #logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) print('Connecting to GSM modem on {0}...'.format(args.port)) try: modem.connect(args.pin, waitingForModemToStartInSeconds=args.wait) except PinRequiredError: sys.stderr.write( 'Error: SIM card PIN required. Please specify a PIN with the -p argument.\n' ) sys.exit(1) except IncorrectPinError: sys.stderr.write('Error: Incorrect SIM card PIN entered.\n') sys.exit(1) print('Checking for network coverage...') try: modem.waitForNetworkCoverage(5) except TimeoutException: print( 'Network signal strength is not sufficient, please adjust modem position/antenna and try again.' ) modem.close() sys.exit(1) else: print('\nPlease type your message and press enter to send it:') text = raw_input('> ') if args.deliver: print('\nSending SMS and waiting for delivery report...') else: print('\nSending SMS message...') try: sms = modem.sendSms(args.destination, text, waitForDeliveryReport=args.deliver) except TimeoutException: print('Failed to send message: the send operation timed out') modem.close() sys.exit(1) else: modem.close() if sms.report: print('Message sent{0}'.format( ' and delivered OK.' if sms.status == SentSms.DELIVERED else ', but delivery failed.')) else: print('Message sent.')
def send_sms_alert(): if SMS_ALERTS_ENABLED: # Configuring the Modem Connection modem_port = '/dev/ttyUSB0' modem_baudrate = 115200 modem_sim_pin = None # SIM card PIN (if any) # Establishing a Connection to the SMS Modem logger.debug("Initializing connection to modem...") modem = GsmModem(modem_port, modem_baudrate) modem.smsTextMode = False if modem_sim_pin: modem.connect(modem_sim_pin) else: modem.connect() # Continuously dispatches SMS alerts to a list of designated recipients while True: sms_alert_status = sms_alert_queue.get() sms_alert_timestamp = sms_alert_queue.get() if sms_alert_status == "Gunshot Detected": try: # At this point in execution, an attempt to send an SMS alert to local authorities will be made modem.waitForNetworkCoverage(timeout = NETWORK_COVERAGE_TIMEOUT) for number in DESIGNATED_ALERT_RECIPIENTS: modem.sendSms(number, ALERT_MESSAGE + sms_alert_timestamp) logger.debug(" *** Sent out an SMS alert to all designated recipients *** ") except: logger.debug("ERROR: Unable to successfully send an SMS alert to the designated recipients.") pass finally: logger.debug(" ** Finished evaluating an audio sample with the model ** ") else: while True: sms_alert_status = sms_alert_queue.get() sms_alert_timestamp = sms_alert_queue.get() if sms_alert_status == "Gunshot Detected": logger.debug(ALERT_MESSAGE + sms_alert_timestamp)
def main(): print('[%s] Initializing modem...' % datetime.datetime.now()) # Uncomment the following line to see what the modem is doing: logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE, smsReceivedCallbackFunc=handleSms) modem.smsTextMode = False modem.connect(PIN) print('[%s] Initialized modem!' % datetime.datetime.now()) print('[%s] Sending Message...' % datetime.datetime.now()) cellnum = raw_input("Please Enter your phone number:") text = raw_input("Please Enter your text message:") print('Type:', type(text)) modem.sendSms(cellnum, unicode(text, 'gbk')) print('[%s] Waiting for SMS message...' % datetime.datetime.now()) try: modem.rxThread.join(2 ** 31) # Specify a (huge) timeout so that it essentially blocks indefinitely, # but still receives CTRL+C interrupt signal finally: modem.close()
def main(): print('Initializing modem...') modem = GsmModem(PORT, BAUDRATE) modem.connect(PIN) modem.waitForNetworkCoverage(10) print('Sending SMS to: {0}'.format(SMS_DESTINATION)) response = modem.sendSms(SMS_DESTINATION, SMS_TEXT, True) if type(response) == SentSms: print('SMS Delivered.') else: print('SMS Could not be sent') modem.close()
def main(): args = parseArgsPy26() if sys.version_info[0] == 2 and sys.version_info[1] < 7 else parseArgs() if args.port == None: sys.stderr.write('Error: No port specified. Please specify the port to which the GSM modem is connected using the -i argument.\n') sys.exit(1) modem = GsmModem(args.port, args.baud, AT_CNMI=args.CNMI) if args.debug: # enable dump on serial port logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) print('Connecting to GSM modem on {0}...'.format(args.port)) try: modem.connect(args.pin, waitingForModemToStartInSeconds=args.wait) except PinRequiredError: sys.stderr.write('Error: SIM card PIN required. Please specify a PIN with the -p argument.\n') sys.exit(1) except IncorrectPinError: sys.stderr.write('Error: Incorrect SIM card PIN entered.\n') sys.exit(1) print('Checking for network coverage...') try: modem.waitForNetworkCoverage(5) except TimeoutException: print('Network signal strength is not sufficient, please adjust modem position/antenna and try again.') modem.close() sys.exit(1) else: if args.message is None: print('\nPlease type your message and press enter to send it:') text = raw_input('> ') else: text = args.message if args.deliver: print ('\nSending SMS and waiting for delivery report...') else: print('\nSending SMS message...') try: sms = modem.sendSms(args.destination, text, waitForDeliveryReport=args.deliver) except TimeoutException: print('Failed to send message: the send operation timed out') modem.close() sys.exit(1) else: modem.close() if sms.report: print('Message sent{0}'.format(' and delivered OK.' if sms.status == SentSms.DELIVERED else ', but delivery failed.')) else: print('Message sent.')
def main(): port = '/dev/ttyUSB0' baud = 460800 deliver = False destination = "0711661919" message = "Testing_message \n new line \t tab \n n \n e \n l" modem = GsmModem(port, baud) # Uncomment the following line to see what the modem is doing: # logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) print('Connecting to GSM modem on {0}...'.format(port)) try: modem.connect() except PinRequiredError: sys.stderr.write('Error: SIM card PIN required. Please specify a PIN. \n') sys.exit(1) except IncorrectPinError: sys.stderr.write('Error: Incorrect SIM card PIN entered.\n') sys.exit(1) print('Checking for network coverage...') try: modem.waitForNetworkCoverage(5) except TimeoutException: print('Network signal strength is not sufficient, please adjust modem position/antenna and try again.') modem.close() sys.exit(1) else: print('\nPlease type your message and press enter to send it:') text = message if deliver: print ('\nSending SMS and waiting for delivery report...') else: print('\nSending SMS message...') try: sms = modem.sendSms(destination, text, waitForDeliveryReport=deliver) except TimeoutException: print('Failed to send message: the send operation timed out') modem.close() sys.exit(1) else: modem.close() if sms.report: print('Message sent{0}'.format( ' and delivered OK.' if sms.status == SentSms.DELIVERED else ', but delivery failed.')) else: print('Message sent.')
def listen_for_sms(): global modem global correct_format # print('Initializing modem...') # Uncomment the following line to see what the modem is doing: # logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE, smsReceivedCallbackFunc=handleSms) modem.smsTextMode = False modem.connect() first_text = BOX + ' Restart: Waiting for credentials | cmcibm,<BROKER>,<PORT>,<USERNAME>,<PASSWORD>' #load_dest() sentmsg = modem.sendSms(DESTINATION, first_text) print('Waiting for SMS message') try: modem.rxThread.join(TIMEOUT) finally: print('Closing modem') to_print = load_mqtt() if correct_format == 1: #print("the format is correct and equal to") # to_print = load_mqtt() print(change_required) print(correct_format) print(to_print[0]) print(to_print[1]) print(to_print[2]) print(to_print[3]) else: #print("the format is NOT correct and equal to") print(change_required) print(correct_format) print('') print('') print('') print('') modem.close()
# logging.info("Use dev %s", device) logging.info("Initializing modem...") modem = GsmModem(device, BAUDRATE, smsReceivedCallbackFunc=handleSms) modem.smsTextMode = True modem.connect() logging.info("Waiting for network coverage...") modem.waitForNetworkCoverage(30) with open( 'data/' + unit + '.csv', 'rU' ) as csvfile: thisList = csv.reader(csvfile, delimiter=',', quotechar='"') head = next(thisList) totalrows = 0 for row in thisList: totalrows += 1 phone = '0' + str(row[0]) logging.info("%s Send to %s", totalrows, phone) try: modem.sendSms(phone,message, deliveryTimeout=30) except CommandError as e: logging.info('SMS send failed: {0}'.format(e)) except TimeoutException as e: logging.info('SMS timeout failed: {0}'.format(e)) time.sleep(10.0) logging.info("Blasting done") modem.close()
# file = sys.argv[1] # device = sys.argv[2] # unit = sys.argv[1] device = sys.argv[2] BAUDRATE = 115200 UNLICODE = "SUPER10" UNLIDIAL = "9999" logging.basicConfig(filename="logs/" + unit + ".log", level = logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s'); # logging.info("Use file %s", file) # logging.info("Use dev %s", device) logging.info("Initializing modem...") modem = GsmModem(device, BAUDRATE) modem.smsTextMode = True modem.connect() logging.info("Waiting for network coverage...") modem.waitForNetworkCoverage(30) logging.info("Register Unlitext %s", unit) modem.sendSms(UNLIDIAL, UNLICODE) logging.info("Unlitext registration done") modem.close()
class GSM(object): RETRY_GAP = 5 def __init__(self): self._logger = logging.getLogger(LOG_ADGSM) self._modem = None self._options = None def setup(self): db_session = Session() section = db_session.query(Option).filter_by(name="notifications", section="gsm").first() db_session.close() self._options = json.loads(section.value) if section else { "pin_code": "" } self._options["port"] = os.environ["GSM_PORT"] self._options["baud"] = os.environ["GSM_PORT_BAUD"] if not self._options["pin_code"]: self._logger.info( "Pin code not defined, skip connecting to GSM modem") return False self._modem = GsmModem(self._options["port"], int(self._options["baud"])) self._modem.smsTextMode = True connected = False while not connected: try: self._logger.info( "Connecting to GSM modem on %s with %s baud (PIN: %s)...", self._options["port"], self._options["baud"], self._options["pin_code"], ) self._modem.connect(self._options["pin_code"]) self._logger.info("GSM modem connected") connected = True except PinRequiredError: self._logger.error("SIM card PIN required!") self._modem = None return False except IncorrectPinError: self._logger.error("Incorrect SIM card PIN entered!") self._modem = None return False except TimeoutException as error: self._logger.error( "No answer from GSM module: %s! Request timeout, retry in %s seconds...", str(error), GSM.RETRY_GAP) except CmeError as error: self._logger.error( "CME error from GSM module: %s! Unexpected error, retry in %s seconds...", str(error), GSM.RETRY_GAP) except CmsError as error: if str(error) == "CMS 302": self._logger.debug( "GSM modem not ready, retry in %s seconds...", GSM.RETRY_GAP) else: self._logger.error( "CMS error from GSM module: %s. Unexpected error, retry in %s seconds...", str(error), GSM.RETRY_GAP, ) except Exception: self._logger.exception("Failed to access GSM module!") return False sleep(GSM.RETRY_GAP) return True def destroy(self): if self._modem is not None: self._modem.close() def sendSMS(self, phone_number, message): if not self._modem: self.setup() if not self._modem: return False if message is None: return False self._logger.debug("Checking for network coverage...") try: self._modem.waitForNetworkCoverage(5) except CommandError as error: self._logger.error("Command error: %s", error) return False except TimeoutException: self._logger.error( ("Network signal strength is not sufficient," " please adjust modem position/antenna and try again.")) return False else: try: self._modem.sendSms(phone_number, message) except TimeoutException: self._logger.error( "Failed to send message: the send operation timed out") return False except CmsError as error: self._logger.error("Failed to send message: %s", error) return False else: self._logger.debug("Message sent.") return True return False
# logging.info("Use dev %s", device) logging.info("Initializing modem...") modem = GsmModem(device, BAUDRATE, smsReceivedCallbackFunc=handleSms) modem.smsTextMode = True modem.connect() logging.info("Waiting for network coverage...") modem.waitForNetworkCoverage(30) with open('data/' + unit + '.csv', 'rU') as csvfile: thisList = csv.reader(csvfile, delimiter=',', quotechar='"') head = next(thisList) totalrows = 0 for row in thisList: totalrows += 1 phone = '0' + str(row[0]) logging.info("%s Send to %s", totalrows, phone) try: modem.sendSms(phone, message, deliveryTimeout=30) except CommandError as e: logging.info('SMS send failed: {0}'.format(e)) except TimeoutException as e: logging.info('SMS timeout failed: {0}'.format(e)) time.sleep(10.0) logging.info("Blasting done") modem.close()
# file = sys.argv[1] # device = sys.argv[2] # unit = sys.argv[1] device = sys.argv[2] BAUDRATE = 115200 BALCODE = "BAL" BALDIAL = "222" logging.basicConfig(filename="logs/" + unit + ".log", level = logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s'); # logging.info("Use file %s", file) # logging.info("Use dev %s", device) logging.info("Initializing modem...") modem = GsmModem(device, BAUDRATE) modem.smsTextMode = True modem.connect() logging.info("Waiting for network coverage...") modem.waitForNetworkCoverage(30) logging.info("Check balance %s", unit) modem.sendSms(BALDIAL, BALCODE) logging.info("Balance request done") modem.close()
class dispgsm: _user=None metrics={} def __init__(self, user): dispgsm._user=user self.logger = logging.getLogger(user.user_code+'.dispgsm') self.logger.info('Initializing GSM device %s',user.user_code) self._config = ConfigParser.ConfigParser() self._config.read('./config.cfg') self._msisdn = ast.literal_eval(self._config.get('GSM_CREDENTIALS',user.user_code))['msisdn'] self._pin = ast.literal_eval(self._config.get('GSM_CREDENTIALS',user.user_code))['pin'] self._port = ast.literal_eval(self._config.get('GSM_CREDENTIALS',user.user_code))['port'] self._baudrate = ast.literal_eval(self._config.get('GSM_CREDENTIALS',user.user_code))['baudrate'] self._modem = GsmModem(self._port, int(self._baudrate), incomingCallCallbackFunc=dispgsm.handleIncomingCall, smsReceivedCallbackFunc=dispgsm.handleSms, smsStatusReportCallback=dispgsm.handleSmsDeliveryReport) #self._modem.smsTextMode = False def connect(self): self.logger.info('Connecting GSM modem...') #self._modem.connect() self._modem.connect(self._pin) self.logger.info('Waiting for network coverage...') try: self._modem.waitForNetworkCoverage(30) except TimeoutException: self.logger.error('Network signal strength is not sufficient, please adjust modem position/antenna and try again.') self.disconnect() self.metrics['handled_sms']=[] self.metrics['handled_call']=[] self.metrics['send_sms']=[] self.metrics['dial_call']=[] self.logger.info('GSM Device ready to use.') def disconnect(self): self.logger.info('Disconnecting modem...') self._modem.close() self.logger.info('Disconnected') def send_sms(self, destination, text, waitForDeliveryReport=True, deliveryTimeout=15): if text==None: text = str(random.randint(1000000000, 9999999999)) self.logger.info('Sending SMS with text:%s',text) m ={} m['sms_text'] = text m['sms_delivery_timeout'] = deliveryTimeout m['sms_sent_time'] = str(datetime.datetime.now()) try: sms = self._modem.sendSms(destination, text, waitForDeliveryReport, deliveryTimeout) self.logger.info('Message sent with delivery report status:%s reference:%s',sms.status,sms.reference) if sms.status==0: m['sms_status'] = 'ENROUTE' elif sms.status==1: m['sms_status'] = 'DELIVERED' elif sms.status==2: m['sms_status'] = 'FAILED' else: m['sms_status'] = 'ERROR' except TimeoutException: self.logger.warning('Fail to deliver message: the send operation timed out') m['sms_end'] = str(datetime.datetime.now()) self.metrics['send_sms'].append(m) def dial(self, destination, dtmf): if dtmf==None: dtmf = str(random.randint(1000000000, 9999999999)) self.logger.info('Calling number %s and sending DTMF:%s',destination,dtmf) m = {} m['dial_dtmf'] = dtmf m['dial_start'] = str(datetime.datetime.now()) call = self._modem.dial(destination) wasAnswered = False while call.active: if call.answered: wasAnswered = True self.logger.info('Call has been answered; waiting a while...') m['dial_answered'] = str(datetime.datetime.now()) # Wait for a bit - some older modems struggle to send DTMF tone immediately after answering a call time.sleep(3.0) self.logger.info('Playing DTMF tones: %s',dtmf) try: if call.active: # Call could have been ended by remote party while we waited in the time.sleep() call call.sendDtmfTone(dtmf) self.logger.info('DTMF tones sent') time.sleep(10) except InterruptedException as e: # Call was ended during playback self.logger.info('DTMF playback interrupted: {0} ({1} Error {2})'.format(e, e.cause.type, e.cause.code)) except CommandError as e: self.logger.error('DTMF playback failed: {0}'.format(e)) finally: if call.active: # Call is still active self.logger.info('Hanging up call...') m['dial_hangup'] = str(datetime.datetime.now()) call.hangup() else: # Call is no longer active (remote party ended it) self.logger.info('Call has been ended by remote party') else: # Wait a bit and check again time.sleep(0.5) if not wasAnswered: self.logger.info('Call was not answered by remote party') self.logger.info('Call finished') m['dial_end'] = str(datetime.datetime.now()) self.metrics['dial_call'].append(m) def handleIncomingCall(call): logger = logging.getLogger('device.'+dispsip._user.user_code+'.dispgsm') if call.ringCount == 1: logger.info('Incoming call from:', call.number) elif call.ringCount >= 2: logger.info('Answering call and playing some DTMF tones...') call.answer() # Wait for a bit - some older modems struggle to send DTMF tone immediately after answering a call time.sleep(20.0) try: call.sendDtmfTone('9515999955951') except InterruptedException as e: # Call was ended during playback logger.info('DTMF playback interrupted: {0} ({1} Error {2})'.format(e, e.cause.type, e.cause.code)) finally: if call.answered: logger.info('Hanging up call.') call.hangup() else: logger.info(' Call from {0} is still ringing...'.format(call.number)) def handleSms(sms): logger = logging.getLogger('device.'+dispsip._user.user_code+'.dispgsm') logger.info(u'== SMS message received ==\nFrom: {0}\nTime: {1}\nMessage:\n{2}\n'.format(sms.number, sms.time, sms.text)) #sms.reply(u'SMS received: "{0}{1}"'.format(sms.text[:20], '...' if len(sms.text) > 20 else '')) def handleSmsDeliveryReport(sms): logger = logging.getLogger('device.'+dispsip._user.user_code+'.dispgsm') logger.info('Delivery report received status:%s reference:%s timeSent:%s timefinalized:%s deliveryStatus:%s',sms.status,sms.reference,sms.timeSent,sms.timeFinalized,sms.deliveryStatus)
def run(self): # Initialize the GPIO interface #exportpins() #writepins('1') logging.info("Modem thread running.") global modem global ppp_requested global sms_queue global beat global modem_failure rxListenLength = 5 init_count = 0 while self.running: beat += 1 while self.running and not ppp_requested and init_count > -1: if (init_count > 10): # Let's exit after 10 fails self.running = False modem_failure = True return(1) try: init_count = init_count + 1 modem = GsmModem(PORT, BAUDRATE, incomingCallCallbackFunc=handleIncomingCall, smsReceivedCallbackFunc=handleSms) logging.info("Initializing modem, try {0}.".format(init_count)) modem.connect(PIN) modem.write('AT+CFUN=1') init_count = -1 except (OSError, TimeoutException,CommandError): # OSError means pppd is likely running logging.error("Failed to initialize the GSM module.") try: modem.close() except AttributeError: True time.sleep(5) #self.modemPowerCycle() logging.info('Waiting for incoming calls...') while self.running and not ppp_requested and init_count < 0: try: #waitForNetworkCoverage() self.signalStrength = modem.signalStrength self.networkName = modem.networkName data['signalStrength'] = self.signalStrength data['networkName'] = self.networkName #modem.write("AT+CFUN=1") serving_cell=self.CGED_REGEX.match(modem.write("AT+CGED=3")[0]) if serving_cell: mcc=serving_cell.group(1) mnc=serving_cell.group(2) lac=serving_cell.group(3) ci=serving_cell.group(4) self.cellInfo="{0}/{1}/{2}/{3}".format(mcc, mnc, lac, ci) data['cellInfo'] = self.cellInfo # Comms are handled elsewhere so we could eventually just sleep, waiting #time.sleep(rxListenLength) if (self.signalStrength > 5): sent_position = 0 if sms_enabled: while (len(sms_queue) > 0): text=sms_queue.pop() if (text == 'position') and sent_position: logging.info('Not resending position in the same interval') elif (text == 'position'): send_position_via_sms(default_destination) sent_position = 1 else: try: modem.sendSms(default_destination, text, waitForDeliveryReport=False) except (CommandError, TimeoutException): sms_queue.append(text) else: logging.info('Waiting for better network coverage') modem.rxThread.join(rxListenLength) if self.do_shutdown: logging.warn('Disabling radio RX/TX.') modem.write('AT+CFUN=0') self.running = False modem.close() except (CommandError, InterruptedException, PinRequiredError, IncorrectPinError, TimeoutException): logging.error("rxThread died: {0}".format(sys.exc_info()[0])) modem.close() time.sleep(5) init_count = 0 # If PPP was requested, now it's the time if self.running and ppp_requested and self.signalStrength > 5 and init_count < 0: try: self.signalStrength = 101 logging.info('Launching PPP session.') if sms_enabled: while (len(sms_queue) > 0): logging.info('==== Sending PPP activation SMS =====') text=sms_queue.pop() try: modem.sendSms(default_destination, text, waitForDeliveryReport=False) time.sleep(1) except (CommandError, TimeoutException): sms_queue.append(text) #waitForNetworkCoverage() modem.close() logging.info("Modem interface closed.") rc = subprocess.check_output(['/usr/bin/timeout','250','/usr/bin/pon'], stderr=subprocess.STDOUT) logging.info('PPP ended: %s' % s) except subprocess.CalledProcessError as e: logging.info('PPP ended: %s' % e) sms_queue.append('PPP connection terminated') ppp_requested = False init_count = 0
from gsmmodem.modem import GsmModem def print_sms(sms): print dir(sms) def handleSms(sms): print dir(sms) PORT = '/dev/ttyUSB2' modem = GsmModem(PORT, 9600, smsReceivedCallbackFunc=handleSms) # modem = GsmModem(PORT, 9600) modem.smsTextMode = True modem.connect(5910) modem.sendSms('+59172038768', 'sadfadfsfd') print modem.imei print modem.networkName # def lineStartingWith(string, lines): # """ Searches through the specified list of strings and returns the # first line starting with the specified search string, or None if not found # """ # for line in lines: # if line.startswith(string): # return line # else: # return None # modem.write('AT+CMGS="{0}"'.format('+59172038768'), timeout=3, expectedResponseTermSeq='> ')
# unit = sys.argv[1] device = sys.argv[2] BAUDRATE = 115200 BALCODE = "BAL" BALDIAL = "222" logging.basicConfig(filename="logs/" + unit + ".log", level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s') # logging.info("Use file %s", file) # logging.info("Use dev %s", device) logging.info("Initializing modem...") modem = GsmModem(device, BAUDRATE) modem.smsTextMode = True modem.connect() logging.info("Waiting for network coverage...") modem.waitForNetworkCoverage(30) logging.info("Check balance %s", unit) modem.sendSms(BALDIAL, BALCODE) logging.info("Balance request done") modem.close()
# unit = sys.argv[1] device = sys.argv[2] BAUDRATE = 115200 UNLICODE = "UNLITXT20" UNLIDIAL = "8888" logging.basicConfig(filename="logs/" + unit + ".log", level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s') # logging.info("Use file %s", file) # logging.info("Use dev %s", device) logging.info("Initializing modem...") modem = GsmModem(device, BAUDRATE) modem.smsTextMode = True modem.connect() logging.info("Waiting for network coverage...") modem.waitForNetworkCoverage(30) logging.info("Register Unlitext %s", unit) modem.sendSms(UNLIDIAL, UNLICODE) logging.info("Unlitext registration done") modem.close()
def send_sms_at(data, action_config): """Send SMS via local modem with AT commands Meact configuration: action_config = { "recipient": ["your-number", "your-number2'], "port": "/dev/ttyUSB1", "speed": 19200, "enabled": 1 } """ if not action_config.get('enabled'): sys.exit(1) LOG.info('Sending SMS via AT') modem = GsmModem(action_config['port'], action_config['speed']) while True: try: modem.connect() modem.waitForNetworkCoverage() except TimeoutException: pass else: break for rcpt in action_config['recipient']: try: sms = modem.sendSms(rcpt, data['message']) except TimeoutException: LOG.warning('Got exception in send_sms_at') sys.exit(2) modem.close() sys.exit(0)