huaweimodem

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 19, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

README

Huawei Modem Go Library

The Huawei Modem Go library provides a simple and convenient way to interact with Huawei LTE WiFi routers (MiFi) through a series of HTTP API endpoints. This library enables users to perform various operations, such as logging in, retrieving device status, sending SMS messages, and more.

Features

  • Login and Logout: Authenticate and manage sessions with the modem.
  • Device Status: Retrieve comprehensive status information, including signal strength, battery level, and network status.
  • SMS Management: Send, read, and delete SMS messages.
  • Device Information: Get detailed information about the device.
  • Network and Signal Information: Obtain current network type, signal strength, and more.
  • Control Operations: Reboot the device and manage various settings.

Installation

To install the Huawei Modem Go library, use the following command:

go get github.com/lagarciag/huaweimodem

Usage

Basic Usage Example

Here's a basic example of how to use the library to log in to the modem, get device status, and send an SMS message.

package main

import (
	"fmt"
	"log"
	"net/http"
	device "github.com/lagarciag/huaweimodem"
	"go.uber.org/zap"
)

func main() {
	logger, _ := zap.NewProduction()
	defer logger.Sync()
	sugar := logger.Sugar()

	// Initialize the device
	modem := device.Device{
		l:        sugar,
		client:   &http.Client{},
		deviceIP: "192.168.8.1",
		user:     "admin",
		password: "yourpassword",
	}

	// Login to the modem
	err := modem.Login()
	if err != nil {
		log.Fatalf("Failed to login: %v", err)
	}
	defer modem.Logout()

	// Get device status
	status, err := modem.GetDeviceStatus()
	if err != nil {
		log.Fatalf("Failed to get device status: %v", err)
	}
	fmt.Printf("Device Status: %+v\n", status)

	// Send an SMS
	err = modem.SendSMS("1234567890", "Hello from Go!")
	if err != nil {
		log.Fatalf("Failed to send SMS: %v", err)
	}
	fmt.Println("SMS sent successfully")
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests.

Acknowledgments

Special thanks to the open-source community and contributors.

Documentation

Overview

Package huaweimodem provides a Go library for interacting with Huawei LTE WiFi routers (MiFi) through a series of HTTP API endpoints.

Features

- Login and Logout: Authenticate and manage sessions with the modem. - Device Status: Retrieve comprehensive status information, including signal strength, battery level, and network status. - SMS Management: Send, read, and delete SMS messages. - Device Information: Get detailed information about the device. - Network and Signal Information: Obtain current network type, signal strength, and more. - Control Operations: Reboot the device and manage various settings.

Installation

To install the Huawei Modem Go library, use the following command:

go get github.com/lagarciag/huaweimodem

Index

Constants

View Source
const (
	// UrlLogin is the endpoint to authenticate and login to the Huawei modem.
	UrlLogin = "http://%s/api/user/login"

	// UrlLogout is the endpoint to log out from the Huawei modem.
	UrlLogout = "http://%s/api/user/logout"

	// UrlSesTokInfo is the endpoint to get session and token information.
	UrlSesTokInfo = "http://%s/api/webserver/SesTokInfo"

	// UrlDeviceStatus is the endpoint to retrieve the current status of the device, including signal strength, battery level, and network status.
	UrlDeviceStatus = "http://%s/api/monitoring/status"

	// UrlDeviceInformation is the endpoint to retrieve detailed information about the device, such as device name, serial number, and IMEI.
	UrlDeviceInformation = "http://%s/api/device/information"

	// UrlSMSList is the endpoint to get a list of SMS messages.
	UrlSMSList = "http://%s/api/sms/sms-list"

	// UrlSendSMS is the endpoint to send an SMS message.
	UrlSendSMS = "http://%s/api/sms/send-sms"

	// UrlDeleteSMS is the endpoint to delete an SMS message.
	UrlDeleteSMS = "http://%s/api/sms/delete-sms"

	// UrlSetSMSRead is the endpoint to mark an SMS message as read.
	UrlSetSMSRead = "http://%s/api/sms/set-read"

	// UrlCurrentPLMN is the endpoint to get information about the current network provider (PLMN).
	UrlCurrentPLMN = "http://%s/api/net/current-plmn"

	// UrlConvergedStatus is the endpoint to get the converged status of the modem, including signal and network status.
	UrlConvergedStatus = "http://%s/api/monitoring/converged-status"

	// UrlMonthStatistics is the endpoint to retrieve monthly statistics about data usage.
	UrlMonthStatistics = "http://%s/api/monitoring/month_statistics"

	// UrlStartDate is the endpoint to get the start date of the data monitoring period.
	UrlStartDate = "http://%s/api/monitoring/start_date"

	// UrlHostList is the endpoint to retrieve a list of devices currently connected to the modem via Wi-Fi.
	UrlHostList = "http://%s/api/wlan/host-list"

	// UrlCheckNotifications is the endpoint to check for new notifications, such as unread SMS messages.
	UrlCheckNotifications = "http://%s/api/monitoring/check-notifications"

	// UrlControlDevice is the endpoint to control the device, such as rebooting it.
	UrlControlDevice = "http://%s/api/device/control"

	// UrlGetSysSettings is the endpoint to retrieve system settings.
	UrlGetSysSettings = "http://%s/api/settings/get-sys"

	// UrlSetSysSettings is the endpoint to set or update system settings.
	UrlSetSysSettings = "http://%s/api/settings/set-sys"

	// UrlDHCPSettings is the endpoint to retrieve or update DHCP settings.
	UrlDHCPSettings = "http://%s/api/dhcp/settings"

	// UrlFirewallSwitch is the endpoint to enable or disable the firewall.
	UrlFirewallSwitch = "http://%s/api/security/firewall-switch"
)

List of API endpoints discovered so far, not all of them are implemented

Variables

This section is empty.

Functions

This section is empty.

Types

type DeleteSMSRequest

type DeleteSMSRequest struct {
	XMLName xml.Name `xml:"request"`
	Index   int      `xml:"Index"`
}

DeleteSMSRequest represents the XML request to delete an SMS message.

type DeleteSMSResponse

type DeleteSMSResponse struct {
	XMLName xml.Name `xml:"response"`
	Result  string   `xml:"result"`
}

DeleteSMSResponse represents the XML response after deleting an SMS message.

type Device

type Device struct {
	// contains filtered or unexported fields
}

Device represents the device information and authentication details.

func NewDevice

func NewDevice(l *zap.SugaredLogger, deviceIP, user, password string) (*Device, error)

NewDevice creates a new instance of Device with the specified logger, device IP, username, and password. It initializes the Device struct and sets up an HTTP client with a cookie jar to manage session cookies.

Parameters:

  • l: A SugaredLogger instance from the zap logging package.
  • deviceIP: The IP address of the device to connect to.
  • user: The username for authentication.
  • password: The password for authentication.

Returns:

  • A pointer to the initialized Device instance.
  • An error if the device could not be created.

func (*Device) DeleteSMSWithIndex

func (d *Device) DeleteSMSWithIndex(index int) error

DeleteSMSWithIndex deletes an SMS message with the specified index from the inbox. It first checks if the user is logged in by verifying the sessionID. If not logged in, it returns an error. Then it reads the SMS inbox to ensure the message with the given index exists. If the message exists, it sends a request to the delete SMS endpoint to remove the message.

Parameters:

  • index: The index of the SMS message to be deleted.

Returns:

  • An error if any step in the process fails.

func (*Device) DeviceIP

func (d *Device) DeviceIP() string

DeviceIP returns the IP address of the device.

func (*Device) DeviceStatus

func (d *Device) DeviceStatus() (*DeviceStatus, error)

DeviceStatus retrieves the status of the device, including signal strength and battery level. It first checks if the user is logged in by verifying the sessionID. If not logged in, it returns an error. Then it refreshes the session and token information, and sends a request to the device status endpoint. The response is parsed and unmarshalled into a DeviceStatus struct, which is returned.

Returns:

  • A pointer to the DeviceStatus struct containing the device status.
  • An error if any step in the process fails.

func (*Device) Login

func (d *Device) Login() (err error)

Login authenticates with the device by obtaining session and token information, hashing the combined token, and sending a login request.

func (*Device) ReadSMSInbox

func (d *Device) ReadSMSInbox() (*SMSList, error)

ReadSMSInbox retrieves the SMS messages from the device's inbox. It first checks if the user is logged in by verifying the sessionID. If not logged in, it returns an error. Then it refreshes the session and token information, and sends a request to the SMS list endpoint. The response is parsed and unmarshaled into an SMSList struct, which is returned.

Returns:

  • A pointer to the SMSList struct containing the SMS messages.
  • An error if any step in the process fails.

func (*Device) SendSMS

func (d *Device) SendSMS(phoneNumber, message string) error

SendSMS sends an SMS message to the specified phone number. It first checks if the user is logged in by verifying the sessionID. If not logged in, it returns an error. Then it refreshes the session and token information, constructs the SMS message, and sends it to the SMS send endpoint.

Parameters:

  • phoneNumber: The phone number to send the SMS to.
  • message: The message content to be sent.

Returns:

  • An error if any step in the process fails.

func (*Device) User

func (d *Device) User() string

User returns the username used to authenticate with the device.

type DeviceStatus

type DeviceStatus struct {
	XMLName              xml.Name `xml:"response"`             // XMLName is the XML element name for the response.
	WifiConnectionStatus int      `xml:"WifiConnectionStatus"` // WifiConnectionStatus indicates the current Wi-Fi connection status.
	SignalStrength       int      `xml:"SignalStrength"`       // SignalStrength represents the strength of the signal.
	SignalIcon           int      `xml:"SignalIcon"`           // SignalIcon provides a visual representation of signal strength.
	CurrentNetworkType   int      `xml:"CurrentNetworkType"`   // CurrentNetworkType indicates the type of the current network.
	CurrentServiceDomain int      `xml:"CurrentServiceDomain"` // CurrentServiceDomain indicates the current service domain.
	RoamingStatus        int      `xml:"RoamingStatus"`        // RoamingStatus indicates if the device is roaming.
	BatteryStatus        int      `xml:"BatteryStatus"`        // BatteryStatus indicates the status of the battery.
	BatteryLevel         int      `xml:"BatteryLevel"`         // BatteryLevel represents the battery level.
	BatteryPercent       int      `xml:"BatteryPercent"`       // BatteryPercent indicates the battery percentage.
	SimlockStatus        int      `xml:"simlockStatus"`        // SimlockStatus indicates if the SIM is locked.
	WanIPAddress         string   `xml:"WanIPAddress"`         // WanIPAddress is the WAN IP address of the device.
	WanIPv6Address       string   `xml:"WanIPv6Address"`       // WanIPv6Address is the WAN IPv6 address of the device.
	PrimaryDns           string   `xml:"PrimaryDns"`           // PrimaryDns is the primary DNS address.
	SecondaryDns         string   `xml:"SecondaryDns"`         // SecondaryDns is the secondary DNS address.
	PrimaryIPv6Dns       string   `xml:"PrimaryIPv6Dns"`       // PrimaryIPv6Dns is the primary IPv6 DNS address.
	SecondaryIPv6Dns     string   `xml:"SecondaryIPv6Dns"`     // SecondaryIPv6Dns is the secondary IPv6 DNS address.
	CurrentWifiUser      int      `xml:"CurrentWifiUser"`      // CurrentWifiUser is the number of current Wi-Fi users.
	TotalWifiUser        int      `xml:"TotalWifiUser"`        // TotalWifiUser is the total number of Wi-Fi users.
	CurrentTotalWifiUser int      `xml:"currenttotalwifiuser"` // CurrentTotalWifiUser is the current total number of Wi-Fi users.
	ServiceStatus        int      `xml:"ServiceStatus"`        // ServiceStatus indicates the status of the service.
	SimStatus            int      `xml:"SimStatus"`            // SimStatus indicates the status of the SIM card.
	WifiStatus           int      `xml:"WifiStatus"`           // WifiStatus indicates the status of the Wi-Fi.
	CurrentNetworkTypeEx int      `xml:"CurrentNetworkTypeEx"` // CurrentNetworkTypeEx indicates the extended current network type.
	WanPolicy            int      `xml:"WanPolicy"`            // WanPolicy indicates the WAN policy.
	MaxSignal            int      `xml:"maxsignal"`            // MaxSignal indicates the maximum signal strength.
	WifiIndoorOnly       int      `xml:"wifiindooronly"`       // WifiIndoorOnly indicates if the Wi-Fi is for indoor use only.
	WifiFrequence        int      `xml:"wififrequence"`        // WifiFrequence indicates the frequency of the Wi-Fi.
	Classify             string   `xml:"classify"`             // Classify indicates the classification of the device.
	FlyMode              int      `xml:"flymode"`              // FlyMode indicates if the device is in flight mode.
	CellRoam             int      `xml:"cellroam"`             // CellRoam indicates if the device is in cell roaming mode.
}

DeviceStatus represents the status of the device, including signal strength and battery level.

func (*DeviceStatus) GetBatteryLevel

func (d *DeviceStatus) GetBatteryLevel() int

GetBatteryLevel returns the battery level.

func (*DeviceStatus) GetBatteryPercent

func (d *DeviceStatus) GetBatteryPercent() int

GetBatteryPercent returns the battery percentage.

func (*DeviceStatus) GetBatteryStatus

func (d *DeviceStatus) GetBatteryStatus() int

GetBatteryStatus returns the battery status.

func (*DeviceStatus) GetCellRoam

func (d *DeviceStatus) GetCellRoam() int

GetCellRoam returns whether the device is in cell roaming mode.

func (*DeviceStatus) GetClassify

func (d *DeviceStatus) GetClassify() string

GetClassify returns the classification of the device.

func (*DeviceStatus) GetCurrentNetworkType

func (d *DeviceStatus) GetCurrentNetworkType() int

GetCurrentNetworkType returns the current network type.

func (*DeviceStatus) GetCurrentNetworkTypeEx

func (d *DeviceStatus) GetCurrentNetworkTypeEx() int

GetCurrentNetworkTypeEx returns the extended current network type.

func (*DeviceStatus) GetCurrentServiceDomain

func (d *DeviceStatus) GetCurrentServiceDomain() int

GetCurrentServiceDomain returns the current service domain.

func (*DeviceStatus) GetCurrentTotalWifiUser

func (d *DeviceStatus) GetCurrentTotalWifiUser() int

GetCurrentTotalWifiUser returns the current total number of Wi-Fi users.

func (*DeviceStatus) GetCurrentWifiUser

func (d *DeviceStatus) GetCurrentWifiUser() int

GetCurrentWifiUser returns the number of current Wi-Fi users.

func (*DeviceStatus) GetFlyMode

func (d *DeviceStatus) GetFlyMode() int

GetFlyMode returns whether the device is in flight mode.

func (*DeviceStatus) GetMaxSignal

func (d *DeviceStatus) GetMaxSignal() int

GetMaxSignal returns the maximum signal strength.

func (*DeviceStatus) GetPrimaryDns

func (d *DeviceStatus) GetPrimaryDns() string

GetPrimaryDns returns the primary DNS address.

func (*DeviceStatus) GetPrimaryIPv6Dns

func (d *DeviceStatus) GetPrimaryIPv6Dns() string

GetPrimaryIPv6Dns returns the primary IPv6 DNS address.

func (*DeviceStatus) GetRoamingStatus

func (d *DeviceStatus) GetRoamingStatus() int

GetRoamingStatus returns the roaming status.

func (*DeviceStatus) GetSecondaryDns

func (d *DeviceStatus) GetSecondaryDns() string

GetSecondaryDns returns the secondary DNS address.

func (*DeviceStatus) GetSecondaryIPv6Dns

func (d *DeviceStatus) GetSecondaryIPv6Dns() string

GetSecondaryIPv6Dns returns the secondary IPv6 DNS address.

func (*DeviceStatus) GetServiceStatus

func (d *DeviceStatus) GetServiceStatus() int

GetServiceStatus returns the service status.

func (*DeviceStatus) GetSignalIcon

func (d *DeviceStatus) GetSignalIcon() int

GetSignalIcon returns the signal icon.

func (*DeviceStatus) GetSignalStrength

func (d *DeviceStatus) GetSignalStrength() int

GetSignalStrength returns the signal strength.

func (*DeviceStatus) GetSimStatus

func (d *DeviceStatus) GetSimStatus() int

GetSimStatus returns the SIM status.

func (*DeviceStatus) GetSimlockStatus

func (d *DeviceStatus) GetSimlockStatus() int

GetSimlockStatus returns the SIM lock status.

func (*DeviceStatus) GetTotalWifiUser

func (d *DeviceStatus) GetTotalWifiUser() int

GetTotalWifiUser returns the total number of Wi-Fi users.

func (*DeviceStatus) GetWanIPAddress

func (d *DeviceStatus) GetWanIPAddress() string

GetWanIPAddress returns the WAN IP address.

func (*DeviceStatus) GetWanIPv6Address

func (d *DeviceStatus) GetWanIPv6Address() string

GetWanIPv6Address returns the WAN IPv6 address.

func (*DeviceStatus) GetWanPolicy

func (d *DeviceStatus) GetWanPolicy() int

GetWanPolicy returns the WAN policy.

func (*DeviceStatus) GetWifiConnectionStatus

func (d *DeviceStatus) GetWifiConnectionStatus() int

GetWifiConnectionStatus returns the Wi-Fi connection status.

func (*DeviceStatus) GetWifiFrequence

func (d *DeviceStatus) GetWifiFrequence() int

GetWifiFrequence returns the Wi-Fi frequency.

func (*DeviceStatus) GetWifiIndoorOnly

func (d *DeviceStatus) GetWifiIndoorOnly() int

GetWifiIndoorOnly returns whether the Wi-Fi is for indoor use only.

func (*DeviceStatus) GetWifiStatus

func (d *DeviceStatus) GetWifiStatus() int

GetWifiStatus returns the Wi-Fi status.

type ErrorResponse

type ErrorResponse struct {
	XMLName   xml.Name `xml:"error"`   // XMLName is the XML element name for the error.
	ErrorCode string   `xml:"code"`    // ErrorCode is the code returned by the API, indicating the type of error.
	Message   string   `xml:"message"` // Message is the error message returned by the API.
}

ErrorResponse represents a generic error response from the API.

type Phones

type Phones struct {
	Phone []string `xml:"Phone"` // Phone is a list of phone numbers.
}

Phones represents a list of phone numbers for the SMS.

type SMS

type SMS struct {
	XMLName  xml.Name `xml:"request"`  // XMLName is the XML element name for the request.
	Index    int      `xml:"Index"`    // Index is the message index, typically set to -1 for new messages.
	Phones   Phones   `xml:"Phones"`   // Phones contains a list of phone numbers to send the SMS to.
	Content  string   `xml:"Content"`  // Content is the text content of the SMS.
	Length   int      `xml:"Length"`   // Length is the length of the SMS content.
	Reserved int      `xml:"Reserved"` // Reserved is a reserved field, often set to 1.
	Date     string   `xml:"Date"`     // Date is the date the SMS is sent.
}

SMS represents the structure of an SMS request to be sent.

type SMSList

type SMSList struct {
	XMLName  xml.Name     `xml:"response"`         // XMLName is the XML element name for the response.
	Messages []SMSMessage `xml:"Messages>Message"` // Messages is a list of SMS messages.
}

SMSList represents the list of SMS messages retrieved from the device.

type SMSMessage

type SMSMessage struct {
	XMLName xml.Name `xml:"Message"` // XMLName is the XML element name for the message.
	Index   int      `xml:"Index"`   // Index is the index of the message.
	Phone   string   `xml:"Phone"`   // Phone is the phone number the message was sent from or to.
	Content string   `xml:"Content"` // Content is the content of the message.
	Date    string   `xml:"Date"`    // Date is the date the message was sent or received.
}

SMSMessage represents a single SMS message.

type SMSResponse

type SMSResponse struct {
	XMLName   xml.Name `xml:"response"` // XMLName is the XML element name for the response.
	ErrorCode string   `xml:"code"`     // ErrorCode is the code returned by the API, indicating success or error.
	Message   string   `xml:"message"`  // Message is the message returned by the API, typically empty on success.
}

SMSResponse represents the response received after sending an SMS.

type SesTokInfo

type SesTokInfo struct {
	XMLName xml.Name `xml:"response"` // XMLName is the XML element name for the response.
	SesInfo string   `xml:"SesInfo"`  // SesInfo is the session information.
	TokInfo string   `xml:"TokInfo"`  // TokInfo is the token information.
}

SesTokInfo represents the session and token information required for authentication.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL