go-waku/library/signals.go

82 lines
2.1 KiB
Go
Raw Normal View History

2023-08-10 13:30:38 +00:00
package library
2022-03-21 23:15:53 +00:00
/*
#include <stddef.h>
2022-03-21 23:15:53 +00:00
#include <stdbool.h>
#include <stdlib.h>
2023-08-10 13:30:38 +00:00
extern bool ServiceSignalEvent(const char *jsonEvent, size_t len);
2022-03-21 23:15:53 +00:00
extern void SetEventCallback(void *cb);
*/
import "C"
2022-03-21 23:15:53 +00:00
import (
"encoding/json"
"fmt"
"unsafe"
)
// SignalHandler defines a minimal interface
// a signal handler needs to implement.
// nolint
type SignalHandler interface {
HandleSignal(string)
}
// MobileSignalHandler is a simple callback function that gets called when any signal is received
2022-03-21 23:15:53 +00:00
type MobileSignalHandler func([]byte)
// storing the current mobile signal handler here
var mobileSignalHandler MobileSignalHandler
// signalEnvelope is a general signal sent upward from node to app
type signalEnvelope struct {
2022-04-03 00:22:42 +00:00
Type string `json:"type"`
Event interface{} `json:"event"`
2022-03-21 23:15:53 +00:00
}
// NewEnvelope creates new envlope of given type and event payload.
func newEnvelope(signalType string, event interface{}) *signalEnvelope {
return &signalEnvelope{
2022-04-03 00:22:42 +00:00
Type: signalType,
Event: event,
2022-03-21 23:15:53 +00:00
}
}
// send sends application signal (in JSON) upwards to application (via default notification handler)
2022-04-03 00:22:42 +00:00
func send(signalType string, event interface{}) {
signal := newEnvelope(signalType, event)
2022-03-21 23:15:53 +00:00
data, err := json.Marshal(&signal)
if err != nil {
fmt.Println("marshal signal error", err)
return
}
// If a Go implementation of signal handler is set, let's use it.
if mobileSignalHandler != nil {
mobileSignalHandler(data)
} else {
// ...and fallback to C implementation otherwise.
2023-08-10 13:30:38 +00:00
dataStr := string(data)
str := C.CString(dataStr)
C.ServiceSignalEvent(str, C.size_t(len(data)))
2022-03-21 23:15:53 +00:00
C.free(unsafe.Pointer(str))
}
}
// SetMobileSignalHandler setup geth callback to notify about new signal
// used for gomobile builds
// nolint
2022-03-21 23:15:53 +00:00
func SetMobileSignalHandler(handler SignalHandler) {
mobileSignalHandler = func(data []byte) {
if len(data) > 0 {
handler.HandleSignal(string(data))
}
}
}
// SetEventCallback is to set a callback in order to receive application
// signals which are used to react to asynchronous events in waku.
func SetEventCallback(cb unsafe.Pointer) {
2022-03-21 23:15:53 +00:00
C.SetEventCallback(cb)
}