maa

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2024 License: LGPL-3.0 Imports: 2 Imported by: 1

README

LOGO

MaaFramework Golang Binding

This is the Go binding for MaaFramework, providing Go developers with a simple and effective way to use MaaFramework's features within their Go applications. Currently, the Go binding is quite rudimentary and closely mirrors the C interface. Future updates will include significant revisions to improve usability and functionality.

Installation

To install the MaaFramework Go binding, run the following command in your terminal:

go get github.com/MaaXYZ/maa-framework-go

Platform-Specific Notes

Windows

On Windows, the default location for MaaFramework is C:\maa. Ensure that MaaFramework is installed in this directory for the binding to work out of the box.

Linux and macOS

On Linux and macOS, you will need to create a pkg-config file named maa.pc. This file should correctly point to the locations of the MaaFramework headers and libraries. Place this file in a directory where pkg-config can find it (e.g., /usr/local/lib/pkgconfig).

A sample maa.pc file might look like this:

prefix=/path/to/maafw
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include

Name: MaaFramework
Description: MaaFramework library
Version: 1.0
Libs: -L${libdir} -lMaaFramework -lMaaToolkit
Cflags: -I${includedir}

Custom Installation Path

If you need to specify a custom installation path for MaaFramework, you can disable the default location using the -tags customenv build tag. Then, set the necessary environment variables CGO_CFLAGS and CGO_LDFLAGS.

go build -tags customenv

Set the environment variables as follows:

export CGO_CFLAGS="-I[path to maafw include directory]"
export CGO_LDFLAGS="-L[path to maafw lib directory] -lMaaFramework -lMaaToolkit"

Replace [path to maafw include directory] with the actual path to the MaaFramework include directory and [path to maafw lib directory] with the actual path to the MaaFramework library directory.

Usage

To use MaaFramework in your Go project, import the package as you would with any other Go package:

import "github.com/MaaXYZ/maa-framework-go"

Then, you can use the functionalities provided by MaaFramework. For detailed usage, refer to the examples and documentation provided in the repository.

Examples

Here is a basic example to get you started:

package main

import (
	"fmt"
	"github.com/MaaXYZ/maa-framework-go"
	"github.com/MaaXYZ/maa-framework-go/toolkit"
)

func main() {
	toolkit.InitOption("./", "{}")

	res := maa.NewResource(nil)
	defer res.Destroy()
	resId := res.PostPath("sample/resource")
	res.Wait(resId)

	devices := toolkit.AdbDevices()
	if len(devices) == 0 {
		fmt.Println("No Adb device found.")
		return
	}

	device := devices[0]
	ctrl := maa.NewAdbController(
		device.AdbPath,
		device.Address,
		device.ControllerType,
		device.Config,
		"sample/MaaAgentBinary",
		nil,
	)
	defer ctrl.Destroy()
	ctrlId := ctrl.PostConnect()
	ctrl.Wait(ctrlId)

	inst := maa.New(nil)
	defer inst.Destroy()

	inst.BindResource(res)
	inst.BindController(ctrl)

	inst.RegisterCustomRecognizer("MyRec", NewMyRec())
	inst.RegisterCustomAction("MyAct", NewMyAct())

	if !inst.Inited() {
		panic("Failed to init Maa Instance.")
	}

	taskId := inst.PostTask("TaskA", "{}")
	inst.WaitTask(taskId)
}

type MyRec struct {
	maa.CustomRecognizerHandler
}

func NewMyRec() MyRec {
	return MyRec{
		CustomRecognizerHandler: maa.NewCustomRecognizerHandler(),
	}
}

func (MyRec) Analyze(
	syncCtx maa.SyncContext,
	image maa.ImageBuffer,
	taskName string,
	customRecognitionParam string,
) (maa.AnalyzeResult, bool) {
	outBox := maa.NewRect()
	outBox.Set(0, 0, 100, 100)
	return maa.AnalyzeResult{
		Box:    outBox,
		Detail: "Hello world.",
	}, true
}

type MyAct struct {
	maa.CustomActionHandler
}

