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