configure_cots_bandrich_ue.py 8.47 KB
Newer Older
1
#!/usr/bin/python 
2 3 4 5 6
#/*
# * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
# * contributor license agreements.  See the NOTICE file distributed with
# * this work for additional information regarding copyright ownership.
# * The OpenAirInterface Software Alliance licenses this file to You under
Cedric Roux's avatar
Cedric Roux committed
7
# * the OAI Public License, Version 1.1  (the "License"); you may not use this file
8 9 10 11 12 13 14 15 16 17 18 19 20 21
# * except in compliance with the License.
# * You may obtain a copy of the License at
# *
# *      http://www.openairinterface.org/?page_id=698
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
# *-------------------------------------------------------------------------------
# * For more information about the OpenAirInterface (OAI) Software Alliance:
# *      contact@openairinterface.org
# */
Rohit Gupta's avatar
Rohit Gupta committed
22 23

# \author Navid Nikaein, Rohit Gupta
24

25 26 27
import time
import serial
import os
28
from socket import AF_INET
29 30 31 32 33 34
from pyroute2 import IPRoute
import sys
import re
import threading
import signal
import traceback
35
import os
36
import commands
37 38

# configure the serial connections (the parameters differs on the device you are connecting to)
39 40
#First we find an open port to work with
serial_port=''
41
ser=serial.Serial()
Rohit Gupta's avatar
Rohit Gupta committed
42 43 44 45 46
openair_dir = os.environ.get('OPENAIR_DIR')
if openair_dir == None:
  print "Error getting OPENAIR_DIR environment variable"
  sys.exit(1)

47 48 49 50
sys.path.append(os.path.expandvars('$OPENAIR_DIR/cmake_targets/autotests/tools/'))

from lib_autotest import *

51 52
def find_open_port():
   global serial_port, ser
53
   max_ports=100
54
   serial_port=''
55 56 57
   while True:
     if os.path.exists(serial_port) == True:
       return serial_port
58
     for port in range(0,100):
59 60 61 62 63 64 65 66 67 68 69
        serial_port_tmp = '/dev/ttyUSB'+str(port)
        if os.path.exists(serial_port_tmp) == True:
           print 'New Serial Port : ' + serial_port_tmp
           serial_port = serial_port_tmp
           break
     if serial_port == '':
        print" Not able to detect valid serial ports. Resetting the modem now..."
        reset_ue()
     else :
        ser = serial.Serial(port=serial_port)
        return
70

71 72
    
#serial_port = '/dev/ttyUSB2'
Rohit Gupta's avatar
Rohit Gupta committed
73
bandrich_ppd_config = os.environ.get('OPENAIR_DIR') + '/cmake_targets/autotests/tools/wdial.bandrich.conf'
74 75 76 77 78 79 80 81 82 83 84 85 86

exit_flag=0

def signal_handler(signal, frame):
        print('You pressed Ctrl+C!')
        print('Resetting the UE to detached state')
        timeout=10
        exit_flag=1
        send_command('AT+CGATT=0' , 'OK' , timeout)
        sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

87

88 89 90 91 92

#ser.open()
#ser.isOpen()

class pppThread (threading.Thread):
93
    def __init__(self, threadID, name, counter,port):
94 95 96 97
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
98
        self.port=port
99 100 101 102 103 104 105 106 107
    def run(self):
        print "Starting " + self.name
        #Here we keep running pppd thread in indefinite loop as this script terminates sometimes
        #while 1:
        while 1:
           time.sleep(5) #Hard coded, do not reduce this number! 
           print "Starting wvdial now..."
           print 'exit_flag = ' + str(exit_flag)
           send_command('AT+CGATT=1','OK', 300)
108 109 110 111
           
           #Now we do search and replace on wvdial config file
           cmd="sed -i \"s%Modem = .*%Modem = " + self.port + "%g\" " +  bandrich_ppd_config
           os.system(cmd)
112 113 114 115 116 117 118 119
           os.system('wvdial -C ' + bandrich_ppd_config + '' )
           if exit_flag == 1:
              print "Exit flag set to true. Exiting pppThread now"
           print "Terminating wvdial now..."

def send_command (cmd, response, timeout):
   count=0
   sleep_duration = 1
Rohit Gupta's avatar
Rohit Gupta committed
120
   print 'In function: send_command: cmd = <' + cmd + '> response: <' + response + '> \n'
121
   global serial_port, ser
122
   while count <= timeout:
Rohit Gupta's avatar
Rohit Gupta committed
123
      try:
124 125 126
        #Sometimes the port does not exist coz of reset in modem.
        #In that case, we need to search for this port again
        if os.path.exists(serial_port) == False:
127
            find_open_port()
Rohit Gupta's avatar
Rohit Gupta committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141
        ser.write (cmd + '\r\n')
        out = ''
        time.sleep(sleep_duration)
        count = count + sleep_duration
        while ser.inWaiting() > 0:
            out += ser.read(1)
        print 'out = <' + out + '> response = <' + response + '> \n'
        if re.search(response, out):
          break
      except Exception, e:
        error = ' cmd : ' + cmd + ' response : ' + response
        error = error + ' In function: ' + sys._getframe().f_code.co_name + ': *** Caught exception: '  + str(e.__class__) + " : " + str( e)
        error = error + traceback.format_exc()
        print error