func NewMyAct() MyAct {
	return MyAct{
		CustomActionHandler: maa.NewCustomActionHandler(),
	}
}

func (MyAct) Run(
	ctx maa.SyncContext,
	taskName string,
	customActionParam string,
	curBox maa.RectBuffer,
	curRecDetail string,
) bool {
	return true
}

func (MyAct) Stop() {
}

Documentation

Currently, there is no detailed documentation available. Please refer to the source code and compare it with the interfaces in the original MaaFramework project to understand how to use the bindings. We are actively working on adding more comments and documentation to the source code.

Contributing

We welcome contributions to the MaaFramework Go binding. If you find a bug or have a feature request, please open an issue on the GitHub repository. If you want to contribute code, feel free to fork the repository and submit a pull request.

License

This project is licensed under the LGPL-3.0 License. See the LICENSE file for details.

Discussion

QQ Group: 595990173

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Click

func Click(syncCtx SyncContext, x, y int32) bool

func FrameworkVersion

func FrameworkVersion() string

func InputText

func InputText(syncCtx SyncContext, text string) bool

func PressKey

func PressKey(syncCtx SyncContext, keycode int32) bool

func RunAction

func RunAction(syncCtx SyncContext, taskName, taskParam string, curBox RectBuffer, curRecDetail string) bool

func RunRecognition

func RunRecognition(syncCtx SyncContext, image ImageBuffer, taskName, taskParam string) (RectBuffer, StringBuffer, bool)

func RunTask

func RunTask(syncCtx SyncContext, taskName, param string) bool

func SetDebugMessage

func SetDebugMessage(enabled bool) bool

func SetLogDir

func SetLogDir(path string) bool

func SetRecording

func SetRecording(enabled bool) bool

func SetSaveDraw

func SetSaveDraw(enabled bool) bool

func SetShowHitDraw

func SetShowHitDraw(enabled bool) bool

func SetStdoutLevel

func SetStdoutLevel(level LoggingLevel) bool

func Swipe

func Swipe(syncCtx SyncContext, x1, y1, x2, y2, duration int32) bool

func TouchDown

func TouchDown(syncCtx SyncContext, contact, x, y, pressure int32) bool

func TouchMove

func TouchMove(syncCtx SyncContext, contact, x, y, pressure int32) bool

func TouchUp

func TouchUp(syncCtx SyncContext, contact int32) bool

Types

type AdbControllerType

type AdbControllerType int32
const (
	AdbControllerTypeInvalid AdbControllerType = iota

	AdbControllerTypeTouchAdb
	AdbControllerTypeTouchMiniTouch
	AdbControllerTypeTouchMaaTouch
	AdbControllerTypeTouchEmulatorExtras
	AdbControllerTypeTouchAutoDetect AdbControllerType = 0xFF - 1

	AdbControllerTypeKeyAdb            AdbControllerType = 1 << 8
	AdbControllerTypeKeyMaaTouch       AdbControllerType = 2 << 8
	AdbControllerTypeKeyEmulatorExtras AdbControllerType = 3 << 8
	AdbControllerTypeKeyAutoDetect     AdbControllerType = 0xFF00 - (1 << 8)

	AdbControllerTypeInputPresetAdb            = AdbControllerTypeTouchAdb | AdbControllerTypeKeyAdb
	AdbControllerTypeInputPresetMiniTouch      = AdbControllerTypeTouchMiniTouch | AdbControllerTypeKeyAdb
	AdbControllerTypeInputPresetMaaTouch       = AdbControllerTypeTouchMaaTouch | AdbControllerTypeKeyMaaTouch
	AdbControllerTypeInputPresetEmulatorExtras = AdbControllerTypeTouchEmulatorExtras | AdbControllerTypeKeyEmulatorExtras
	AdbControllerTypeInputPresetAutoDetect     = AdbControllerTypeTouchAutoDetect | AdbControllerTypeKeyAutoDetect

	AdbControllerTypeScreencapFastestWayCompatible AdbControllerType = 1 << 16
	AdbControllerTypeScreencapRawByNetcat          AdbControllerType = 2 << 16
	AdbControllerTypeScreencapRawWithGzip          AdbControllerType = 3 << 16
	AdbControllerTypeScreencapEncode               AdbControllerType = 4 << 16
	AdbControllerTypeScreencapEncodeToFile         AdbControllerType = 5 << 16
	AdbControllerTypeScreencapMinicapDirect        AdbControllerType = 6 << 16
	AdbControllerTypeScreencapMinicapStream        AdbControllerType = 7 << 16
	AdbControllerTypeScreencapEmulatorExtras       AdbControllerType = 8 << 16
	AdbControllerTypeScreencapFastestLosslessWay   AdbControllerType = 0xFF0000 - (2 << 16)
	AdbControllerTypeScreencapFastestWay           AdbControllerType = 0xFF0000 - (1 << 16)
)

