本文整理汇总了Python中gsmmodem.modem.GsmModem.close方法的典型用法代码示例。如果您正苦于以下问题:Python GsmModem.close方法的具体用法?Python GsmModem.close怎么用?Python GsmModem.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gsmmodem.modem.GsmModem
的用法示例。
在下文中一共展示了GsmModem.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getAllText
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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"
示例2: Modem
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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))
示例3: send_sms_at
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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)
示例4: getUnreadText
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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"
示例5: text
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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'
示例6: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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()
示例7: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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();
示例8: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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()
示例9: autodetect_modem
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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()
示例10: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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()
示例11: gmsmodem
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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
示例12: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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()
示例13: run
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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.")
示例14: initModem
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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)
示例15: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import close [as 别名]
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.')