142
        time.sleep(1)
143 144 145 146
        

def start_ue () :
   #print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
147
   global serial_port
148 149
   timeout=60 #timeout in seconds
   send_command('AT', 'OK' , timeout)
150
   send_command('AT+CFUN=1' , 'OK' , timeout)
Rohit Gupta's avatar
Rohit Gupta committed
151
   #send_command('AT+CGATT=0' , 'OK' , timeout)
152 153 154
   send_command('AT+CGATT=1','OK', 300)
   #os.system('wvdial -C ' + bandrich_ppd_config + ' &' )
   
155
   thread_ppp = pppThread(1, "ppp_thread", 1,port=serial_port)
156 157
   thread_ppp.start()

158
   #iface='ppp0'
159 160 161
   
   while 1:
     time.sleep ( 2)
162
     iface=''
163 164 165 166
     #Now we check if ppp0 interface is up and running
     try:
        if exit_flag == 1:
          break
167 168 169
        cmd="ifconfig -a | sed 's/[ \t].*//;/^$/d' | grep ppp"
        status, out = commands.getstatusoutput(cmd)
        iface=out
170 171
        ip = IPRoute()
        idx = ip.link_lookup(ifname=iface)[0]
172 173 174 175 176 177
        print "iface = " + iface
        print " Setting route now..."
        #os.system("status=1; while [ \"$status\" -ne \"0\" ]; do route add -host " + gw + ' ' + iface + " ; status=$? ;sleep 1; echo \"status = $status\"  ; sleep 2; done ")
        os.system ('route add -host ' + gw + ' ' + iface + ' 2> /dev/null')
        #ip.route('add', dst=gw, oif=iface)
        
Rohit Gupta's avatar
Rohit Gupta committed
178
        os.system('sleep 5')
179 180 181
        #print "Starting ping now..."
        os.system ('ping -c 1 ' + gw)
        #break
182 183 184 185 186 187 188 189 190 191 192 193
     except Exception, e:
        error = ' Interface ' + iface + 'does not exist...'
        error = error + ' In function: ' + sys._getframe().f_code.co_name + ': *** Caught exception: '  + str(e.__class__) + " : " + str( e)
        error = error + traceback.format_exc()
        print error
    
   thread_ppp.join()

def stop_ue():
   timeout=60
   os.system('killall wvdial')
   send_command('AT', 'OK' , timeout)
194
   send_command('AT+CGATT=0' , 'OK|ERROR' , timeout)
195
   send_command('AT+CFUN=4' , 'OK' , timeout)
196

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

#reset the USB BUS of Bandrich UE
def reset_ue():
  stringIdBandrich='BandRich, Inc. 4G LTE adapter'
  status, out = commands.getstatusoutput('lsusb | grep -i \'' + stringIdBandrich + '\'')
  if (out == '') :
     print "Bandrich 4G LTE Adapter not found. Exiting now..."
     sys.exit()
  p=re.compile('Bus\s*(\w+)\s*Device\s*(\w+):\s*ID\s*(\w+):(\w+)')
  res=p.findall(out)
  BusId=res[0][0]
  DeviceId=res[0][1]
  VendorId=res[0][2]
  ProductId=res[0][3]
  usb_dir= find_usb_path(VendorId, ProductId)
212
  print "Bandrich 4G LTE Adapter found in..." + usb_dir
213
  print "Sleeping now for 45 seconds...please wait..."
214
  cmd = "sudo sh -c \"echo 0 > " + usb_dir + "/authorized\""
215
  os.system(cmd + " ; sleep 15" )
216
  cmd = "sudo sh -c \"echo 1 > " + usb_dir + "/authorized\""
217
  os.system(cmd + " ; sleep 30" )
218
  find_open_port()
219
  stop_ue()
220

221 222 223 224
i=1
gw='192.172.0.1'
while i <  len(sys.argv):
    arg=sys.argv[i]
225
    if arg == '--start-ue' :
226
        print "Turning on UE..."
227 228
        find_open_port()
        print 'Using Serial port : ' + serial_port  
229 230
        start_ue()
    elif arg == '--stop-ue' :
231
        print "Turning off UE..."
232 233
        find_open_port()
        print 'Using Serial port : ' + serial_port  
234
        stop_ue()
235
    elif arg == '--reset-ue' :
236
        print "Resetting UE..."
237
        find_open_port()
238
        reset_ue()
239 240 241 242 243 244 245 246
    elif arg == '-gw' :
        gw = sys.argv[i+1]
        i=i+1
    elif arg == '-h' :
        print "--reset-ue:  Reset the UE on USB Bus. Similar to unplugging and plugging the UE"
        print "--stop-ue:  Stop the UE. Send DETACH command" 
        print "--start-ue:  Start the UE. Send ATTACH command"
        print "-gw:  Specify the default gw as sometimes the gateway/route arguments are not set properly via wvdial"
247 248 249
    else :
        print " Script called with wrong arguments, arg = " + arg
        sys.exit()
250
    i = i +1
251 252