AdbControllerType

type AnalyzeResult

type AnalyzeResult struct {
	Box    RectBuffer
	Detail string
}

type Controller

type Controller interface {
	Destroy()
	Handle() unsafe.Pointer
	SetOption(key CtrlOption, value unsafe.Pointer, valSize uint64) bool
	PostConnect() int64
	PostClick(x, y int32) int64
	PostSwipe(x1, y1, x2, y2, duration int32) int64
	PostPressKey(keycode int32) int64
	PostInputText(text string) int64
	PostStartApp(intent string) int64
	PostStopApp(intent string) int64
	PostTouchDown(contact, x, y, pressure int32) int64
	PostTouchMove(contact, x, y, pressure int32) int64
	PostTouchUp(contact int32) int64
	PostScreencap() int64
	Status(id int64) Status
	Wait(id int64) Status
	Connected() bool
	GetImage() (ImageBuffer, bool)
	GetUUID() (string, bool)
}

func NewAdbController

func NewAdbController(
	adbPath, address string,
	adbCtrlType AdbControllerType,
	config, agentPath string,
	callback func(msg, detailsJson string),
) Controller

func NewCustomController

func NewCustomController(
	customCtrl CustomControllerImpl,
	callback func(msg, detailsJson string),
) Controller

func NewDbgController

func NewDbgController(
	readPath, writePath string,
	dbgCtrlType DbgControllerType,
	config string,
	callback func(msg, detailsJson string),
) Controller

func NewThriftController

func NewThriftController(
	thriftCtrlType ThriftControllerType,
	host string,
	port int32,
	config string,
	callback func(msg, detailsJson string),
) Controller

func NewWin32Controller

func NewWin32Controller(
	hWnd unsafe.Pointer,
	win32CtrlType Win32ControllerType,
	callback func(msg, detailsJson string),
) Controller

type CtrlOption

type CtrlOption int32
const (
	CtrlOptionInvalid CtrlOption = iota

	// CtrlOptionScreenshotTargetLongSide Only one of long and short side can be set, and the other is automatically scaled according
	// to the aspect ratio.
	//
	// value: int, eg: 1920; val_size: sizeof(int)
	CtrlOptionScreenshotTargetLongSide

	// CtrlOptionScreenshotTargetShortSide Only one of long and short side can be set, and the other is automatically scaled according
	// to the aspect ratio.
	//
	// value: int, eg: 1080; val_size: sizeof(int)
	CtrlOptionScreenshotTargetShortSide

	// CtrlOptionDefaultAppPackageEntry For StartApp
	//
	// value: string, eg: "com.hypergryph.arknights/com.u8.sdk.U8UnityContext"; val_size: string length
	CtrlOptionDefaultAppPackageEntry

	// CtrlOptionDefaultAppPackage For StopApp
	//
	// value: string, eg: "com.hypergryph.arknights"; val_size: string length
	CtrlOptionDefaultAppPackage

	// CtrlOptionRecording Dump all screenshots and actions
	//
	// Recording will evaluate to true if any of this or
	// MaaGlobalOptionEnum::MaaGlobalOption_Recording is true.
	//
	// value: bool, eg: true; val_size: sizeof(bool)
	CtrlOptionRecording
)

