GO - Asterisk AMI Interface

Overview

GAMI

GO - Asterisk AMI Interface

communicate with the Asterisk AMI, Actions and Events.

Example connecting to Asterisk and Send Action get Events.

package main
import (
	"log"
	"github.com/bit4bit/gami"
	"github.com/bit4bit/gami/event"
	"time"
)

func main() {
	ami, err := gami.Dial("127.0.0.1:5038")
	if err != nil {
		log.Fatal(err)
	}
	ami.Run()
	defer ami.Close()
	
	//install manager
	go func() {
		for {
			select {
			//handle network errors
			case err := <-ami.NetError:
				log.Println("Network Error:", err)
				//try new connection every second
				<-time.After(time.Second)
				if err := ami.Reconnect(); err == nil {
					//call start actions
					ami.Action("Events", gami.Params{"EventMask": "on"})
				}
				
			case err := <-ami.Error:
				log.Println("error:", err)
			//wait events and process
			case ev := <-ami.Events:
				log.Println("Event Detect: %v", *ev)
				//if want type of events
				log.Println("EventType:", event.New(ev))
			}
		}
	}()
	
	if err := ami.Login("admin", "root"); err != nil {
		log.Fatal(err)
	}
	
	
	if _, errPing := ami.Action("Ping", nil); errPing != nil {
		log.Fatal(errPing)
	}
	
	//async actions
	rsPing, rsErr := ami.AsyncAction("Ping", gami.Params{"ActionID": "pingo"})
	if rsErr != nil {
		log.Fatal(rsErr)
	}
						
	if _, err := ami.Action("Events", gami.Params{"EventMask":"on"}); err != nil {
		log.Fatal(err)
	}
	
	log.Println("ping:", <-rsPing)
	

}

###TLS SUPPORT In order to use TLS connection to manager interface you could Dial with additional parameters

//without TLS
ami, err := gami.Dial("127.0.0.1:5038")

//if certificate is trusted
ami, err := gami.Dial("127.0.0.1:5039", gami.UseTLS)

//if self signed certificate
ami, err := gami.Dial("127.0.0.1:5039", gami.UseTLS, gami.UnsecureTLS)

//if custom tls configuration
ami, err := gami.Dial("127.0.0.1:5039", gami.UseTLSConfig(&tls.Config{}))

WARNING: Only Asterisk >=1.6 supports TLS connection to AMI and it needs additional configuration(follow the Asterisk AMI configuration documentation)

CURRENT EVENT TYPES

The events use documentation and struct from PAMI.

use bit4bit/gami/event.New() for get this struct from raw event

EVENT ID TYPE TEST
Newchannel YES
Newexten YES
Newstate YES
Dial YES
ExtensionStatus YES
Hangup YES
PeerStatus YES
PeerEntry YES
VarSet YES
AgentLogin YES
Agents YES
AgentLogoff YES
AgentConnect YES
RTPReceiverStats YES
RTPSenderStats YES
Bridge YES
You might also like...
dont-interface calculates how many interface{} are declared or used in your project?

dont-interface calculates how many interface{} are declared or used in your project?

Go library to interface with NEAR nodes' JSON-RPC interface

StreamingFast Solana library for Go Go library to interface with NEAR nodes' JSON-RPC interface Contributing Issues and PR in this repo related strict

Recursively searches a map[string]interface{} structure for another map[string]interface{} structure

msirecurse Recursively searches a map[string]interface{} structure for existence of a map[string]interface{} structure Motivation I wrote this package

s3fs provides a S3 implementation for Go1.16 filesystem interface.

S3 FileSystem (fs.FS) implementation.Since S3 is a flat structure, s3fs simulates directories by using prefixes and "/" delim. ModTime on directories is always zero value.

A simple logging interface that supports cross-platform color and concurrency.
A simple logging interface that supports cross-platform color and concurrency.

WLog Package wlog creates simple to use UI structure. The UI is used to simply print to the screen. There a wrappers that will wrap each other to crea

Go language interface to Swift / Openstack Object Storage / Rackspace cloud files (golang)

Swift This package provides an easy to use library for interfacing with Swift / Openstack Object Storage / Rackspace cloud files from the Go Language

An in-memory string-interface{} map with various expiration options for golang

TTLCache - an in-memory cache with expiration TTLCache is a simple key/value cache in golang with the following functions: Expiration of items based o

Decode / encode XML to/from map[string]interface{} (or JSON); extract values with dot-notation paths and wildcards. Replaces x2j and j2x packages.

mxj - to/from maps, XML and JSON Decode/encode XML to/from map[string]interface{} (or JSON) values, and extract/modify values from maps by key or key-

Kivik provides a common interface to CouchDB or CouchDB-like databases for Go and GopherJS.

