meta-netmodule-bsp/recipes-connectivity/sim-config/files/sim-config.py

110 lines
2.8 KiB
Python
Executable File

#!/usr/bin/env python3
import serial
import os
import time
import configparser
import sys
CONFIG = '/etc/sim.conf'
SERIAL_DEV = '/dev/ttyACM0'
GPIO_PATH = '/sys/class/gpio/'
GPIO_SIM_SW = '44'
GPIO_SIM_RST = '57'
RST_FILE = '/tmp/modem-reset-required'
rst = False
def write_to_file(file, value):
f = open(file, 'w')
f.write(value)
f.close()
def reset_modem():
print("modem reset")
write_to_file(GPIO_PATH + 'export', GPIO_SIM_RST)
write_to_file(GPIO_PATH + 'gpio' + GPIO_SIM_RST + '/direction', 'out')
write_to_file(GPIO_PATH + 'gpio' + GPIO_SIM_RST + '/value', '1')
time.sleep(2)
write_to_file(GPIO_PATH + 'gpio' + GPIO_SIM_RST + '/value', '0')
print("reset done")
# Wait until modem rebooted
while True:
dirs = os.listdir("/dev")
for file in dirs:
if file == 'ttyACM2':
sys.exit(0);
time.sleep(1)
def is_rst_required():
global rst
if rst:
return True
elif os.path.exists(RST_FILE):
return True
else:
return False
def switch_sim():
global rst
write_to_file(GPIO_PATH + 'export', GPIO_SIM_SW)
write_to_file(GPIO_PATH + 'gpio' + GPIO_SIM_SW + '/direction', 'out')
write_to_file(GPIO_PATH + 'gpio' + GPIO_SIM_SW + '/value', '0')
rst = True
def sim_present(ser):
cmd = b'AT+CCID?'
while True:
try:
ser.flushInput()
ser.write(cmd)
ser.write(b'\r')
s = ser.read_until(b'OK')
if b'ERROR' in s:
return False
elif b'OK' in s:
return True
except Exception as e:
print("Exception : " + str(e))
time.sleep(1)
return s
def check_sim_presence():
while not os.path.exists(SERIAL_DEV):
time.sleep(1)
ser = serial.Serial(SERIAL_DEV, 115200, timeout=0.5)
while True:
try:
ser.read()
break
except Exception:
pass
if sim_present(ser):
print("sim present")
else:
print("no sim, switching to esim")
switch_sim()
ser.close()
def read_config():
config = configparser.ConfigParser()
config.read(CONFIG)
print(config.get('default', 'SIM'))
sim = config.get('default', 'SIM')
if sim == 'auto':
check_sim_presence()
elif sim == 'esim' or sim == 'ui-top':
switch_sim()
# ui-btm and main are default
if is_rst_required():
reset_modem()
read_config();