CtrlOption

type CustomActionHandler added in v0.2.0

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

func NewCustomActionHandler added in v0.2.0

func NewCustomActionHandler() CustomActionHandler

func (CustomActionHandler) Destroy added in v0.2.0

func (a CustomActionHandler) Destroy()

func (CustomActionHandler) Handle added in v0.2.0

func (a CustomActionHandler) Handle() unsafe.Pointer

type CustomActionImpl added in v0.2.0

type CustomActionImpl interface {
	Run(ctx SyncContext, taskName, ActionParam string, curBox RectBuffer, curRecDetail string) bool
	Stop()

	Handle() unsafe.Pointer
	Destroy()
}

CustomActionImpl defines an interface for custom action. Implementers of this interface must embed an CustomActionHandler struct and provide implementations for the Run and Stop methods.

type CustomControllerHandler added in v0.2.0

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

func NewCustomControllerHandler added in v0.2.0

func NewCustomControllerHandler() CustomControllerHandler

func (CustomControllerHandler) Destroy added in v0.2.0

func (c CustomControllerHandler) Destroy()

func (CustomControllerHandler) Handle added in v0.2.0

type CustomControllerImpl added in v0.2.0

type CustomControllerImpl interface {
	Connect() bool
	RequestUUID() (string, bool)
	RequestResolution() (width, height int32, ok bool)
	StartApp(intent string) bool
	StopApp(intent string) bool
	Screencap() (ImageBuffer, bool)
	Click(x, y int32) bool
	Swipe(x1, y1, x2, y2, duration int32) bool
	TouchDown(contact, x, y, pressure int32) bool
	TouchMove(contact, x, y, pressure int32) bool
	TouchUp(contact int32) bool
	PressKey(keycode int32) bool
	InputText(text string) bool

	Handle() unsafe.Pointer
	Destroy()
}

CustomControllerImpl defines an interface for custom controller. Implementers of this interface must embed a CustomControllerHandler struct and provide implementations for the following methods: Connect, RequestUUID, RequestResolution, StartApp, StopApp, Screencap, Click, Swipe, TouchDown, TouchMove, TouchUp, PressKey and InputText.

type CustomRecognizerHandler added in v0.2.0

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

func NewCustomRecognizerHandler added in v0.2.0

func NewCustomRecognizerHandler() CustomRecognizerHandler

func (CustomRecognizerHandler) Destroy added in v0.2.0

func (r CustomRecognizerHandler) Destroy()

func (CustomRecognizerHandler) Handle added in v0.2.0

type CustomRecognizerImpl added in v0.2.0

type CustomRecognizerImpl interface {
	Analyze(syncCtx SyncContext, image ImageBuffer, taskName, RecognitionParam string) (AnalyzeResult, bool)

	Handle() unsafe.Pointer
	Destroy()
}

CustomRecognizerImpl defines an interface for custom recognizer. Implementers of this interface must embed a CustomRecognizerHandler struct and provide an implementation for the Analyze method.

type DbgControllerType

type DbgControllerType int32
const (
	DbgControllerTypeInvalid DbgControllerType = iota
	DbgControllerTypeCarouselImage
	DbgControllerTypeReplayRecording
)

DbgControllerType

type GlobalOption

type GlobalOption int32
const (
	GlobalOptionInvalid GlobalOption = iota

	// GlobalOptionLogDir Log dir
	//
	// value: string, eg: "C:\\Users\\Administrator\\Desktop\\log"; val_size: string length
	GlobalOptionLogDir

	// GlobalOptionSaveDraw Whether to save draw
	//
	// value: bool, eg: true; val_size: sizeof(bool)
	GlobalOptionSaveDraw

	// GlobalOptionRecording Dump all screenshots and actions
	//
	// Recording will evaluate to true if any of this or MaaCtrlOptionEnum::MaaCtrlOption_Recording
	// is true. value: bool, eg: true; val_size: sizeof(bool)
	GlobalOptionRecording

	// GlobalOptionStdoutLevel The level of log output to stdout
	//
	// value: MaaLoggingLevel, val_size: sizeof(MaaLoggingLevel)
	// default value is MaaLoggingLevel_Error
	GlobalOptionStdoutLevel

	// GlobalOptionShowHitDraw Whether to show hit draw
	//
	// value: bool, eg: true; val_size: sizeof(bool)
	GlobalOptionShowHitDraw

	// GlobalOptionDebugMessage Whether to callback debug message
	//
	// value: bool, eg: true; val_size: sizeof(bool)
	GlobalOptionDebugMessage
)

