Python Code Samples

From Lantronix Developer Wiki
Jump to: navigation, search


Determining the type of device

Get MAC address for identification

Sometimes it is useful to find out what kind of device the script is running on, so that it can be deployed on multiple types of PremierWave devices without modifying.

The code below creates the pwDevice class. When an instance of this class is created, it will first find out what the MAC address of the device is. This can be useful to use as a unique identifier. It will then determine which type of device it is. As an example, it also creates a property called import_file which is a string with the path of the file used for importing configuration. This will become useful if a program needs to change configuration of the device.

import os.path
class pwDevice:
	def __init__(self):
		mac = commands.getoutput("ifconfig eth0| grep HWaddr | awk '{ print $5 }'").strip()			
		self.mac = mac.translate(None,':')
		if os.path.exists('/ltrx_user/pwxcr/pwxc_hspa_import.xcr'):
			self.type = "PremierWave XC HSPA+"
			self.import_file = '/ltrx_user/pwxcr/pwxc_hspa_import.xcr'
		elif os.path.exists('/ltrx_user/pwxcr/pwxn_import.xcr'):
			self.type = "PremierWave XN"
			self.import_file = '/ltrx_user/pwxcr/pwxn_import.xcr'
		elif os.path.exists('/ltrx_user/pwxcr/pwen_import.xcr'):
			self.type = "PremierWave EN"
			self.import_file = '/ltrx_user/pwxcr/pwen_import.xcr'
		elif os.path.exists('/ltrx_user/pwxcr/pwse1000_import.xcr'):
			self.type = "PremierWave SE1000"
			self.import_file = '/ltrx_user/pwxcr/pwse1000_import.xcr'
			self.type = "Unknown"

This example will create an instance, and log the MAC address to a file in the PremierWave's filesystem:

import logging
logging.basicConfig(level=logging.DEBUG, filename='pythonDebug.log')
if __name__ == '__main__':
		dev = pwDevice()
	except Exception, ex:
		logging.exception('Was not able to log')

Changing PremierWave configuration


The Lantronix application running on the PremierWave device safely handles the reboot cycle. You can kick off a reboot by importing XML into the configuration file that indicates to the application to start a reboot.

xml = '''<?xml version="1.0" standalone="yes"?>
<!DOCTYPE configrecord [  <!ELEMENTconfigrecord (configgroup+)>   
<!ELEMENT configgroup (configitem+,configgroup*)>   
<!ELEMENT configitem(value+)>   
<!ELEMENT value (#PCDATA)>   
<!ATTLIST configrecord version CDATA #IMPLIED>   
<!ATTLISTconfiggroup name CDATA #IMPLIED>   
<!ATTLIST configgroup instance CDATA #IMPLIED>   
<!ATTLIST configitem nameCDATA #IMPLIED>   
<!ATTLIST configitem instance CDATA #IMPLIED>   
<!ATTLIST value name CDATA #IMPLIED>]>
<configrecord version = "">
<configgroup name = "xml import control">       
<configitem name = "reboot">           

import logging
logging.basicConfig(level=logging.DEBUG, filename='pythonDebug.log')
if __name__ == '__main__':
       dev = pwDevice()	
	       f = open(dev.import_file,'w')
       except Exception, ex:

Send SMS from PremierWave XC HSPA+

Run Linux commands

Sometimes it might be useful to send a text message (SMS) from the PremierWave XC HSPA+. The example below calls the ctest utility to do so. Note that because it's calling a Linux command line operation, special characters such as spaces need to be properly escaped.

import os

num = '+15555551212'
msg = 'Hello\ from\ PremierWave\ XC\ HSPA+'

os.system('ctest sms-send ' + num + ' ' + msg)

Send emails through Gmail

Setting up a menu on the serial port, and sending authenticated email

This example makes use of several modules to access the serial port, ask the user for information, parse the result, and then send emails. All the modules used are already installed on the PremierWave firmware. To access the serial ports with use Pyserial, and to send emails we use smtplib which is part of the Standard Library.

#!/usr/bin/env python
import serial
import smtplib
from time import sleep

Here we'll define a function to send emails. In this case we're using the Gmail servers. Notice that if you have 2-step verification enabled in your Gmail account, you'll need to use an App password instead of your standard password. See this document:

def SendEmail(sender,recepient,subject,passwd,msg):
	smtpserver = ''
	smtpport = 587
	s = smtplib.SMTP(smtpserver, smtpport)
	s.sendmail(sender,recepient, 'To: ' + recepient + '\n' + 'From: ' + sender + '\n' + 'Subject: ' + subject + '\n\n' + msg +  '\n\n')

Also define a function to read a line (separated by a carriage return) and return everything in that line but the carriage return. This can be useful in many projects.

def receive_line(ser):
	buffer = 
	while True:
		buffer = buffer +
		if '\r' in buffer:
			lines = buffer.split('\r')
			return lines[-2]			

Run the main part of the program. See the comments inline the code.

# We'll define ttyS1 which is Serial Port 1 on the PremierWave XC HSPA+, but Serial Port 2 on PremierWave XN
# (the XN has ttyS1 and ttyS2 "reversed")			
port = '/dev/ttyS1'
baud = 9600

ser = serial.Serial(port, baud)

# Start the console on the serial port to ask for the details of the email to be sent
ser.write('Welcome to the serial emailer!\n\r')
ser.write('Please enter your Gmail email address (as sender)\n\r')
sender = receive_line(ser)
ser.write('From: ' + sender + '\n\rNow enter your Gmail password\n\r')
passwd = receive_line(ser)
ser.write('Got it, now enter the recepient of the email\n\r')
recepient = receive_line(ser)
ser.write('To: ' + recepient + '\n\rAlmost done here, enter a Subject for your email\n\r')
subject = receive_line(ser)
ser.write('Subject: ' + subject + '\n\rNow enter the body of the message. Finish with a blank line\n\r')
msg = 
while True:
	line = receive_line(ser)

	if line == "":
		ser.write("Email sent, I'm done!\n\r")
		msg = msg + line + '\n'
Personal tools