99 lines
2.4 KiB
Go
99 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type alamosAlarm struct {
|
|
Message string `json:"message"`
|
|
Type string `json:"type"`
|
|
Sender string `json:"sender"`
|
|
Timestamp int64 `json:"timestamp"`
|
|
}
|
|
|
|
func main() {
|
|
|
|
storefolder := filepath.Join(".", "storetmp")
|
|
_ = os.MkdirAll(storefolder, os.ModePerm)
|
|
|
|
alamosPort, _ := strconv.Atoi(os.Args[1])
|
|
sds := strings.Join(os.Args[2:], " ")
|
|
finalString := strings.HasPrefix(sds, "#")
|
|
|
|
partialAlarmRegex := regexp.MustCompile(`\s(?P<alarmid>\d+)\/(?P<position>\d+)\)(?P<alarmtext>.+$)`)
|
|
|
|
if !partialAlarmRegex.MatchString(sds) {
|
|
fmt.Println("Alarm is not a splitted alarm")
|
|
completeAlarmRegex := regexp.MustCompile(`\s(?P<alarmtext>\d+\/.+$)`)
|
|
if !completeAlarmRegex.MatchString(sds) {
|
|
log.Fatal("Recived invalid alarm text: " + sds)
|
|
}
|
|
matches := completeAlarmRegex.FindStringSubmatch(sds)
|
|
sendAlarmToAlamos(matches[1], alamosPort)
|
|
}
|
|
fmt.Println("Alarm is a splitted alarm")
|
|
|
|
matches := partialAlarmRegex.FindStringSubmatch(sds)
|
|
alarmid := matches[1]
|
|
position, _ := strconv.Atoi(matches[2])
|
|
alarmtext := matches[3]
|
|
fmt.Printf("Recived alarm with id %s and position %d\n", alarmid, position)
|
|
|
|
if finalString {
|
|
// read all previous text
|
|
mergedAlarmtext := alarmid
|
|
for i := 1; i < position; i++ {
|
|
filename := filepath.Join(storefolder, fmt.Sprintf("%s_%d.txt", alarmid, i))
|
|
f, err := os.ReadFile(filename)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
os.Remove(filename)
|
|
mergedAlarmtext += string(f)
|
|
}
|
|
sendAlarmToAlamos(mergedAlarmtext, alamosPort)
|
|
} else {
|
|
filename := filepath.Join(storefolder, fmt.Sprintf("%s_%d.txt", alarmid, position))
|
|
f, err := os.Create(filename)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
f.WriteString(alarmtext)
|
|
defer f.Close()
|
|
}
|
|
|
|
}
|
|
|
|
func sendAlarmToAlamos(text string, port int) {
|
|
tcpAddr, _ := net.ResolveTCPAddr("tcp", "localhost:"+strconv.Itoa(port))
|
|
conn, err := net.DialTCP("tcp", nil, tcpAddr)
|
|
if err != nil {
|
|
log.Fatal("Failed connecting to Alamos", err)
|
|
}
|
|
|
|
alarm := &alamosAlarm{
|
|
Message: text,
|
|
Type: "ALARM",
|
|
Sender: "self",
|
|
Timestamp: time.Now().UnixNano(),
|
|
}
|
|
alarmjson, err := json.Marshal(alarm)
|
|
if err != nil {
|
|
log.Fatal("Failed marshalling alarm json", err)
|
|
}
|
|
_, err = conn.Write(alarmjson)
|
|
if err != nil {
|
|
log.Fatal("Failed writing alarm", err)
|
|
}
|
|
conn.Close()
|
|
log.Println("Successfully published new alarm")
|
|
}
|