本文整理汇总了Python中gsmmodem.modem.GsmModem.waitForNetworkCoverage方法的典型用法代码示例。如果您正苦于以下问题:Python GsmModem.waitForNetworkCoverage方法的具体用法?Python GsmModem.waitForNetworkCoverage怎么用?Python GsmModem.waitForNetworkCoverage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gsmmodem.modem.GsmModem
的用法示例。
在下文中一共展示了GsmModem.waitForNetworkCoverage方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_sms_at
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [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)
示例2: text
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [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'
示例3: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [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.')
示例4: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [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, callStatusUpdateCallbackFunc=callStatusCallback)
global waitForCallback
while waitForCallback:
time.sleep(0.1)
print('Done')
示例5: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [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()
示例6: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [as 别名]
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.')
示例7: main
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [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()
示例8: gmsmodem
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [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
示例9: listen
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [as 别名]
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))
示例10: initModem
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [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)
示例11: GsmModem
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [as 别名]
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)
try:
modem.sendSms(phone,message, deliveryTimeout=30)
except CommandError as e:
logging.info('SMS send failed: {0}'.format(e))
except TimeoutException as e:
示例12: start
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [as 别名]
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):
#.........这里部分代码省略.........
示例13: __init__
# 需要导入模块: from gsmmodem.modem import GsmModem [as 别名]
# 或者: from gsmmodem.modem.GsmModem import waitForNetworkCoverage [as 别名]
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
#.........这里部分代码省略.........