class GSM(object): def __init__(self, port, baudrate, pin=None): self.sms_callbacks = [] self.port = port self.baudrate = baudrate self.pin = pin def run(self): self.modem = GsmModem(self.port, self.baudrate, smsReceivedCallbackFunc=self.sms_callback) self.modem.smsTextMode = False self.modem.connect(self.pin) def sms_callback(self, sms): logger.info(sms_receive_log_template.format(sms.number, sms.time, sms.text)) for callback in self.sms_callbacks: tornado.ioloop.IOLoop.instance().add_callback(callback, sms) def add_sms_callback(self, callback): self.sms_callbacks.append(callback) def process_stored_sms(self, delete=False): self.modem.processStoredSms()
def main(): print('Initializing modem...') #logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE) modem.connect(PIN) modem.waitForNetworkCoverage(10) print('Sending USSD string: {0}'.format(USSD_STRING)) response = modem.sendUssd(USSD_STRING) # response type: gsmmodem.modem.Ussd print('USSD reply received: {0}'.format(response.message)) if response.sessionActive: print('Closing USSD session.') # At this point, you could also reply to the USSD message by using response.reply() response.cancel() else: print('USSD session was ended by network.') modem.close()
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 __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)
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 getUnreadText(key): if key.strip() == '9703BB8D5A': modem = GsmModem('/dev/ttyUSB0', 9600) try: print "Connecting mode" modem.connect() except: return "Error connecting" try: messages = modem.listStoredSms(status=Sms.STATUS_RECEIVED_UNREAD) except Exception as e: return str(e) modem.close() retString = "" print "Got %d messages" % len(messages) for message in messages: retString = retString + "%s : %s" % (message.number, message.text) return retString else: return "Incorrect key"
def main(): args = parseArgsPy26() if sys.version_info[0] == 2 and sys.version_info[1] < 7 else parseArgs() print ('args:',args) modem = GsmModem(args.port, args.baud) 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) if args.debug: # Print debug info print('\n== MODEM DEBUG INFORMATION ==\n') print('ATI', modem.write('ATI', parseError=False)) print('AT+CGMI:', modem.write('AT+CGMI', parseError=False)) print('AT+CGMM:', modem.write('AT+CGMM', parseError=False)) print('AT+CGMR:', modem.write('AT+CGMR', parseError=False)) print('AT+CFUN=?:', modem.write('AT+CFUN=?', parseError=False)) print('AT+WIND=?:', modem.write('AT+WIND=?', parseError=False)) print('AT+WIND?:', modem.write('AT+WIND?', parseError=False)) print('AT+CPMS=?:', modem.write('AT+CPMS=?', parseError=False)) print('AT+CNMI=?:', modem.write('AT+CNMI=?', parseError=False)) print('AT+CVHU=?:', modem.write('AT+CVHU=?', parseError=False)) print('AT+CSMP?:', modem.write('AT+CSMP?', parseError=False)) print('AT+GCAP:', modem.write('AT+GCAP', parseError=False)) print('AT+CPIN?', modem.write('AT+CPIN?', parseError=False)) print('AT+CLAC:', modem.write('AT+CLAC', parseError=False)) print() else: # Print basic info print('\n== MODEM INFORMATION ==\n') print('Manufacturer:', modem.manufacturer) print('Model:', modem.model) print('Revision:', modem.revision if modem.revision != None else 'N/A') print('\nIMEI:', modem.imei if modem.imei != None else 'N/A') print('IMSI:', modem.imsi if modem.imsi != None else 'N/A') print('\nNetwork:', modem.networkName) print('Signal strength:', modem.signalStrength) print()
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
class GSM(object): def __init__(self, port, baudrate, pin=None): self.sms_callbacks = [] self.port = port self.baudrate = baudrate self.pin = pin def run(self): self.modem = GsmModem(self.port, self.baudrate, smsReceivedCallbackFunc=self.sms_callback) self.modem.smsTextMode = False self.modem.connect(self.pin) def sms_callback(self, sms): logger.info( sms_receive_log_template.format(sms.number, sms.time, sms.text)) for callback in self.sms_callbacks: tornado.ioloop.IOLoop.instance().add_callback(callback, sms) def add_sms_callback(self, callback): self.sms_callbacks.append(callback) def process_stored_sms(self, delete=False): self.modem.processStoredSms()
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('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) modem.connect(PIN) number = modem.ownNumber print("The SIM card phone number is:") print(number)
def reinitializeModem(): try: print('Reinitializing modem...') global modem modem = GsmModem(config.PORT, config.BAUDRATE, smsReceivedCallbackFunc=smsCommands.handleSms) modem.connect(config.PIN) print("Modem IMEI: ", modem.imei) except: print("Failed to reinitialize modem")
def initializeModem(): print('Initializing modem...') global modem modem = GsmModem(config.PORT, config.BAUDRATE, smsReceivedCallbackFunc=smsCommands.handleSms) # logging.basicConfig(format='%(levelname)s: %(message)s', # level=logging.DEBUG) modem.connect(config.PIN) print("Modem IMEI: ", modem.imei) testMessageRequest()
def run(self): # initialize modem modem = GsmModem(self._modem_device, self._modem_baud, smsReceivedCallbackFunc=self._handleSms) modem.connect(self._modem_pin) # try to sycn clock with GSM network time self.set_clock_from_network(modem) # handle SMS self._pon_requested = False modem.smsTextMode = False modem.processStoredSms() # wait for completion try: modem.rxThread.join(1) finally: modem.close() # handle asynchronous sms request if self._pon_requested: self._pon_requested = False self.setup_connection()
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 main(): global modem global phonebook config.read('config.ini') # Create the phonebook tmpPhonebook = config.items('phonebook') for row in tmpPhonebook: phonebook[row[0]] = row[1] # Initialize the modem print('Initializing modem...') modem = GsmModem(config.get('modem', 'port'), config.getint('modem', 'baudrate'), smsReceivedCallbackFunc=on_gsm_handleSms) modem.smsTextMode = True # Connect to the modem try: modem.connect(config.get('modem', 'pin')) except PinRequiredError: print('Pin required') sys.exit(1) except IncorrectPinError: print('Wrong pin') sys.exit(1) # Print information about modem and network print(u'Connected to modem: {0} {1}'.format(modem.manufacturer, modem.model)) print(u'Connected to network: {0}'.format(modem.networkName)) print(u'Signal strenght: {0}'.format(str(modem.signalStrength))) print('Ready!') print('===') # Make sure to empty incoming sms bucket modem.processStoredSms() # Initialize MQTT client.on_connect = on_mqtt_connect client.on_message = on_mqtt_message client.username_pw_set(config.get('mqtt', 'user'), config.get('mqtt', 'pass')) client.connect(config.get('mqtt', 'server'), config.getint('mqtt', 'port'), 60) client.loop_start() # Keep running forever 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 initModem(port='/dev/ttyUSB0', baud=460800): global modem 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)
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 __init__(self, handleSMSCallBack): self.port = '/dev/ttyUSB2' ports = list(serial.tools.list_ports.comports()) for p in ports: if 'ZTE NMEA Device' in p.description: self.port = p.device self.baudRate = 115200 self.pin = None # SIM card PIN (if any) self.modem = GsmModem(self.port, self.baudRate, smsReceivedCallbackFunc=handleSMSCallBack\ ,incomingCallCallbackFunc=handleCall) self.modem.smsTextMode = False self.modem.connect(self.pin) self.signalStrength = self.modem.waitForNetworkCoverage(10) self.response = None self.modem.ownNumber
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)
class ModemWorker(Actor): def __init__(self, dev, serial_info, serial_manager): self.serial_manager = serial_manager self.dev = dev self.imsi = None self.serial_info = serial_info self.modem_info = None self.sim_config = None self.modem = None self.concat_pool = ConcatPool(self) self.concat_pool.start() self.state = 'initialized' super(ModemWorker, self).__init__('Modem %s' % dev) @property def state(self): return self._state @state.setter def state(self, new_state): if hasattr(self, '_state') and new_state != self._state: logger.info('STATE %s -> %s', self._state, new_state) self._state = new_state def run(self): step = self.connect try: while True: step = step() if step is None: break finally: self._try_modem_close() # ~~~~~ STATES ~~~~~ def connect(self): self.state = 'connecting' try: self.modem = GsmModem(self.dev, 19200) self.modem.connect() except TimeoutException: self.state = 'no modem detected' except Exception, e: self.state = 'error %s' % e else:
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 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 getAllText(key): if key.strip() == '9703BB8D5A': modem = GsmModem('/dev/ttyUSB0', 9600) try: print "Connecting modem" modem.connect() except Exception as e: return str(e) try: messages = modem.listStoredSms() except Exception as e: return str(e) modem.close() retString = "" print "Got %d messages" % len(messages) for message in messages: retString = retString + "%s : %s" % (message.number, message.text) + "\n" return retString else: return "Incorrect key"
def connect(self): self.state = 'connecting' try: self.modem = GsmModem(self.dev, 19200) self.modem.connect() except TimeoutException: self.state = 'no modem detected' except Exception, e: self.state = 'error %s' % e
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()
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 runModem(): print('Initializing modem...') #logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE, smsReceivedCallbackFunc=handleSms) modem.smsTextMode = False modem.connect(PIN) modem.deleteMultipleStoredSms() #modem.sendSms('+44740000000','asdsdefed',False) 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 autodetect_modem(pin=None, check_fn=None, modem_options={'baudrate': 9600}): """ Autodetect a suitable cellular modem connected to the system. :param pin: Security PIN to unlock the SIM. :param check_cn: Callable that should take a single ``modem`` argument and return True if the modem instance is suitable. :param modem_options: Structure to pass as keyword arguments to ``GsmModem`` initialisation. :type modem_options: dict-like :returns: Connected modem instance :rtype: :class:`gsmmodem.modem.GsmModem` This method will iterate through all potential serial ports on the system and attempt to ``connect()`` to each of them in turn. The first serial port that connects successfully, and passes the ``check_fn(modem)`` call (if ``check_fn`` is specified), will be returned. All other unsuccessful connections will be closed during the process. This method will return ``None`` if no modems could be detected. """ ports = enumerate_serial() if not ports: log.error('No modem ports detected on system.') return modem = None for port in ports: modem = GsmModem(port, **modem_options) try: log.debug('Attempting to connect to modem at %s' % port) modem.connect(pin=pin) if not check_fn or check_fn and check_fn(modem): log.debug('Successfully detected modem at %s' % port) return modem except SerialException: log.warn('Serial communication problem for port %s' % port) except TimeoutException: log.warn('Timeout detected on port %s' % port) log.debug('Closing modem at %s' % port) modem.close()
def main(): # logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE, smsReceivedCallbackFunc=handleSms) modem.smsTextMode = False modem.connect(PIN) try: modem.rxThread.join(2**31) finally: modem.close()
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(): if NUMBER == None or NUMBER == "00000": print( "Error: Please change the NUMBER variable's value before running this example." ) sys.exit(1) print("Initializing modem...") # logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE) modem.connect(PIN) print("Waiting for network coverage...") modem.waitForNetworkCoverage(30) print("Dialing number: {0}".format(NUMBER)) call = modem.dial(NUMBER) print("Waiting for call to be answered/rejected") wasAnswered = False while call.active: if call.answered: wasAnswered = True print("Call has been answered; waiting a while...") # Wait for a bit - some older modems struggle to send DTMF tone immediately after answering a call time.sleep(3.0) print("Playing DTMF tones...") try: if ( call.active ): # Call could have been ended by remote party while we waited in the time.sleep() call call.sendDtmfTone("9515999955951") except InterruptedException as e: # Call was ended during playback print("DTMF playback interrupted: {0} ({1} Error {2})".format( e, e.cause.type, e.cause.code)) except CommandError as e: print("DTMF playback failed: {0}".format(e)) finally: if call.active: # Call is still active print("Hanging up call...") call.hangup() else: # Call is no longer active (remote party ended it) print("Call has been ended by remote party") else: # Wait a bit and check again time.sleep(0.5) if not wasAnswered: print("Call was not answered by remote party") print("Done.") modem.close()
def main(): logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.INFO) modem = GsmModem(PORT, BAUDRATE, smsReceivedCallbackFunc=handleSms) modem.smsTextMode = False modem.connect(PIN) try: if modem.ownNumber: print("Modem phone number:", modem.ownNumber) print("IMSI:", modem.imsi) print("IMEI:", modem.imei) modem.processStoredSms() while True: print("--- Network: {0} / Signal: {1} ---".format( modem.networkName, modem.signalStrength)) modem.rxThread.join(60 * 60) finally: modem.close()
def run(self): logging.info("Modem thread running") global modem rxListenLength = 10 init_count = 0 while self.running and init_count > -1: try: init_count = init_count + 1 modem = GsmModem(PORT, BAUDRATE, incomingCallCallbackFunc=handleIncomingCall) logging.info("Initializing modem, try {0}.".format(init_count)) modem.connect(PIN) init_count = -1 except TimeoutException as e: logging.critical("Failed to initialize the GSM module: {0}", e) modem.close() logging.info('Waiting for incoming calls...') while self.running: try: #waitForNetworkCoverage() self.signalStrength = modem.signalStrength self.networkName = modem.networkName 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) # Comms are handled elsewhere so we could eventually just sleep, waiting #time.sleep(rxListenLength) modem.rxThread.join(rxListenLength) except (InterruptedException, PinRequiredError, IncorrectPinError, TimeoutException): logging.error("rxThread died: {0}".format(sys.exc_info()[0])) modem.close() logging.info("Modem closed.")
def main(): 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(PIN) print('Waiting for SMS message...') try: modem.rxThread.join(2**10) finally: modem.close()
def main(): 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(PIN) 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('Initializing modem...') modem = GsmModem(PORT, BAUDRATE, smsReceivedCallbackFunc=sms_catcher, incomingCallCallbackFunc=call_catcher) modem.smsTextMode = False modem.connect() print('Waiting for SMS or Call...') try: modem.rxThread.join() finally: modem.close()
def main(): if NUMBER == None or NUMBER == '00000': print('Error: Please change the NUMBER variable\'s value before running this example.') sys.exit(1) print('Initializing modem...') #logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE) modem.connect(PIN) print('Waiting for network coverage...') modem.waitForNetworkCoverage(30) print('Dialing number: {0}'.format(NUMBER)) call = modem.dial(NUMBER) print('Waiting for call to be answered/rejected') wasAnswered = False while call.active: if call.answered: wasAnswered = True print('Call has been answered; waiting a while...') # Wait for a bit - some older modems struggle to send DTMF tone immediately after answering a call time.sleep(3.0) print('Playing DTMF tones...') try: if call.active: # Call could have been ended by remote party while we waited in the time.sleep() call call.sendDtmfTone('9515999955951') except InterruptedException as e: # Call was ended during playback print('DTMF playback interrupted: {0} ({1} Error {2})'.format(e, e.cause.type, e.cause.code)) except CommandError as e: print('DTMF playback failed: {0}'.format(e)) finally: if call.active: # Call is still active print('Hanging up call...') call.hangup() else: # Call is no longer active (remote party ended it) print('Call has been ended by remote party') else: # Wait a bit and check again time.sleep(0.5) if not wasAnswered: print('Call was not answered by remote party') print('Done.') modem.close()
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 run(self): logging.info("Modem thread running") global modem rxListenLength = 10 init_count = 0 while self.running and init_count > -1: try: init_count = init_count + 1 modem = GsmModem(PORT, BAUDRATE, incomingCallCallbackFunc=handleIncomingCall) logging.info("Initializing modem, try {0}.".format(init_count)) modem.connect(PIN) init_count = -1 except TimeoutException as e: logging.critical("Failed to initialize the GSM module: {0}", e) modem.close() logging.info('Waiting for incoming calls...') while self.running: try: #waitForNetworkCoverage() self.signalStrength = modem.signalStrength self.networkName = modem.networkName 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) # Comms are handled elsewhere so we could eventually just sleep, waiting #time.sleep(rxListenLength) modem.rxThread.join(rxListenLength) except (InterruptedException, PinRequiredError, IncorrectPinError, TimeoutException): logging.error("rxThread died: {0}".format(sys.exc_info()[0])) modem.close() logging.info("Modem closed.")
def main(): if NUMBER == None or NUMBER == '00000': print('Error: Please change the NUMBER variable\'s value before running this example.') sys.exit(1) print('Initializing modem...') logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE) modem.connect(PIN) print('Waiting for network coverage...') modem.waitForNetworkCoverage(30) print('Dialing number: {0}'.format(NUMBER)) call = modem.dial(NUMBER, callStatusUpdateCallbackFunc=callStatusCallback) global waitForCallback while waitForCallback: time.sleep(0.1) print('Done')
def gmsmodem(port=3,baud=115200,pin=None): while port<9: try: print('Connecting to GSM modem on com %s...'%(port+1)) modem = GsmModem(port,baud) try: print('Checking for pin...') modem.connect(pin) try: print('Checking for network coverage...') modem.waitForNetworkCoverage(5) return modem except Exception, e: modem.close() print e except Exception, e: print e except Exception, e: print e port+=1
def initModem(port='/dev/ttyUSB1', baud=460800): global modem 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)
def listen(): global gsm jeedom_socket.open() logging.debug("Start listening...") try: logging.debug("Connecting to GSM Modem...") gsm = GsmModem(_device, int(_serial_rate), smsReceivedCallbackFunc=handleSms) if _text_mode == 'yes' : logging.debug("Text mode true") gsm.smsTextMode = True else : logging.debug("Text mode false") gsm.smsTextMode = False if _pin != 'None': logging.debug("Enter pin code : "+_pin) gsm.connect(_pin) else : gsm.connect() if _smsc != 'None' : logging.debug("Configure smsc : "+_smsc) gsm.write('AT+CSCA="{0}"'.format(_smsc)) logging.debug("Waiting for network...") gsm.waitForNetworkCoverage() logging.debug("Ok") try: jeedom_com.send_change_immediate({'number' : 'network_name', 'message' : str(gsm.networkName) }); except Exception, e: if str(e).find('object has no attribute') <> -1: pass logging.error("Exception: %s" % str(e)) try: gsm.write('AT+CPMS="ME","ME","ME"') gsm.write('AT+CMGD=1,4') except Exception, e: if str(e).find('object has no attribute') <> -1: pass logging.error("Exception: %s" % str(e))
unit = str(sys.argv[1]) device = str(sys.argv[2]) cardcode = str(sys.argv[3]) + "#" cardpin = str(sys.argv[4]) + "#" BAUDRATE = 115200 LOADCODE = '223' 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.connect() logging.info("Waiting for network coverage...") modem.waitForNetworkCoverage(30) logging.info("Loading %s with %s %s", unit, cardcode, cardpin) call = modem.dial( LOADCODE) wasAnswered = False while call.active: if call.answered: wasAnswered = True logging.info("Call answered") time.sleep(5.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='> ')
modem.deleteMultipleStoredSms(delFlag=1) unit = sys.argv[1] device = sys.argv[2] message = "Message" BAUDRATE = 115200 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, 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)
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) # 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) 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.')
# 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()
unit = str(sys.argv[1]) device = str(sys.argv[2]) cardcode = str(sys.argv[3]) BAUDRATE = 115200 LOADCODE = '1510' 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 = False modem.connect() logging.info("Waiting for network coverage...") modem.waitForNetworkCoverage(30) logging.info("Loading %s with %s", unit, cardcode) call = modem.dial( LOADCODE + cardcode) wasAnswered = False while call.active: if call.answered: wasAnswered = True logging.info("Call answered")
def start(self): """ Samotne jadro daemona: setupneme GmailAPI, setupneme GSM modem a zacneme provadet nekonecnou smycku """ self.running = True # (0) SETUP VIRTUAL SERIAL PORT FOR MODEM if "virtualPortInitCommand" in myconfig['modem']: try: virtualSerialPortInstance = virtualSerialPort(myconfig['modem']['virtualPortInitCommand']) virtualSerialPortInstance.start() except: pass else: virtualSerialPortInstance = None # (1) SETUP GMAIL ACCESS logging.info('Initializing GMAIL access...') try: gmailService = gmailUtils.get_service(self.cwd) except RuntimeError as e: print(str(e)) logging.critical(str(e)) if (virtualSerialPortInstance is not None): virtualSerialPortInstance.stop() #sys.exit(1) self.stop() ###################################################################################################################################################### # (2) SETUP GSM MODEM + bind a "smsReceived" callback + poll gmail inbox logging.info('Initializing GSM modem on {0} port @ {1} speed...'.format(myconfig['modem']['port'], myconfig['modem']['baudrate'])) modem = GsmModem(myconfig['modem']['port'], myconfig['modem']['baudrate'], smsReceivedCallbackFunc=self.incomingSmsHandler) modem.smsTextMode = False while self.running: # start of gsm init loop try: modem.connect(myconfig['modem']['pin']) except serial.SerialException: logging.error('Error: Cannot connect to modem on serial port %s @ %s. Trying again in %d sec...' % (myconfig['modem']['port'], myconfig['modem']['baudrate'], myconfig['modem']['errorRetryWaitTime'])) time.sleep(myconfig['modem']['errorRetryWaitTime']) except TimeoutException: logging.error('Error: Serial device %s @ %s timeout. Trying again in %d sec...' % (myconfig['modem']['port'], myconfig['modem']['baudrate'], myconfig['modem']['errorRetryWaitTime'])) time.sleep(myconfig['modem']['errorRetryWaitTime']) except PinRequiredError: # Fatal error logging.critical('Error: SIM card PIN required. Please provide PIN in the config file.') self.stop() return 1 except IncorrectPinError: # Fatal error logging.critical('Error: Incorrect SIM card PIN entered!') self.stop() return 1 else: logging.info('Modem connected.') try: logging.info('Checking for network coverage...') modem.waitForNetworkCoverage(8) # of seconds except TimeoutException: logging.warning('We can now start gmail inbox polling infinite loop.') print('Network signal strength is not sufficient, please adjust modem position/antenna and try again.') modem.close() else: logging.info('GSM modem is ready.') logging.info('We are now handling all incoming SMS messages.') try: if (myconfig['incomingSmsHandlerSetup']['processStoredSms'] == "all"): modem.processStoredSms(unreadOnly=False) elif (myconfig['incomingSmsHandlerSetup']['processStoredSms'] == "unread"): modem.processStoredSms(unreadOnly=True) except Exception as e: logging.critical("Nastal problem pri zpracovani drivejsich neprectenych SMS:") raise sys.exit(0) else: logging.info('We can now start gmail inbox polling infinite loop.') try: while self.running: # start of main gmail loop logging.debug('Checking incoming emails...') newMessagesCount = self.incomingGmailHandler(gmailService, modem) time.sleep(myconfig['general']['gmailQueueWaitingPeriod'] if newMessagesCount > 0 else myconfig['general']['gmailPollingInterval']) # end of main gmail loop except KeyboardInterrupt: #sys.exit(0) self.stop() return 0 except Exception as e: print("Nastala vyjimka v hlavni smycce daemona, viz log.") logging.exception("Nastal problem v hlavni smycce:") raise finally: print("Bye gmail loop.") finally: print("Bye stored sms handling try-cache.") finally: print("Bye.") modem.close() if (virtualSerialPortInstance is not None): virtualSerialPortInstance.stop() finally: print("end of gsm init loop") # end of gsm init loop # normally we won't reach this place, but when a non-fatal error happens # (like 'No modem found', 'No GSM signal', etc.), we can continue the loop to # try it again in the new iteration of the main loop # TODO - move kill socat here. Move socat init to try finally ###################################################################################################################################################### return 0 # just for make sure, the program should never end up on this line
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)
def main(): print('Initializing modem...') #logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE, incomingCallCallbackFunc=handleIncomingCall) modem.connect(PIN) print('Waiting for incoming calls...') 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()