GlobalOption

type ImageBuffer

type ImageBuffer interface {
	Destroy()
	Handle() unsafe.Pointer
	IsEmpty() bool
	Clear() bool
	GetRawData() unsafe.Pointer
	GetWidth() int32
	GetHeight() int32
	GetType() int32
	SetRawData(data unsafe.Pointer, width, height, imageType int32) bool
	GetEncoded() unsafe.Pointer
	GetEncodedSize() int32
	SetEncoded(data unsafe.Pointer, size uint64) bool
}

func CacheImage

func CacheImage(syncCtx SyncContext) (ImageBuffer, bool)

func NewImage

func NewImage() ImageBuffer

func Screencap

func Screencap(syncCtx SyncContext) (ImageBuffer, bool)

type ImageListBuffer

type ImageListBuffer interface {
	Destroy()
	Handle() unsafe.Pointer
	IsEmpty() bool
	Clear() bool
	Size() uint64
	Get(index uint64) ImageBuffer
	Append(value ImageBuffer) bool
	Remove(index uint64) bool
}

func NewImageList

func NewImageList() ImageListBuffer

type Instance

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

func New

func New(callback func(msg, detailsJson string)) *Instance

func (*Instance) BindController

func (i *Instance) BindController(ctrl Controller) bool

func (*Instance) BindResource

func (i *Instance) BindResource(res *Resource) bool

func (*Instance) ClearCustomAction

func (i *Instance) ClearCustomAction() bool

func (*Instance) ClearCustomRecognizer

func (i *Instance) ClearCustomRecognizer() bool

func (*Instance) Destroy

func (i *Instance) Destroy()

func (*Instance) GetController

func (i *Instance) GetController() Controller

func (*Instance) GetResource

func (i *Instance) GetResource() *Resource

func (*Instance) Handle

func (i *Instance) Handle() unsafe.Pointer

func (*Instance) Inited

func (i *Instance) Inited() bool

func (*Instance) PostAction

func (i *Instance) PostAction(entry, param string) int64

func (*Instance) PostRecognition

func (i *Instance) PostRecognition(entry, param string) int64

func (*Instance) PostStop

func (i *Instance) PostStop() bool

func (*Instance) PostTask

func (i *Instance) PostTask(entry, param string) int64

func (*Instance) RegisterCustomAction

func (i *Instance) RegisterCustomAction(name string, action CustomActionImpl) bool

func (*Instance) RegisterCustomRecognizer

func (i *Instance) RegisterCustomRecognizer(name string, recognizer CustomRecognizerImpl) bool

func (*Instance) Running

func (i *Instance) Running() bool

func (*Instance) SetTaskParam

func (i *Instance) SetTaskParam(id int64, param string) bool

func (*Instance) TaskStatus

func (i *Instance) TaskStatus(id int64) Status

func (*Instance) UnregisterCustomAction

func (i *Instance) UnregisterCustomAction(name string) bool

func (*Instance) UnregisterCustomRecognizer

func (i *Instance) UnregisterCustomRecognizer(name string) bool

func (*Instance) WaitTask

func (i *Instance) WaitTask(id int64) Status

type LoggingLevel

type LoggingLevel int32
const (
	LoggingLevelOff LoggingLevel = iota
	LoggingLevelFatal
	LoggingLevelError
	LoggingLevelWarn
	LoggingLevelInfo
	LoggingLevelDebug
	LoggingLevelTrace
	LoggingLevelAll
)

LoggingLevel

type NodeDetail

