Table of Contents
Question content
Solution
Home Backend Development Golang How to get the number of active calls from Asterisk Manager interface events

How to get the number of active calls from Asterisk Manager interface events

Feb 09, 2024 am 11:20 AM

如何从 Asterisk Manager 接口事件获取活动呼叫数量

When using an Asterisk communications system, knowing the number of active calls is important to monitor and manage call traffic. Various event information, including the number of calls, can be obtained through the Asterisk Manager interface. This article will introduce you to the methods and steps on how to use the Asterisk Manager interface to obtain the number of active calls. Whether you are new to Asterisk or an experienced user, this article will provide you with detailed guidance. Let’s take a look!

Question content

I have connected to asterisk and managed to get the number of active and inactive peers from the event peerstatus, but now I need to get the number of active calls and channels and Show them. I've tried looking for channelstatedesc=up but it doesn't work. Even if I put the log, I don't see the event being found. How can I fix it (maybe via event coreshowchannelscomplete?) Thanks in advance

//server.go
package server

import (
    "bufio"
    "fmt"
    "net"
    "strings"

    "data"
)

func connecttoami(address, username, password string) error {
    conn, err := net.dial("tcp", address)
    if err != nil {
        return err
    }
    defer conn.close()

    fmt.fprintf(conn, "action: login\r\nusername: %s\r\nsecret: %s\r\n\r\n", username, password)

    peerstatus := &data.peerstatus{}
    callstatus := &data.callstatus{}

    scanner := bufio.newscanner(conn)
    for scanner.scan() {
        line := scanner.text()
        fmt.println(line)

        if strings.hasprefix(line, "peerstatus") {
            data.getpeerstatus(line, peerstatus)
            fmt.println("active peers:", peerstatus.active)
            fmt.println("inactive peers:", peerstatus.inactive)
        } else if strings.hasprefix(line, "coreshowchannel") {
            data.getchannelstatus(line, callstatus)
            fmt.println("active peers:", peerstatus.active)
            fmt.println("inactive peers:", peerstatus.inactive)
        }

    }

    if err := scanner.err(); err != nil {
        return err
    }

    return nil
}
//calls.go
package data

import (
    "encoding/json"
    "fmt"
    "strings"
)

type CallStatus struct {
    ActiveCalls    int `json:"active_calls"`
    ActiveChannels int `json:"active_channels"`
}

func (cs *CallStatus) UpdateCallStatus(state string) {
    fmt.Println("UpdateCallStatus function", state)

    switch state {
    case "Up":
        cs.ActiveCalls++
        cs.ActiveChannels = cs.ActiveCalls * 2
    case "Down":
        cs.ActiveCalls--
        cs.ActiveChannels=cs.ActiveChannels-2
    default:
    }
}

func GetChannelStatus(event string, callStatus *CallStatus) {
    fmt.Println("GetChannelStatus function", event)
    for _, line := range strings.Split(event, "\r\n") {
        if strings.HasPrefix(line, "ChannelStateDesc: ") {
            state := strings.TrimSpace(strings.TrimPrefix(line, "ChannelStateDesc: "))
            callStatus.UpdateCallStatus(state)
        }
    }
}

Solution

I have figured it out, the code is as follows: //Server.go

parts := strings.split(line, ": ")
    if len(parts) == 2 {
        key := parts[0]
        value := parts[1]

        if key == "event" {
            object.event = value
        }
        if key == "channelstate" {
            object.channelstate = value
        }
        if key == "linkedid" {
            object.linkedid = value
        }
    }
    data.handleevent(object, activecalls)

calls.go

package data

import (
"encoding/json"
"fmt"
)

type Data struct {
Event        string `json:"Event"`
ChannelState string `json:"ChannelState"`
Linkedid     string `json:"Linkedid"`
}

type ActiveCalls struct {
Count int `json:"active_calls"`
}

func HandleEvent(data Data, activeCalls 
*ActiveCalls) {
if data.Event == "Newstate" {
    fmt.Println(data.ChannelState)
    if data.ChannelState == "6" {
        activeCalls.Count++
        fmt.Println("Newstate count active 
calls", activeCalls.Count)
    }
} else if data.Event == "Hangup" {
    fmt.Println(data.ChannelState)
    activeCalls.Count--
    if activeCalls.Count < 0 {
        activeCalls.Count = 0
    }
    fmt.Println("Newstate count active calls after hangup", activeCalls.Count)
}
}

func ActiveCallsToJSON(activeCalls *ActiveCalls) (string, error) {
jsonBytes, err := json.Marshal(activeCalls)
if err != nil {
    return "", err
}
return string(jsonBytes), nil

}

The above is the detailed content of How to get the number of active calls from Asterisk Manager interface events. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

reading from stdin in go by example reading from stdin in go by example Jul 27, 2025 am 04:15 AM

Use fmt.Scanf to read formatted input, suitable for simple structured data, but the string is cut off when encountering spaces; 2. It is recommended to use bufio.Scanner to read line by line, supports multi-line input, EOF detection and pipeline input, and can handle scanning errors; 3. Use io.ReadAll(os.Stdin) to read all inputs at once, suitable for processing large block data or file streams; 4. Real-time key response requires third-party libraries such as golang.org/x/term, and bufio is sufficient for conventional scenarios; practical suggestions: use fmt.Scan for interactive simple input, use bufio.Scanner for line input or pipeline, use io.ReadAll for large block data, and always handle

How does the switch statement work in Go? How does the switch statement work in Go? Jul 30, 2025 am 05:11 AM

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

go by example generics go by example generics Jul 29, 2025 am 04:10 AM

Go generics are supported since 1.18 and are used to write generic code for type-safe. 1. The generic function PrintSlice[Tany](s[]T) can print slices of any type, such as []int or []string. 2. Through type constraint Number limits T to numeric types such as int and float, Sum[TNumber](slice[]T)T safe summation is realized. 3. The generic structure typeBox[Tany]struct{ValueT} can encapsulate any type value and be used with the NewBox[Tany](vT)*Box[T] constructor. 4. Add Set(vT) and Get()T methods to Box[T] without

go by example running a subprocess go by example running a subprocess Aug 06, 2025 am 09:05 AM

Run the child process using the os/exec package, create the command through exec.Command but not execute it immediately; 2. Run the command with .Output() and catch stdout. If the exit code is non-zero, return exec.ExitError; 3. Use .Start() to start the process without blocking, combine with .StdoutPipe() to stream output in real time; 4. Enter data into the process through .StdinPipe(), and after writing, you need to close the pipeline and call .Wait() to wait for the end; 5. Exec.ExitError must be processed to get the exit code and stderr of the failed command to avoid zombie processes.

How do you work with environment variables in Golang? How do you work with environment variables in Golang? Aug 19, 2025 pm 02:06 PM

Goprovidesbuilt-insupportforhandlingenvironmentvariablesviatheospackage,enablingdeveloperstoread,set,andmanageenvironmentdatasecurelyandefficiently.Toreadavariable,useos.Getenv("KEY"),whichreturnsanemptystringifthekeyisnotset,orcombineos.Lo

how to break from a nested loop in go how to break from a nested loop in go Jul 29, 2025 am 01:58 AM

In Go, to break out of nested loops, you should use labeled break statements or return through functions; 1. Use labeled break: Place the tag before the outer loop, such as OuterLoop:for{...}, use breakOuterLoop in the inner loop to directly exit the outer loop; 2. Put the nested loop into the function, and return in advance when the conditions are met, thereby terminating all loops; 3. Avoid using flag variables or goto, the former is lengthy and easy to make mistakes, and the latter is not recommended; the correct way is that the tag must be before the loop rather than after it, which is the idiomatic way to break out of multi-layer loops in Go.

What is the standard project layout for a Go application? What is the standard project layout for a Go application? Aug 02, 2025 pm 02:31 PM

The answer is: Go applications do not have a mandatory project layout, but the community generally adopts a standard structure to improve maintainability and scalability. 1.cmd/ stores the program entrance, each subdirectory corresponds to an executable file, such as cmd/myapp/main.go; 2.internal/ stores private code, cannot be imported by external modules, and is used to encapsulate business logic and services; 3.pkg/ stores publicly reusable libraries for importing other projects; 4.api/ optionally stores OpenAPI, Protobuf and other API definition files; 5.config/, scripts/, and web/ store configuration files, scripts and web resources respectively; 6. The root directory contains go.mod and go.sum

See all articles