Kivik Package kivik provides a common interface to CouchDB or CouchDB-like databases. The kivik package must be used in conjunction with a database dr

beedb is a go ORM,support database/sql interface,pq/mysql/sqlite

Beedb ❗ IMPORTANT: Beedb is being deprecated in favor of Beego.orm ❗ Beedb is an ORM for Go. It lets you map Go structs to tables in a database. It's

The gofinder program is an acme user interface to search through Go projects.

The gofinder program is an acme user interface to search through Go projects.

An implementation of the FileSystem interface for tar files.

TarFS A wrapper around tar.Reader. Implements the FileSystem interface for tar files. Adds an Open method, that enables reading of file according to i

Protobuf3 with Interface support - Designed for blockchains (deterministic, upgradeable, fast, and compact)

Amino Spec (and impl for Go) This software implements Go bindings for the Amino encoding protocol. Amino is an object encoding specification. It is a

Payment abstraction library - one interface for multiple payment processors ( inspired by Ruby's ActiveMerchant )

Sleet Payment abstraction library - interact with different Payment Service Providers (PsP) with one unified interface. Installation go get github.com

Go bindings for libVLC and high-level media player interface
Go bindings for libVLC and high-level media player interface

Go bindings for libVLC 2.X/3.X/4.X and high-level media player interface. The package can be useful for adding multimedia capabilities to applications

Native Go (golang) Graphical Interface system (2D and 3D), built on GoKi tree framework
Native Go (golang) Graphical Interface system (2D and 3D), built on GoKi tree framework

GoGi is part of the GoKi Go language (golang) full strength tree structure system (ki = 木 = tree in Japanese) package gi is a scenegraph-based 2D and

efaceconv - Code generation tool for high performance conversion from interface{} to immutable type without allocations.

efaceconv High performance conversion from interface{} to immutable types without additional allocations This is tool for go generate and common lib (

⚡ Rux is an simple and fast web framework. support middleware, compatible http.Handler interface. 简单且快速的 Go web 框架,支持中间件,兼容 http.Handler 接口

Rux Simple and fast web framework for build golang HTTP applications. NOTICE: v1.3.x is not fully compatible with v1.2.x version Fast route match, sup

gNXI Tools - gRPC Network Management/Operations Interface Tools

gNxI Tools gNMI - gRPC Network Management Interface gNOI - gRPC Network Operations Interface A collection of tools for Network Management that use the

Comments
  • Generate Random action ID. fix ActionID check

    Generate Random action ID. fix ActionID check

    Hi,

    We have noted that after sending a couple AsyncAction requests, the main goroutine stops receiving and processing new events. This could be caused by ActionID being statically set to 'gamigeneral' We have added some randomness to it. We also think that sending actions line by line may cause some problems when you have multiple processes sending request in the same socket. The patch I provided is grouping those and sending in one packet. sending it line by line isn't also as much efficient as sending grouped ones. The check for empty ActionID does not look right and I think it didn't work as expected.

    I also spotted that if have have two separate connection handlers, one only receiving events and the other sending actions, at some point the one receiving events stops doing it. This may be caused by some variables being shared between instances but we were unable to fix it yet.

    csiwek @Nexmo

    opened by csiwek 2
  • add TLS support and some refactoring

    add TLS support and some refactoring

    as of asterisk >= 1.6, manager interface supports TLS.

    With this PR it is possible to use it.

    //without TLS
    ami, err := gami.Dial("127.0.0.1:5038")
    
    //if certificate is trusted
    ami, err := gami.Dial("127.0.0.1:5039", gami.UseTLS)
    
    //if self signed certificate
    ami, err := gami.Dial("127.0.0.1:5039", gami.UseTLS, gami.UnsecureTLS)
    
    opened by AnatoliiD 2
  • Data race when concurrently accessing client.response map in notifyResponse func.

    Data race when concurrently accessing client.response map in notifyResponse func.

    Hello, data race conditions were detected when concurrently performing actions, presumably, due to read locks in notifyResponse method, which not only performs read ops but also a write operation on the map (delete). Would you consider fixing this (e.g. using a full lock instead or something)? Thanks.

    `================== WARNING: DATA RACE Read at 0x00c42001b740 by goroutine 62: runtime.mapaccess1_faststr() /usr/local/go/src/runtime/hashmap_fast.go:192 +0x0 github.com/bit4bit/gami.(*AMIClient).notifyResponse.func1() .../src/github.com/bit4bit/gami/gami.go:273 +0xb9

    Previous write at 0x00c42001b740 by goroutine 95: runtime.mapdelete() /usr/local/go/src/runtime/hashmap.go:558 +0x0 github.com/bit4bit/gami.(*AMIClient).notifyResponse.func1() .../src/github.com/bit4bit/gami/gami.go:275 +0x1b3

    Goroutine 62 (running) created at: github.com/bit4bit/gami.(*AMIClient).notifyResponse() .../src/github.com/bit4bit/gami/gami.go:277 +0x56 github.com/bit4bit/gami.(*AMIClient).Run.func1() .../src/github.com/bit4bit/gami/gami.go:257 +0x3c4

    Goroutine 95 (finished) created at: github.com/bit4bit/gami.(*AMIClient).notifyResponse() .../src/github.com/bit4bit/gami/gami.go:277 +0x56 github.com/bit4bit/gami.(*AMIClient).Run.func1() .../src/github.com/bit4bit/gami/gami.go:257 +0x3c4 ==================`

    opened by gborisov 1
  • Reconnect not working properly

    Reconnect not working properly

    Hello,

    thank you for the AMI Adapter, it's great work. Though it seems that there are two small issues with the reconnect machanism you provide. Please have a look at the following code snippets. I commented two lines with '!!!!!'

    it seems that your reconnect does not work properly as there is a race condition in your example code:

    func (client *AMIClient) Reconnect() error { client.conn.Close() reconnect, err := Dial(client.address)

    if err != nil {
        //client.NetError <- err  <--- !!!!!! Do not pass the error to the channel, because it blocks
        return err
    }
    
    //new connection
    client.conn = reconnect.conn
    client.connRaw = reconnect.connRaw
    client.waitNewConnection <- struct{}{}
    
    if err := client.Login(client.amiUser, client.amiPass); err != nil {
        return err
    }
    
    return nil
    

    }

    //install manager go func() { for { select { //handle network errors case err := <-ami.NetError: log.Println("Network Error:", err) //try new connection every second for { <-time.After(time.Second) if err := ami.Reconnect(); err == nil { //call start actions if _, err := ami.Action("Events", gami.Params{"EventMask": "on"}); err != nil { // <--- !!!!!! This should break if 'err == nil' --> Seems to be a typo break } } }

            case err := <-ami.Error:
                log.Println("error:", err)
            //wait events and process
            case ev := <-ami.Events:
                log.Println("Event Detect: %v", *ev)
                //if want type of events
                log.Println("EventType:", event.New(ev))
            }
        }
    }()
    

    Regards, Marko

    opened by markose 1