type NodeDetail struct {
	Name         string
	RecId        int64
	RunCompleted bool
}

func QueryNodeDetail

func QueryNodeDetail(nodeId int64) (*NodeDetail, bool)

type RecognitionDetail

type RecognitionDetail struct {
	Name       string
	Hit        bool
	DetailJson string
	Raw        ImageBuffer
	Draws      ImageListBuffer
}

func QueryRecognitionDetail

func QueryRecognitionDetail(recId int64) (RecognitionDetail, bool)

type RectBuffer

type RectBuffer interface {
	Destroy()
	Handle() unsafe.Pointer
	GetX() int32
	GetY() int32
	GetW() int32
	GetH() int32
	Set(x, y, w, h int32) bool

	SetY(value int32) bool
	SetW(value int32) bool
	SetH(value int32) bool
	// contains filtered or unexported methods
}

func NewRect

func NewRect() RectBuffer

type Resource

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

func NewResource

func NewResource(callback func(msg, detailsJson string)) *Resource

NewResource creates a new resource.

This function takes two arguments:

  • callback: The callback function.

func (*Resource) Clear

func (r *Resource) Clear() bool

Clear clears the resource loading paths. If the call is successful, it returns true. Otherwise, it returns false.

func (*Resource) Destroy

func (r *Resource) Destroy()

Destroy frees the resource.

func (*Resource) GetHash

func (r *Resource) GetHash() (string, bool)

GetHash gets the hash of the resource.

func (*Resource) GetTaskList

func (r *Resource) GetTaskList() (string, bool)

GetTaskList gets the task list of the resource.

func (*Resource) Loaded

func (r *Resource) Loaded() bool

Loaded checks if resources are loaded.

func (*Resource) PostPath

func (r *Resource) PostPath(path string) int64

PostPath adds a path to the resource loading paths. Return id of the resource.

func (*Resource) Status

func (r *Resource) Status(resId int64) Status

Status gets the loading status of a resource identified by id.

func (*Resource) Wait

func (r *Resource) Wait(resId int64) Status

Wait waits for a resource to be loaded.

type Status

type Status int32
const (
	Invalid Status = 0
	Pending Status = 1000
	Running Status = 2000
	Success Status = 3000
	Failed  Status = 4000
)

type StringBuffer

type StringBuffer interface {
	Destroy()
	Handle() unsafe.Pointer
	IsEmpty() bool
	Clear() bool
	Get() string
	Size() uint64
	Set(str string) bool
	SetWithSize(str string, size uint64) bool
}

func NewString

func NewString() StringBuffer

type StringListBuffer

type StringListBuffer interface {
	Destroy()
	IsEmpty() bool
	Clear() bool
	Size() uint64
	Get(index uint64) string
	Append(value StringBuffer) bool
	Remove(index uint64) bool
}

func NewStringList

func NewStringList() StringListBuffer

type SyncContext

type SyncContext C.MaaSyncContextHandle

type TaskDetail

type TaskDetail struct {
	Entry      string
	NodeIdList []int64
}

func QueryTaskDetail

func QueryTaskDetail(taskId int64) (*TaskDetail, bool)

type ThriftControllerType

type ThriftControllerType int32
const (
	ThriftControllerInvalid ThriftControllerType = iota
	ThriftControllerTypeSocket
	ThriftControllerTypeUnixDomainSocket
)

type Win32ControllerType

type Win32ControllerType int32
const (
	Win32ControllerTypeInvalid Win32ControllerType = iota

	Win32ControllerTypeTouchSendMessage
	Win32ControllerTypeTouchSeize

	Win32ControllerTypeKeySendMessage Win32ControllerType = 1 << 8
	Win32ControllerTypeKeySeize       Win32ControllerType = 2 << 8

	Win32ControllerTypeScreencapGDI            Win32ControllerType = 1 << 16
	Win32ControllerTypeScreencapDXGIDesktopDup Win32ControllerType = 2 << 16
	Win32ControllerTypeScreencapDXGIFramePool  Win32ControllerType = 4 << 16
)

Win32ControllerType

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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