79 lines
2.1 KiB
Go
Raw Normal View History

2021-09-29 11:32:34 +02:00
package signal
/*
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
2021-10-07 11:50:53 +02:00
extern bool KeycardServiceSignalEvent(const char *jsonEvent);
extern void KeycardSetEventCallback(void *cb);
2021-09-29 11:32:34 +02:00
*/
import "C"
import (
"encoding/json"
"unsafe"
"github.com/ethereum/go-ethereum/log"
)
2021-10-07 11:50:53 +02:00
// KeycardSignalHandler is a simple callback function that gets called when any signal is received
type KeycardSignalHandler func([]byte)
2021-09-29 11:32:34 +02:00
// storing the current signal handler here
2021-10-07 11:50:53 +02:00
var keycardSignalHandler KeycardSignalHandler
2021-09-29 11:32:34 +02:00
// All general log messages in this package should be routed through this logger.
2021-10-07 11:50:53 +02:00
var logger = log.New("package", "keycard-go/signal")
2021-09-29 11:32:34 +02:00
// Envelope is a general signal sent upward from node to RN app
type Envelope struct {
Type string `json:"type"`
Event interface{} `json:"event"`
}
// NewEnvelope creates new envlope of given type and event payload.
func NewEnvelope(typ string, event interface{}) *Envelope {
return &Envelope{
Type: typ,
Event: event,
}
}
// send sends application signal (in JSON) upwards to application (via default notification handler)
func send(typ string, event interface{}) {
signal := NewEnvelope(typ, event)
data, err := json.Marshal(&signal)
if err != nil {
logger.Error("Marshalling signal envelope", "error", err)
return
}
// If a Go implementation of signal handler is set, let's use it.
2021-10-07 11:50:53 +02:00
if keycardSignalHandler != nil {
keycardSignalHandler(data)
2021-09-29 11:32:34 +02:00
} else {
// ...and fallback to C implementation otherwise.
str := C.CString(string(data))
2021-10-07 11:50:53 +02:00
C.KeycardServiceSignalEvent(str)
2021-09-29 11:32:34 +02:00
C.free(unsafe.Pointer(str))
}
}
//export KeycardTriggerTestSignal
2021-09-29 11:32:34 +02:00
//nolint: golint
func KeycardTriggerTestSignal() {
2021-09-29 11:32:34 +02:00
str := C.CString(`{"answer": 42}`)
2021-10-07 11:50:53 +02:00
C.KeycardServiceSignalEvent(str)
2021-09-29 11:32:34 +02:00
C.free(unsafe.Pointer(str))
}
2021-10-07 11:50:53 +02:00
// SetKeycardSignalHandler sets new handler for geth events
2021-09-29 11:32:34 +02:00
// this function uses pure go implementation
2021-10-07 11:50:53 +02:00
func SetKeycardSignalHandler(handler KeycardSignalHandler) {
keycardSignalHandler = handler
2021-09-29 11:32:34 +02:00
}
2021-10-07 11:50:53 +02:00
// KeycardSetSignalEventCallback set callback
2021-09-29 11:32:34 +02:00
// this function uses C implementation (see `signals.c` file)
2021-10-07 11:50:53 +02:00
func KeycardSetSignalEventCallback(cb unsafe.Pointer) {
C.KeycardSetEventCallback(cb)
2021-09-29 11:32:34 +02:00
}