Skip to content

SIM800L, SIM800C and SIM800H GSM module library for the Raspberry Pi to send, receive, delete SMS messages, perform HTTP GET/POST requests and many additional queries

License

Notifications You must be signed in to change notification settings

Ircama/sim800l-gsm-module

 
 

Repository files navigation

Raspberry Pi SIM800L, SIM800C and SIM800H GSM module

Raspberry Pi PyPI Python Versions PyPI download month GitHub license

SIM800L GSM module library for Linux systems like the Raspberry Pi. This library was also successfully tested with SIM800C and should also support SIM800H.

This library provides a driver for SIMCom GSM modules (SIM800L, SIM800C, SIM800H) via AT commands over a serial interface. It supports SMS (including multipart), HTTP/HTTPS GET and POST requests, DNS resolution, RTC synchronization, and access to module information. SMS messaging can be done in TEXT, HEX, or PDU mode (default: PDU). Possibly the driver is also compatible with newer modules like SIM7100 and SIM5300.

Key features include:

  • send_sms(): Sends SMS messages, automatically handling multipart when necessary.
  • read_next_message(): Retrieves the next SMS, abstracting message type and reassembling multipart content.
  • http(): Executes HTTP and HTTPS GET/POST requests, returning response status and payload.
  • dns_query(): Resolves domain names to IPs via the module’s DNS functionality.
  • ping(): ICMP ping of a domain name or IP address.
  • internet_sync_time(): syncronize the RTC time with the NTP time server and returns the current NTP time.

The library also exposes over 30 methods to configure and query the SIM module.

AT Protocol issues

The SIMCom SIM800 series (including models such as SIM800L, SIM800C, SIM800H and others) supports a broad set of cellular and Internet features, all accessible through a proprietary AT command set over the module’s asynchronous serial interface. This software utilizes only a limited subset of these extensive set of AT commands.

The AT command protocol is fundamentally inadequate for reliable and verifiable communication and presents intrinsic limitations when employed for robust operations: it is inherently textual and lacks the formal structure of communication protocols that utilize packetized data exchange.

AT commands are plain-text strings without explicit framing mechanisms. Unlike packet-based protocols, AT messages do not encapsulate data within headers that define payload length, type, or integrity information such as checksums or CRCs. Consequently, parsing and verifying the completeness and correctness of messages becomes error-prone.

Moreover, AT-based communication lacks a standardized state machine or signaling mechanisms to indicate distinct phases of a connection lifecycle. Commands that initiate, maintain, or terminate connections must be issued and interpreted in a predefined order, but the protocol itself does not return the transition between these states. This absence of inherent session management results in brittle implementations, where the client must continually probe the status of operations.

In addition, vendor-specific instructions introduce proprietary connection setup sequences requiring polling or conditional branching based on context-sensitive responses, and may also include asynchronous "Unsolicited Result Codes" within the textual communication that needs special processing while managing the workflow. Without structured feedback or flags denoting session phases, the client application must rely on loosely coupled responses to maintain protocol correctness.

Through an accurately tested heuristic approach, this software attempts to handle all supported operations via the AT protocol as robustly as possible, with the goal of automatically recovering from errors whenever feasible.

Setup

This module only installs on Linux (not on Windows).

Hw Requirements

  • Linux system with a UART serial port, or Raspberry Pi with Raspberry Pi OS (this library has been tested with Buster and Bullseye).
  • External power supply for the SIM800L (using the Raspberry Pi 5V power supply, a standard diode (1N4007) with voltage drop of about 0.6 volts and a 1 F capacitor might work). A stable power supply with adequate power is crucial for the correct operation of the module.

Installation

Check that the Python version is 3.6 or higher (python3 -V), then install the sim800l-gsm-module with the following command:

python3 -m pip install sim800l-gsm-module

Prerequisite components: pyserial, gsm0338. All needed prerequisites are automatically installed with the package.

Alternatively to the above mentioned installation method, the following steps allow installing the latest version from GitHub.

  • Optional preliminary configuration (if not already done):

    sudo apt-get update
    sudo apt-get -y upgrade
    sudo add-apt-repository universe # this is only needed if "sudo apt install python3-pip" fails
    sudo apt-get update
    sudo apt install -y python3-pip
    python3 -m pip install --upgrade pip
    sudo apt install -y git
  • Run this command:

    python3 -m pip install git+https://github.com/Ircama/sim800l-gsm-module

To uninstall:

python3 -m pip uninstall -y sim800l-gsm-module

Hardware connection

sim800l

Disabling the serial console login

Disabling the serial console login is needed in order to enable communication between the Raspberry Pi and SIM800L via /dev/serial0.

  • Open the terminal on your pi and run sudo raspi-config
  • Select Interfaces → Serial
  • Select No to the 1st prompt and Yes for the 2nd one.

Basic use

Check Usage examples. Basic program:

from sim800l import SIM800L
sim800l = SIM800L()
sim800l.setup()
print("Unit Name:", sim800l.get_unit_name())

API Documentation

For debugging needs, logs can be set to the maximum level (verbose mode, tracing each request/response) with the following command:

import logging
logging.getLogger().setLevel(5)`

Main Commands

sim800l = SIM800L(port="/dev/serial0", baudrate=115000, timeout=3.0, write_timeout=300, inter_byte_timeout=10, mode="PDU")

Class instantiation (using pySerial)

Parameters:

  • port (str): Serial port (e.g., /dev/serial0).
  • baudrate (int): Baud rate (default: 115000).
  • timeout (float): Read timeout in seconds.
  • write_timeout (int): Write timeout in seconds.
  • inter_byte_timeout (int): Timeout between bytes during read.
  • mode (str): SMS mode (TEXT, HEX, or PDU).

setup(disable_netlight=False)

Run setup strings for the initial configuration of the SIM800 module

  • disable_netlight: True if the Net Light LED has to be disabled (default is to enable it).

return: True if setup is successfully completed; None in case of module error.


SMS

read_next_message(all_msg=False, index=0, delete=True, tuple=False, concatenate=False, delta_min=15)

Check messages, read one message and then delete it. This function can be repeatedly called to read all stored/received messages one by one and delete them.

  • all_msg: True if no filter is used (read and unread messages). Otherwise only the unread messages are returned. return: retrieved message text (string), otherwise: None = no messages to read; False = read error (module error)

Aggregate multipart PDU messages. Only delete messages if there are no errors.

  • all_msg: True if no filter is used (return both read and non read messages). Otherwise, only the non read messages are returned.
  • index: read index message in processed array; default is the first one.
  • delete: delete the message after reading it.
  • tuple: returns a tuple instead of the plain text. Tuple: [MSISDN origin number, SMS date string, SMS time string, SMS text]
  • concatenate: concatenate text messages (text mode) when read message is > 150 chars. Not reliable (suggest using PDU mode)
  • delta_min: max time in minutes to keep uncompleted multipart undecoded (allowing to wait for its completion)

return: retrieved message text (string), otherwise: None = no messages to read; False = read error (module error)

As an example of usage, this is a trivial continuous SMS message monitor showing all incoming messages for 10 minutes (it also includes a recovery operation that resets the device in case of fault, that should never occur in normal conditions):

import time
import threading
from sim800l import SIM800L

RESET_GPIO = 24

def reset_and_setup(sim800l, disable_netlight):
    """Perform hard reset and attempt setup."""
    time.sleep(1)
    sim800l.hard_reset(RESET_GPIO)
    time.sleep(20)
    return sim800l.setup(disable_netlight=disable_netlight)

def sms_listener():
    sim800l = SIM800L()
    net_light_disabled = not sim800l.get_netlight()

    if not sim800l.setup(disable_netlight=net_light_disabled):
        if not reset_and_setup(sim800l, net_light_disabled):
            return

    print("Message monitor started")
    while True:
        msg = sim800l.read_next_message(all_msg=True)
        if msg is False:
            if not reset_and_setup(sim800l, net_light_disabled):
                return
            continue
        if msg is not None:
            print("Received SMS message:", repr(msg))

# Usage Example: Start SMS Message Monitor
listener_thread = threading.Thread(target=sms_listener, daemon=True)
listener_thread.start()

print("Sample running for 10 minutes and printing any received message.")
time.sleep(600)
print("Terminated.")

send_sms(destno, msgtext, ...)

Sends an SMS.

It includes sending multipart SMS messages (long SMS) if mode is PDU.

Parameters:

  • destno (str): Destination phone number.
  • msgtext (str): Message content.
  • validity (int): SMS validity period (PDU mode).
  • smsc (str): SMSC number (PDU mode).
  • requestStatusReport (bool): Request delivery report.
  • rejectDuplicates (bool): Reject duplicate messages.
  • sendFlash (bool): Send as flash SMS.

Returns:

  • True: SMS sent successfully.
  • False: Failed to send.

read_and_delete_all(index_id=0, delete=True)

Reads and deletes all SMS messages.

Read the message at position 1, otherwise delete all SMS messages, regardless the type (read, unread, sent, unsent, received). If the message is succesfully retrieved, no deletion is done. (Deletion only occurs in case of retrieval error.) Notice that, while generally message 1 is the first to be read, it might happen that no message at position 1 is available, while other positions might still include messages; for those cases (missing message at position 1, but other messages available at other positions), the whole set of messages is deleted.

Parameters:

  • index_id: Starting index
  • delete: Whether to delete after reading

Returns:

  • str: Message text
  • None: No messages
  • False: Error

read_sms(index_id)

Reads an SMS by index.

Parameters:

  • index_id (int): SMS storage index (1-based).

Returns:

  • tuple: (origin, date, time, text).
  • None: No message.
  • False: Read error.

delete_sms(index_id)

Deletes an SMS by index.

Parameters:

  • index_id (int): SMS storage index.

GPRS

dns_query(apn=None, domain=None, timeout=10)

Perform a DNS query.

Parameters:

  • apn (str): The APN string required for network context activation.
  • domain (str): The domain name to resolve.
  • timeout (int): Maximum duration in seconds to wait for responses (default: 10).

Returns:

  • dict: On success, returns a dictionary with keys:

    • 'domain': resolved domain name
    • 'ips': list of resolved IP addresses
    • 'local_ip': the device's IP address
    • 'primary_dns': Primary DNS server used for the query
    • 'secondary_dns': Secondary DNS server used for the query
  • False: On failure due to command error, timeout, or unexpected responses.

  • None: If the DNS query completes but no result is found (domain not resolved).


ping(apn=None, domain=None, timeout=10)

Perform a ICMP ping.

Parameters:

  • apn (str): The APN string required for network context activation.
  • domain (str): The domain name to ping.
  • timeout (int): Maximum duration in seconds to wait for responses (default: 10).

Returns: dict or False

  • dict: On success, returns a dictionary summarizing the ICMP ping results with keys:

    • 'local_ip': the device's IP address

    • 'ip': the target IP address that was pinged (not available if the ping failed)

    • 'results': (not available is the ping failed) a list of dictionaries, one per ping response, each with:

      • 'seq': sequence number of the ping response
      • 'ttl': time-to-live value returned in the ICMP response
      • 'time': round-trip time (RTT) in milliseconds
  • False: On failure due to command error, timeout, or unexpected responses.


http(url, data=None, apn=None, ...)

Run the HTTP GET method or the HTTP POST method and return retrieved data.

Automatically perform the full PDP context setup and close it at the end (use keep_session=True to keep the IP session active). Reuse the IP session if an IP address is found active.

Automatically open and close the HTTP session, resetting errors.

Parameters:

  • url (str): Target URL.
  • data (bytes): Payload for POST requests.
  • apn (str): APN for GPRS connection.
  • method (str): GET or POST (or PUT, same as POST).
  • use_ssl (bool): Use HTTPS.
  • content_type (str): HTTP Content-Type header.
  • http_timeout (int): Timeout in seconds.
  • keep_session (bool): Keep PDP context active.

Returns:

  • status, str/bytes: tuple including two values: HTTP status code (numeric, e.g., 200) and Response data (which can be text or binary).
  • False, None: Request failed.

While the Content type header field can be set, the Content encoding is always null.

Sending data with zlib is allowed:

import zlib
body = zlib.compress('hello world'.encode())
status, ret_data = sim800l.http("...url...", method="POST", content_type="zipped", data=body, apn="...")

Note on SSL: SIM800L does not support AT+HTTPSSL on firmware releases less than R14.18 (e.g., 1308B08SIM800L16, which is SIM800L R13.08 Build 08, 16 Mbit Flash, does not support SSL). Newer firmwares of SIM800L support SSL2, SSL3 and TLS 1.0, but not TLS 1.2 (this is for any SIM800L known firmwares including Revision 1418B06SIM800L24, which is SIM800L R14.18 Build 06, 24 Mbit Flash); old cryptographic protocols are deprecated for all modern backend servers and the connection will be generally denied by the server, typically leading to SIM800L error 605 or 606 when establishing an HTTPS connection. Nevertheless, SIM800C supports TLS 1.2 with recent firmwares and with this device you can use use_ssl=True. No known firmware supports TLS 1.3. Notice that most websites are progressively abandoning TLS 1.2 in favor of TLS 1.3, which offers improved security, performance, and reduced handshake overhead; a device that only supports up to TLS 1.2 risks future incompatibility, as an increasing number of sites will enforce TLS 1.3 exclusively.

Notice also that, depending on the web server, a specific SSL certificate could be needed for a successful HTTPS connection; the SIM800L module has a limited support of SSL certificates and installing an additional one is not straightforfard.

An additional problem is related to possible DNS errors when accessing endpoints. Using IP addresses is preferred.

Example of usage:

from sim800l import SIM800L
sim800l = SIM800L()
sim800l.setup()

print(sim800l.http("httpbin.org/ip", method="GET", apn="..."))

print(sim800l.http("https://www.google.com/", method="GET", apn="...", use_ssl=True))  # Only SIM800C with latest TLS1.2 firmware

internet_sync_time(time_server='193.204.114.232', time_zone_quarter=4, apn=None, http_timeout=10, keep_session=False)

Connect to the bearer, get the IP address and sync the internal RTC with the local time returned by the NTP time server (Network Time Protocol). Automatically perform the full PDP context setup. Disconnect the bearer at the end (unless keep_session = True) Reuse the IP session if an IP address is found active.

  • time_server: internet time server (IP address string)
  • time_zone_quarter: time zone in quarter of hour
  • http_timeout: timeout in seconds
  • keep_session: True to keep the PDP context active at the end return: False if error, otherwise the returned date (datetime.datetime)

Example: "2022-03-09 20:38:09"


get_ip(poll_timeout=4)

Get the IP address of the PDP context

Parameter:

  • poll_timeout: optional poll setting in seconds to wait for the IP address to return as +SAPBR: 1,1,"...".

Returns:

  • valid IP address string if the bearer is connected
  • None: Bearer not connected, no IP address
  • False: Error (e.g., module error)

connect_gprs(apn)

Activates GPRS PDP context.

Parameters:

  • apn (str): APN name for the carrier.

Returns:

  • str: Assigned IP address.
  • False: Connection error.

disconnect_gprs()

Deactivates GPRS PDP context.
Returns:

  • True: Success
  • False: Error

Query Commands

check_sim()

Checks if a SIM card is inserted.

Returns:

  • True: SIM inserted.
  • False: SIM not inserted.
  • None: Module error.

is_registered()

Checks if the SIM is registered on the home network.

Returns:

  • True: Registered.
  • False: Not registered.
  • None: Module error.

get_date()

Retrieves the module's internal clock date.

Returns:

  • datetime.datetime: Current date/time.
  • None: Module error.

get_operator()