Matrix/main.go

206 lines
4.8 KiB
Go
Raw Normal View History

2024-04-12 07:54:27 +00:00
package main
import (
2024-04-12 09:58:13 +00:00
"bytes"
2024-04-12 08:14:25 +00:00
"encoding/json"
2024-04-12 08:00:53 +00:00
"errors"
2024-04-12 07:54:27 +00:00
"fmt"
2024-04-12 08:00:53 +00:00
"log"
2024-04-12 09:58:13 +00:00
"mime/multipart"
2024-04-12 08:00:53 +00:00
"os"
"strconv"
"github.com/go-resty/resty/v2"
"github.com/joho/godotenv"
2024-04-12 07:54:27 +00:00
)
2024-04-12 08:01:24 +00:00
type Response struct {
Success bool `json:"success"`
2024-04-12 08:01:24 +00:00
}
type Endpoint string
const (
RECTANGLE Endpoint = "rectangle"
UPDATE Endpoint = "update"
COLOR Endpoint = "color"
)
type Update struct {
2024-04-12 08:49:20 +00:00
Endpoint Endpoint `json:"endpoint"`
2024-04-12 08:01:24 +00:00
}
type Color struct {
2024-04-12 08:49:20 +00:00
R int `json:"r"`
G int `json:"g"`
B int `json:"b"`
Endpoint Endpoint `json:"endpoint"`
2024-04-12 08:01:24 +00:00
}
type Rectangle struct {
2024-04-12 08:49:20 +00:00
X int `json:"x"`
Y int `json:"y"`
W int `json:"w"`
H int `json:"h"`
Endpoint Endpoint `json:"endpoint"`
2024-04-12 08:01:24 +00:00
}
func GetEnvFallback(key string, fallback ...string) (string, error) {
// Check for function fallback signature
length := len(fallback)
if length > 1 {
return "", errors.New("Invalid signature: Too many fallback values provided!")
}
// Try to get environment variable
value, exists := os.LookupEnv(key)
if exists {
return value, nil
}
// Try using fallback value instead
if length == 1 {
return fallback[0], nil
} else if length == 0 {
// No fallback value provided
return "", errors.New("Panic: No fallback value provided!")
}
// Could not get environment variable
return "", errors.New("Could not get environment variable: " + key)
}
func ConvertFallback(input string, fallback ...int) (int, error) {
// Check for function fallback signature
length := len(fallback)
if length > 1 {
return 0, errors.New("Invalid signature: Too many fallback values provided!")
}
// Try to convert input to int
value, err := strconv.Atoi(input)
if err == nil {
return value, nil
}
// Try using fallback value instead
if length == 1 {
return fallback[0], nil
} else if length == 0 {
// No fallback value provided
return 0, errors.New("Panic: No fallback value provided!")
}
// Could not convert input
return 0, err
}
func LoadMatrixData() (string, int, int) {
// Remote server info
2024-04-12 08:13:28 +00:00
API_SERVER_IP, _ := GetEnvFallback("API_SERVER_IP", "localhost")
API_SERVER_PORT, _ := GetEnvFallback("API_SERVER_PORT", "8080")
// LED panel info
PUBLIC_LED_WIDTH, _ := ConvertFallback(os.Getenv("PUBLIC_LED_WIDTH"), 64)
PUBLIC_LED_HEIGHT, _ := ConvertFallback(os.Getenv("PUBLIC_LED_HEIGHT"), 64)
// Matrix arrangement info
PUBLIC_LED_CHAIN, _ := ConvertFallback(os.Getenv("PUBLIC_LED_CHAIN"), 1)
PUBLIC_LED_PARALLEL, _ := ConvertFallback(os.Getenv("PUBLIC_LED_PARALLEL"), 1)
// Prepare remote server url
url := fmt.Sprintf("http://%s:%s", API_SERVER_IP, API_SERVER_PORT)
// Calculate combined resolution
width := PUBLIC_LED_WIDTH * PUBLIC_LED_CHAIN
height := PUBLIC_LED_HEIGHT * PUBLIC_LED_PARALLEL
return url, width, height
}
2024-04-12 09:58:13 +00:00
func CreateInsructions(marshal []byte) (*bytes.Buffer, string) {
// Create a new form data object
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Add the "instructions" key with the value of marshal
part, err := writer.CreateFormField("instructions")
if err != nil {
log.Fatal(err)
return nil, ""
}
part.Write(marshal)
// Close the multipart writer
writer.Close()
return body, writer.FormDataContentType()
}
2024-04-12 08:03:36 +00:00
func SendRequest(client *resty.Client, url string, ins []interface{}) {
2024-04-12 08:49:49 +00:00
// Manually marshal instructions
marshal, err := json.Marshal(ins)
if err != nil {
log.Fatal(err)
return
}
// Debug log json data
log.Printf("Request: %s\n", string(marshal))
2024-04-12 09:58:13 +00:00
// Create instructions form data
req, content := CreateInsructions(marshal)
if req == nil {
return
}
2024-04-12 08:05:14 +00:00
// Build and send request
2024-04-12 09:58:13 +00:00
res, err := client.R().
SetHeader("Content-Type", content).
SetBody(req.Bytes()).
2024-04-12 08:03:36 +00:00
Post(fmt.Sprintf("%s/instructions", url))
2024-04-12 08:05:14 +00:00
// Error handling
2024-04-12 08:03:36 +00:00
if err != nil {
log.Fatal(err)
return
}
2024-04-12 08:05:14 +00:00
// Print response status
2024-04-12 09:58:13 +00:00
log.Printf("Response Status: %s\n", res.Status())
2024-04-12 08:14:25 +00:00
// Unmarshal response
var data Response
2024-04-12 09:58:13 +00:00
err = json.Unmarshal(res.Body(), &data)
2024-04-12 08:14:25 +00:00
if err != nil {
log.Fatal(err)
return
}
// Print response
log.Printf("Success: %t\n", data.Success)
2024-04-12 08:03:36 +00:00
}
2024-04-12 07:54:27 +00:00
func main() {
2024-04-12 08:02:12 +00:00
// Load .env file if it exists
err := godotenv.Load(".env")
if err != nil {
log.Fatal("Error loading .env file")
}
// Load env server data
2024-04-12 08:14:17 +00:00
url, width, height := LoadMatrixData()
log.Printf("At '%s': %d x %d\n", url, width, height)
// Initialize resty client
client := resty.New()
// Initialize custom matrix data
2024-04-12 08:50:12 +00:00
col := Color{R: 255, G: 0, B: 255, Endpoint: COLOR}
rct := Rectangle{X: 0, Y: 0, W: 10, H: 10, Endpoint: RECTANGLE}
upd := Update{Endpoint: UPDATE}
2024-04-12 08:03:36 +00:00
// Send request to remote server
SendRequest(client, url, []interface{}{col, rct, upd})
2024-04-12 07:54:27 +00:00
}