go-whatsapp-rest-API is a Go library for the WhatsApp web which use Swagger as api interface

go-whatsapp-rest-API go-whatsapp-rest-API is a Go library for the WhatsApp web which use Swagger as api interface Multi-devices (MD) Support. This ver

null 17 Nov 30, 2022
Utilcanvas is a package which provides some utilities to interface with the Canvas LMS Api.

Utilcanvas Utilcanvas is a package which provides some utilities to interface with the Canvas LMS Api. Example usage c := utilcanvas.NewClient("https:

Martín Zamorano 0 Oct 22, 2021
This package provides a Go interface for the Typeform API.

typeform This package provides a Go interface for the Typeform API

Roopesh V S 2 Dec 1, 2021
Go library to interface with Solana JSON RPC and WebSocket interfaces

Solana SDK library for Go Go library to interface with Solana JSON RPC and WebSocket interfaces. Clients for Solana native programs, Solana Program Li

Dev Expert 1 Mar 2, 2022
Command line interface to windows clipboard over KiTTY remote-control printing

kclip Command line interface to windows clipboard over KiTTY remote-control printing About This tool behaves like the cat command, it just tries to pa

Jacob Alberty 0 Dec 12, 2021
Package rhymen/go-whatsapp implements the WhatsApp Web API to provide a clean interface for developers

go-whatsapp Package rhymen/go-whatsapp implements the WhatsApp Web API to provide a clean interface for developers. Big thanks to all contributors of

Relldev メイ 3 Mar 19, 2022
gRPC Network Management Interface

gNMI - gRPC Network Management Interface This repository contains reference Go implementations for gNMI. Note: This is not an official Google product.

OpenConfig 367 Nov 29, 2022
Invidtui - An invidious client, which fetches data from invidious and displays a user interface in the terminal(TUI)

invidtui invidtui is an invidious client, which fetches data from invidious and

null 79 Nov 17, 2022
Turn asterisk-indented text lines into mind maps

Crumbs Turn asterisk-indented text lines into mind maps. Organize your notes in a hierarchical tree structure, using a simple text editor. an asterisk

Luca Sepe 98 Dec 4, 2022
Package GoEagi provides some fundamental functionalities that work with Asterisk's EAGI

GoEagi Package GoEagi provides some fundamental functionalities that work with Asterisk's EAGI. It has the following features: Audio Streaming Google'

null 5 Sep 9, 2022