Created
March 15, 2026 22:21
-
-
Save polprog/21f1fc9e0625bec8e5dcc3cc88db0871 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import argparse | |
| import serial | |
| import time | |
| import re | |
| # Return signal level in dBm | |
| def get_signallevel(tty): | |
| resp = send_command(tty, b"AT+CSQ\r") | |
| csq = int(re.match(".* ([0-9]+),[0-9]+.*", resp).group(1)) | |
| return -111 + 2*(csq-1) | |
| # Return operator name | |
| def get_operator(tty): | |
| resp = send_command(tty, b"AT+COPS?\r") | |
| oper = re.match("\\+COPS: .*\"(.*)\"", resp).group(1) | |
| return oper | |
| def get_imei(tty): | |
| return send_command(tty, b"AT+GSN\r").split("\n")[0] | |
| def get_imsi(tty): | |
| return send_command(tty, b"AT+CIMI\r").split("\n")[0] | |
| def get_number(tty): | |
| resp = send_command(tty, b"AT+CNUM\r") | |
| oper = re.match("\\+CNUM: .*,\"(.*)\",.*", resp).group(1) | |
| return oper | |
| regstat = ["Not registered, not searching", "Registered (domestic)", | |
| "Not registered, searching", "Rejected", "Unknown", "Roaming"] | |
| def get_regstatus(tty): | |
| resp = send_command(tty, b"AT+CREG?\r") | |
| reg = re.match("\\+CREG: (.*)", resp).group(1) | |
| status = reg.split(",")[1] | |
| return status | |
| def send_command(tty, cmd): | |
| try: | |
| # Initialize the serial connection | |
| with serial.Serial(tty, baudrate=115200, timeout=1) as modem: | |
| modem.write(cmd) | |
| time.sleep(1) | |
| response = modem.read_all().decode('utf-8', errors='ignore') | |
| return response.strip() | |
| except serial.SerialException as e: | |
| return f"Error: {e}" | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description='Modem utility') | |
| parser.add_argument('tty', type=str, help='Modem TTY (e.g., /dev/ttyUSB0).') | |
| parser.add_argument('action', type=str, help='action', default="all") | |
| args = parser.parse_args() | |
| tty = args.tty | |
| action = args.action | |
| send_command(tty, b"ATE0\r") | |
| if(action == "all"): | |
| print("IMEI\t\t", get_imei(tty)) | |
| print("IMSI\t\t", get_imsi(tty)) | |
| print("Phone number\t", get_number(tty)) | |
| print("signal level\t", get_signallevel(tty), "dBm") | |
| print("operator\t", get_operator(tty)) | |
| r = int(get_regstatus(tty)) | |
| print("reg status\t", r, regstat[r]) | |
| if(action == "rxlevel"): | |
| print(get_signallevel(tty), "dBm") | |
| elif(action == "oper"): | |
| print(get_operator(tty)) | |
| elif(action == "number"): | |
| print(get_number(tty)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment