### Install python-gammu via pip Source: https://github.com/gammu/python-gammu/blob/master/README.rst Standard command to install the python-gammu package using the Python package manager. ```bash pip install python-gammu ``` -------------------------------- ### Install python-gammu with custom path Source: https://github.com/gammu/python-gammu/blob/master/README.rst Commands to install the package while specifying a custom path for Gammu libraries on Linux and Windows systems. ```bash GAMMU_PATH=/opt/gammu pip install . ``` ```batch SET GAMMU_PATH="C:\Gammu" pip install . ``` -------------------------------- ### Get Phone Information and Status with Python-Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Retrieve phone status information such as battery level, signal quality, and network details using the gammu library. This requires a configured gammu state machine. ```python import gammu state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() # Battery information battery = state_machine.GetBatteryCharge() for key, value in battery.items(): if value != -1: print(f"{key}: {value}") # Signal quality signal = state_machine.GetSignalQuality() print(f"\nSignal Strength: {signal['SignalPercent']}%\n") # Network information netinfo = state_machine.GetNetworkInfo() print(f"Network Code: {netinfo['NetworkCode']}\n") print(f"Network Name: {netinfo['NetworkName']}\n") print(f"State: {netinfo['State']}\n") # Look up network name from database if empty if not netinfo["NetworkName"] and netinfo["NetworkCode"]: if netinfo["NetworkCode"] in gammu.GSMNetworks: print(f"Network (from DB): {gammu.GSMNetworks[netinfo['NetworkCode']]}") ``` -------------------------------- ### Initialize and Configure StateMachine in Python Source: https://context7.com/gammu/python-gammu/llms.txt Demonstrates initializing the StateMachine, reading configuration, connecting to the phone, and retrieving basic phone information using python-gammu. Requires a valid Gammu configuration file (e.g., ~/.gammurc). ```python import gammu # Create the state machine instance state_machine = gammu.StateMachine() # Read configuration from default location (~/.gammurc) state_machine.ReadConfig() # Or read from a specific config file # state_machine.ReadConfig(Filename="/path/to/config") # Connect to the phone state_machine.Init() # Get phone information manufacturer = state_machine.GetManufacturer() model = state_machine.GetModel() imei = state_machine.GetIMEI() firmware = state_machine.GetFirmware() print(f"Manufacturer: {manufacturer}") print(f"Model: {model[0]} ({model[1]})") print(f"IMEI: {imei}") print(f"Firmware: {firmware[0]}") ``` -------------------------------- ### Access gammu help in Python Source: https://github.com/gammu/python-gammu/blob/master/README.rst Demonstrates how to import the gammu module and access its built-in help documentation within an interactive Python session. ```python import gammu help(gammu) ``` -------------------------------- ### Asynchronous Worker (Threading) with Python Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Demonstrates using GammuWorker for asynchronous phone communication in a separate thread. It shows how to set up a callback function, configure the worker, enqueue various commands (single, compound, with parameters), and manage the worker's lifecycle. ```python import gammu import gammu.worker def callback(name, result, error, percent): """Callback executed when a command completes.""" print(f"Command '{name}' completed ({percent}%)") if error != "ERR_NONE": print(f" Error: {error}") else: print(f" Result: {result}") def read_config(): """Read gammu configuration.""" sm = gammu.StateMachine() sm.ReadConfig() return sm.GetConfig() # Create worker with callback worker = gammu.worker.GammuWorker(callback) worker.configure(read_config()) # Queue commands before starting worker.enqueue("GetManufacturer") worker.enqueue("GetIMEI") worker.enqueue("GetModel") # Create compound task (multiple commands as one task) worker.enqueue("GetPhoneInfo", commands=[ "GetBatteryCharge", "GetSignalQuality", ]) # Command with parameters worker.enqueue("GetMemory", ("SM", 1)) # Command with named parameters worker.enqueue("GetSMSC", {"Location": 1}) # Start the worker thread worker.initiate() print("Worker started, commands executing...") # Wait for completion and cleanup worker.terminate() print("Worker terminated") ``` -------------------------------- ### Manage Todo List Tasks with Python-Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Illustrates how to access todo list status and retrieve task details including priority and completion status. ```python import gammu state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() status = state_machine.GetToDoStatus() remain = status["Used"] start = True while remain > 0: if start: entry = state_machine.GetNextToDo(Start=True) start = False else: entry = state_machine.GetNextToDo(Location=entry["Location"]) remain -= 1 ``` -------------------------------- ### Browse Phone File System with Python-Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Navigate and retrieve information about files and folders on the phone's filesystem using the `GetNextFileFolder` method. This method returns details like name, size, type, and attributes. ```python import gammu def get_next_file(state_machine, start=False): """Wrapper to handle end of file list.""" try: return state_machine.GetNextFileFolder(start) except gammu.ERR_EMPTY: return None state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() # List all files and folders file_obj = get_next_file(state_machine, start=True) while file_obj: indent = " " * (file_obj["Level"] - 1) file_type = "Folder" if file_obj["Folder"] else "File" print(f"{indent}{file_type}: {file_obj['Name']}") print(f"{indent} ID: {file_obj['ID_FullName']}") print(f"{indent} Size: {file_obj['Used']} bytes") print(f"{indent} Type: {file_obj['Type']}") if file_obj.get("Modified"): print(f"{indent} Modified: {file_obj['Modified']}") # File attributes attrs = [] if file_obj["Protected"]: attrs.append("Protected") if file_obj["ReadOnly"]: attrs.append("ReadOnly") if file_obj["Hidden"]: attrs.append("Hidden") if attrs: print(f"{indent} Attributes: {', '.join(attrs)}") file_obj = get_next_file(state_machine) ``` -------------------------------- ### Initiate Voice Calls with Python-Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Make voice calls, answer incoming calls, and cancel ongoing calls using the gammu library. This function requires an initialized gammu state machine. ```python import gammu state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() # Dial a voice call try: state_machine.DialVoice("+1234567890") print("Call initiated") except gammu.GSMError as e: print(f"Failed to dial: {e}") # Answer an incoming call (call ID is optional) # state_machine.AnswerCall() # Cancel/end a call (call ID is optional) # state_machine.CancelCall() ``` -------------------------------- ### Manage Calendar Entries with Python-Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Shows how to query the calendar status and iterate through stored calendar events like meetings and reminders. ```python import gammu state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() status = state_machine.GetCalendarStatus() remain = status["Used"] start = True while remain > 0: if start: entry = state_machine.GetNextCalendar(Start=True) start = False else: entry = state_machine.GetNextCalendar(Location=entry["Location"]) remain -= 1 ``` -------------------------------- ### Manage Phonebook Contacts with Python-Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Demonstrates how to retrieve memory status, iterate through existing phonebook contacts, and add new entries to the SIM card memory using the StateMachine class. ```python import gammu state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() # Get memory status for SIM card contacts memory_type = "SM" status = state_machine.GetMemoryStatus(Type=memory_type) remain = status["Used"] # Read all contacts start = True while remain > 0: if start: entry = state_machine.GetNextMemory(Start=True, Type=memory_type) start = False else: entry = state_machine.GetNextMemory(Location=entry["Location"], Type=memory_type) remain -= 1 # Add a new contact new_contact = { "MemoryType": "SM", "Entries": [ {"Type": "Text_Name", "Value": "John Doe"}, {"Type": "Number_Mobile", "Value": "+1234567890"}, ], } location = state_machine.AddMemory(new_contact) ``` -------------------------------- ### Handle Incoming Events with Python-Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Configures callback functions to handle incoming SMS and call notifications, while maintaining a connection to the device. ```python import time import gammu def incoming_callback(state_machine, callback_type, data): if callback_type == "SMS": print(f"New SMS from: {data.get('Number', 'Unknown')}") elif callback_type == "Call": print(f"Incoming call from: {data.get('Number', 'Unknown')}") state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() state_machine.SetIncomingCallback(incoming_callback) state_machine.SetIncomingSMS() state_machine.SetIncomingCall() ``` -------------------------------- ### Asyncio Worker with Python Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Illustrates using GammuAsyncWorker for async/await style phone communication, integrating with Python's asyncio. It covers connecting to the phone, retrieving various phone information asynchronously, sending an SMS, and proper cleanup. ```python import asyncio import gammu import gammu.asyncworker async def main(): # Create async worker worker = gammu.asyncworker.GammuAsyncWorker() # Configure connection config = { "Device": "/dev/ttyUSB0", "Connection": "at" } worker.configure(config) try: # Connect to phone await worker.init_async() print("Connected to phone") # Get phone information (all async) manufacturer = await worker.get_manufacturer_async() print(f"Manufacturer: {manufacturer}") model = await worker.get_model_async() print(f"Model: {model[0]} ({model[1]})") imei = await worker.get_imei_async() print(f"IMEI: {imei}") # Get network info netinfo = await worker.get_network_info_async() print(f"Network: {netinfo['NetworkName']}") print(f"Signal: ", end="") signal = await worker.get_signal_quality_async() print(f"{signal['SignalPercent']}%\n") # Send SMS asynchronously message = { "Text": "Async test message", "SMSC": {"Location": 1}, "Number": "+1234567890", } await worker.send_sms_async(message) print("Message sent!") finally: # Cleanup await worker.terminate_async() print("Disconnected") # Run the async function asyncio.run(main()) ``` -------------------------------- ### Handle Gammu Errors with GSMError in Python Source: https://context7.com/gammu/python-gammu/llms.txt Demonstrates how to catch and handle Gammu-specific errors using the GSMError exception and predefined error codes. This includes handling device connection issues, timeouts, and specific operation failures like reading SMS messages. It also shows how to access the available error codes and their descriptions. ```python import gammu from gammu.exception import GSMError state_machine = gammu.StateMachine() state_machine.ReadConfig() try: state_machine.Init() except gammu.ERR_DEVICENOTEXIST: print("Phone device not found - check connection") except gammu.ERR_DEVICEOPENERROR: print("Cannot open device - check permissions") except gammu.ERR_TIMEOUT: print("Connection timeout - phone not responding") except GSMError as e: print(f"GSM Error: {e}") # Example: Handle specific operation errors try: sms = state_machine.GetNextSMS(Start=True, Folder=0) except gammu.ERR_EMPTY: print("No SMS messages found") except gammu.ERR_NOTSUPPORTED: print("SMS reading not supported by this phone") except gammu.ERR_SECURITYERROR: print("PIN code required") # Access error codes print(f"\nAvailable error codes: {len(gammu.ErrorNumbers)}") print(f"Error descriptions: {len(gammu.Errors)}") ``` -------------------------------- ### Backup and Restore Phone Data with Python-Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Read and write backup files for contacts, calendar, and SMS messages in various formats including vCard, iCalendar, and Gammu's native format. This involves using `ReadBackup`, `SaveBackup`, `ReadSMSBackup`, and `SaveSMSBackup` functions. ```python import gammu # Read a backup file (supports .vcf, .ics, .backup formats) backup = gammu.ReadBackup("contacts.vcf") print(f"Phone phonebook entries: {len(backup.get('PhonePhonebook', []))}") print(f"SIM phonebook entries: {len(backup.get('SIMPhonebook', []))}") print(f"Calendar entries: {len(backup.get('Calendar', []))}") print(f"Todo entries: {len(backup.get('ToDo', []))}") # Convert and save to another format gammu.SaveBackup("contacts_backup.backup", backup) # Read and save SMS backup sms_backup = gammu.ReadSMSBackup("messages.smsbackup") gammu.SaveSMSBackup("messages_copy.smsbackup", sms_backup) # Restore contacts to phone state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() for contact in backup.get("PhonePhonebook", []): contact["MemoryType"] = "ME" # Store in phone memory location = state_machine.AddMemory(contact) print(f"Restored contact to location: {location}") ``` -------------------------------- ### SMSD Integration with Python Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Shows how to use the gammu.smsd wrapper to inject SMS messages into the Gammu SMS daemon queue for background sending. This is useful for reliable message delivery with retry logic. It covers injecting single and multipart messages. ```python import gammu.smsd # Create SMSD instance with config file smsd = gammu.smsd.SMSD("/etc/gammu-smsdrc") # Prepare message message = { "Text": "Message via SMSD daemon", "SMSC": {"Location": 1}, "Number": "+1234567890", } # Inject message into SMSD queue # The daemon will handle actual sending smsd.InjectSMS([message]) print("Message injected into SMSD queue") # For multipart messages, inject all parts smsinfo = { "Class": -1, "Unicode": False, "Entries": [ {"ID": "ConcatenatedTextLong", "Buffer": "A very long message..."} ] } encoded = gammu.EncodeSMS(smsinfo) for part in encoded: part["SMSC"] = {"Location": 1} part["Number"] = "+1234567890" smsd.InjectSMS(encoded) print("Multipart message injected") ``` -------------------------------- ### Read All SMS Messages with python-gammu Source: https://context7.com/gammu/python-gammu/llms.txt Demonstrates how to retrieve all SMS messages from a phone using python-gammu. It utilizes GetSMSStatus to determine the number of messages and GetNextSMS in a loop to iterate through each message, printing its details. ```python import gammu state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() # Get SMS status to know how many messages exist status = state_machine.GetSMSStatus() remain = status["SIMUsed"] + status["PhoneUsed"] + status["TemplatesUsed"] print(f"Total messages: {remain}") start = True try: while remain > 0: if start: sms = state_machine.GetNextSMS(Start=True, Folder=0) start = False else: sms = state_machine.GetNextSMS(Location=sms[0]["Location"], Folder=0) remain -= len(sms) for m in sms: print(f"\nFrom: {m['Number']}") print(f"Date: {m['DateTime']}") print(f"State: {m['State']}") print(f"Text: {m['Text']}") except gammu.ERR_EMPTY: print("Reached end of messages") ``` -------------------------------- ### Send Simple SMS Message with python-gammu Source: https://context7.com/gammu/python-gammu/llms.txt Shows how to send a basic SMS message using the SendSMS method in python-gammu. The message is defined as a dictionary including text, recipient number, and SMSC location. Handles potential GSM errors during sending. ```python import gammu state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() # Prepare a simple SMS message message = { "Text": "Hello from python-gammu!", "SMSC": {"Location": 1}, # Use first stored SMSC "Number": "+1234567890", # Recipient phone number } # Send the message try: state_machine.SendSMS(message) print("Message sent successfully!") except gammu.GSMError as e: print(f"Failed to send message: {e}") ``` -------------------------------- ### Decode PDU Hex String with Python Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Decodes a PDU (Protocol Data Unit) hex string into a readable SMS format using the gammu library. It handles potential decoding errors by catching GSMError. The output includes the sender's number, message text, and timestamp. ```python import gammu pdu_hex = "07911326040000F0040B911346610089F60000208062aborce" pdu_bytes = bytes.fromhex(pdu_hex) try: sms = gammu.DecodePDU(pdu_bytes) print(f"From: {sms.get('Number', 'Unknown')}") print(f"Text: {sms.get('Text', '')}") print(f"Date: {sms.get('DateTime', 'Unknown')}") except gammu.GSMError as e: print(f"Failed to decode PDU: {e}") ``` -------------------------------- ### Send Long (Multipart) SMS with python-gammu Source: https://context7.com/gammu/python-gammu/llms.txt Explains how to send SMS messages longer than 160 characters using python-gammu's EncodeSMS function. The function splits the message into multiple parts for concatenation by the recipient's phone. Each part is then sent individually. ```python import gammu state_machine = gammu.StateMachine() state_machine.ReadConfig() state_machine.Init() # Create SMS info structure for long message smsinfo = { "Class": -1, "Unicode": False, "Entries": [ { "ID": "ConcatenatedTextLong", "Buffer": "This is a very long message that exceeds the standard " "160 character limit for SMS messages. Python-gammu will " "automatically split this into multiple parts that will be " "reassembled on the recipient's phone. This is useful for " "sending detailed notifications or longer content.", } ], } # Encode the long message into multiple SMS parts encoded = gammu.EncodeSMS(smsinfo) # Send each part for message in encoded: message["SMSC"] = {"Location": 1} message["Number"] = "+1234567890" state_machine.SendSMS(message) print(f"Sent part of multipart message") ``` -------------------------------- ### Decode SMS PDU Data with Python-Gammu Source: https://context7.com/gammu/python-gammu/llms.txt Decode raw PDU (Protocol Data Unit) data from SMS messages for debugging or processing. This involves setting debug output to capture PDU details. ```python import gammu import sys # Enable debug output gammu.SetDebugFile(sys.stderr) gammu.SetDebugLevel("textall") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.