feat(platform): harden telemetry pipeline and unify Semi UI workspaces
This commit is contained in:
57
go/vehicle-gateway/internal/feichibridge/captcha.go
Normal file
57
go/vehicle-gateway/internal/feichibridge/captcha.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var captchaPattern = regexp.MustCompile(`^[0-9A-Z]{4}$`)
|
||||
|
||||
type CaptchaSolver interface {
|
||||
Solve(context.Context, []byte) (string, error)
|
||||
}
|
||||
|
||||
type DockerCaptchaSolver struct {
|
||||
Image string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (s DockerCaptchaSolver) Solve(ctx context.Context, image []byte) (string, error) {
|
||||
if len(image) == 0 {
|
||||
return "", errors.New("captcha image is empty")
|
||||
}
|
||||
if strings.TrimSpace(s.Image) == "" {
|
||||
return "", errors.New("captcha OCR image is required")
|
||||
}
|
||||
timeout := s.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 20 * time.Second
|
||||
}
|
||||
solveCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
command := exec.CommandContext(
|
||||
solveCtx,
|
||||
"docker", "run", "--rm", "--network=none", "-i", strings.TrimSpace(s.Image),
|
||||
)
|
||||
command.Stdin = bytes.NewReader(image)
|
||||
var stderr bytes.Buffer
|
||||
command.Stderr = &stderr
|
||||
output, err := command.Output()
|
||||
if err != nil {
|
||||
if solveCtx.Err() != nil {
|
||||
return "", fmt.Errorf("captcha OCR timed out: %w", solveCtx.Err())
|
||||
}
|
||||
return "", fmt.Errorf("captcha OCR failed: %w: %s", err, strings.TrimSpace(stderr.String()))
|
||||
}
|
||||
code := strings.ToUpper(strings.TrimSpace(string(output)))
|
||||
if !captchaPattern.MatchString(code) {
|
||||
return "", fmt.Errorf("captcha OCR returned invalid result %q", code)
|
||||
}
|
||||
return code, nil
|
||||
}
|
||||
211
go/vehicle-gateway/internal/feichibridge/client.go
Normal file
211
go/vehicle-gateway/internal/feichibridge/client.go
Normal file
@@ -0,0 +1,211 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrUnauthorized = errors.New("feichi API session unauthorized")
|
||||
|
||||
type APIClient struct {
|
||||
baseURL *url.URL
|
||||
headers http.Header
|
||||
client *http.Client
|
||||
login *loginSession
|
||||
}
|
||||
|
||||
func NewAPIClient(baseURL string, headers map[string]string, timeout time.Duration) (*APIClient, error) {
|
||||
parsed, err := url.Parse(strings.TrimRight(strings.TrimSpace(baseURL), "/") + "/")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse FEICHI_BASE_URL: %w", err)
|
||||
}
|
||||
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||
return nil, fmt.Errorf("FEICHI_BASE_URL must use http or https")
|
||||
}
|
||||
if timeout <= 0 {
|
||||
timeout = 15 * time.Second
|
||||
}
|
||||
out := &APIClient{
|
||||
baseURL: parsed,
|
||||
headers: make(http.Header),
|
||||
client: &http.Client{Timeout: timeout},
|
||||
}
|
||||
for name, value := range headers {
|
||||
if strings.TrimSpace(name) != "" && strings.TrimSpace(value) != "" {
|
||||
out.headers.Set(name, value)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func NewAuthenticatedAPIClient(baseURL string, credentials LoginCredentials, solver CaptchaSolver, timeout time.Duration) (*APIClient, error) {
|
||||
client, err := NewAPIClient(baseURL, nil, timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
login, err := newLoginSession(credentials, solver)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client.login = login
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) Vehicles(ctx context.Context) ([]Vehicle, error) {
|
||||
payload := map[string]any{
|
||||
"conditions": []map[string]string{
|
||||
{"name": "iccid", "value": ""},
|
||||
{"name": "powerMode", "value": ""},
|
||||
},
|
||||
"sort": []map[string]string{{"name": "updateTime", "order": "desc"}},
|
||||
"start": 0,
|
||||
"limit": 100,
|
||||
}
|
||||
var envelope collectionEnvelope[Vehicle]
|
||||
if err := c.doJSON(ctx, http.MethodPost, "api/v1/sys/vehicleRealStatuss", payload, &envelope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !apiCodeOK(envelope.Code) {
|
||||
return nil, apiCodeError(envelope.Code)
|
||||
}
|
||||
return envelope.Data, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) Snapshot(ctx context.Context, vehicleID string) (Snapshot, error) {
|
||||
path := "api/v1/sys/vehicleRealStatussByVId/" + url.PathEscape(vehicleID) + "/-1"
|
||||
var envelope objectEnvelope[Snapshot]
|
||||
if err := c.doJSON(ctx, http.MethodGet, path, nil, &envelope); err != nil {
|
||||
return Snapshot{}, err
|
||||
}
|
||||
if !apiCodeOK(envelope.Code) {
|
||||
return Snapshot{}, apiCodeError(envelope.Code)
|
||||
}
|
||||
return envelope.Data, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) History(ctx context.Context, vin string, begin, end time.Time) ([]Record, error) {
|
||||
payload := map[string]any{
|
||||
"conditions": []map[string]string{
|
||||
{"name": "queryType", "value": "0"},
|
||||
{"name": "queryContent", "value": vin},
|
||||
{"name": "beginTime", "value": begin.In(shanghai).Format("2006-01-02 15:04:05")},
|
||||
{"name": "endTime", "value": end.In(shanghai).Format("2006-01-02 15:04:05")},
|
||||
{"name": "hisdataType", "value": "0"},
|
||||
},
|
||||
"start": 0,
|
||||
"limit": 100,
|
||||
}
|
||||
var envelope collectionEnvelope[historySegment]
|
||||
if err := c.doJSON(ctx, http.MethodPost, "api/v1/sys/hisdataQuerys", payload, &envelope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !apiCodeOK(envelope.Code) {
|
||||
return nil, apiCodeError(envelope.Code)
|
||||
}
|
||||
var records []Record
|
||||
for _, segment := range envelope.Data {
|
||||
records = append(records, segment.Subdata...)
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) doJSON(ctx context.Context, method, path string, body any, output any) error {
|
||||
if c.login != nil {
|
||||
if err := c.login.ensure(ctx, c); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
_, err := c.rawJSON(ctx, method, path, body, output)
|
||||
if !errors.Is(err, ErrUnauthorized) || c.login == nil || attempt == 1 {
|
||||
return err
|
||||
}
|
||||
c.login.invalidate()
|
||||
if err := c.login.ensure(ctx, c); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return ErrUnauthorized
|
||||
}
|
||||
|
||||
func (c *APIClient) rawJSON(ctx context.Context, method, path string, body any, output any) (http.Header, error) {
|
||||
endpoint, err := c.baseURL.Parse(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
encoded, marshalErr := json.Marshal(body)
|
||||
if marshalErr != nil {
|
||||
return nil, marshalErr
|
||||
}
|
||||
reader = bytes.NewReader(encoded)
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, method, endpoint.String(), reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Header.Set("Accept", "application/json")
|
||||
if body != nil {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for name, values := range c.headers {
|
||||
for _, value := range values {
|
||||
request.Header.Add(name, value)
|
||||
}
|
||||
}
|
||||
if c.login != nil {
|
||||
if cookie := c.login.cookieHeader(); cookie != "" {
|
||||
request.Header.Set("Cookie", cookie)
|
||||
}
|
||||
if csrf := c.login.csrfHeader(); csrf != "" {
|
||||
request.Header.Set("x-api-csrf", csrf)
|
||||
}
|
||||
}
|
||||
response, err := c.client.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("feichi %s %s: %w", method, path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden {
|
||||
return response.Header, ErrUnauthorized
|
||||
}
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
snippet, _ := io.ReadAll(io.LimitReader(response.Body, 1024))
|
||||
return response.Header, fmt.Errorf("feichi %s %s: HTTP %d: %s", method, path, response.StatusCode, strings.TrimSpace(string(snippet)))
|
||||
}
|
||||
encoded, err := io.ReadAll(io.LimitReader(response.Body, 16<<20))
|
||||
if err != nil {
|
||||
return response.Header, fmt.Errorf("read feichi %s: %w", path, err)
|
||||
}
|
||||
var status struct {
|
||||
Code any `json:"code"`
|
||||
}
|
||||
if err := json.Unmarshal(encoded, &status); err != nil {
|
||||
return response.Header, fmt.Errorf("decode feichi %s: %w", path, err)
|
||||
}
|
||||
if fmt.Sprint(status.Code) == "401" || fmt.Sprint(status.Code) == "403" {
|
||||
return response.Header, ErrUnauthorized
|
||||
}
|
||||
if output != nil {
|
||||
if err := json.Unmarshal(encoded, output); err != nil {
|
||||
return response.Header, fmt.Errorf("decode feichi %s: %w", path, err)
|
||||
}
|
||||
}
|
||||
return response.Header, nil
|
||||
}
|
||||
|
||||
func apiCodeError(code any) error {
|
||||
if fmt.Sprint(code) == "401" || fmt.Sprint(code) == "403" {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return fmt.Errorf("feichi API returned code %v", code)
|
||||
}
|
||||
154
go/vehicle-gateway/internal/feichibridge/client_test.go
Normal file
154
go/vehicle-gateway/internal/feichibridge/client_test.go
Normal file
@@ -0,0 +1,154 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fixedCaptchaSolver struct {
|
||||
code string
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *fixedCaptchaSolver) Solve(_ context.Context, image []byte) (string, error) {
|
||||
s.calls++
|
||||
if string(image) != "captcha-image" {
|
||||
return "", fmt.Errorf("unexpected captcha image")
|
||||
}
|
||||
return s.code, nil
|
||||
}
|
||||
|
||||
func TestAPIClientUsesSessionHeadersAndExpectedEndpoints(t *testing.T) {
|
||||
var calls int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
calls++
|
||||
if request.Header.Get("Cookie") != "R_SESS=test" || request.Header.Get("x-api-csrf") != "csrf" {
|
||||
t.Errorf("missing session headers: %#v", request.Header)
|
||||
}
|
||||
response.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case request.URL.Path == "/api/v1/sys/vehicleRealStatuss":
|
||||
_ = json.NewEncoder(response).Encode(map[string]any{
|
||||
"code": 200,
|
||||
"data": []map[string]string{{"vehicleId": "id-1", "vin": "LTEST32960VIN0001"}},
|
||||
})
|
||||
case strings.Contains(request.URL.Path, "vehicleRealStatussByVId"):
|
||||
_ = json.NewEncoder(response).Encode(map[string]any{
|
||||
"code": 200,
|
||||
"data": map[string]any{"vehicleId": "id-1", "vin": "LTEST32960VIN0001", "dataItems": map[string]string{"2000": "2026-07-17 12:00:00"}},
|
||||
})
|
||||
case request.URL.Path == "/api/v1/sys/hisdataQuerys":
|
||||
_ = json.NewEncoder(response).Encode(map[string]any{
|
||||
"code": 200,
|
||||
"data": []map[string]any{{"subdata": []map[string]string{{"2000": "2026-07-17 11:59:50"}}}},
|
||||
})
|
||||
default:
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewAPIClient(server.URL, map[string]string{"Cookie": "R_SESS=test", "x-api-csrf": "csrf"}, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vehicles, err := client.Vehicles(context.Background())
|
||||
if err != nil || len(vehicles) != 1 {
|
||||
t.Fatalf("vehicles = %#v, err = %v", vehicles, err)
|
||||
}
|
||||
if _, err := client.Snapshot(context.Background(), "id-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
records, err := client.History(context.Background(), vehicles[0].VIN, time.Now().Add(-time.Hour), time.Now())
|
||||
if err != nil || len(records) != 1 {
|
||||
t.Fatalf("history = %#v, err = %v", records, err)
|
||||
}
|
||||
if calls != 3 {
|
||||
t.Fatalf("calls = %d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIClientMapsUnauthorizedEnvelope(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = response.Write([]byte(`{"code":401,"data":[]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := NewAPIClient(server.URL, nil, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.Vehicles(context.Background()); err != ErrUnauthorized {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticatedAPIClientLogsInAndRetriesExpiredSession(t *testing.T) {
|
||||
var loginCalls int
|
||||
var vehicleCalls int
|
||||
solver := &fixedCaptchaSolver{code: "12WN"}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
response.Header().Set("Content-Type", "application/json")
|
||||
switch request.URL.Path {
|
||||
case "/api/v1/first-login":
|
||||
response.Header().Set("x-api-csrf", "csrf-value")
|
||||
response.Header().Add("Set-Cookie", "CSRF=csrf-value; Path=/")
|
||||
_, _ = response.Write([]byte(`{"code":200}`))
|
||||
case "/api/v1/login/randCode":
|
||||
if request.Header.Get("x-api-csrf") != "csrf-value" {
|
||||
t.Errorf("captcha CSRF = %q", request.Header.Get("x-api-csrf"))
|
||||
}
|
||||
src := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString([]byte("captcha-image"))
|
||||
_ = json.NewEncoder(response).Encode(map[string]any{"code": 200, "data": map[string]string{"src": src}})
|
||||
case "/api/v1/login":
|
||||
loginCalls++
|
||||
var payload map[string]string
|
||||
_ = json.NewDecoder(request.Body).Decode(&payload)
|
||||
if payload["username"] != "JXQN0003" || payload["validCode"] != "12WN" {
|
||||
t.Errorf("login payload = %#v", payload)
|
||||
}
|
||||
encrypted, err := base64.StdEncoding.DecodeString(payload["password"])
|
||||
if err != nil || len(encrypted) != 128 || payload["password"] == "JXQN0003-" {
|
||||
t.Errorf("password was not RSA encrypted: len=%d err=%v", len(encrypted), err)
|
||||
}
|
||||
_ = json.NewEncoder(response).Encode(map[string]any{
|
||||
"code": 200, "data": map[string]string{"token": fmt.Sprintf("token-%d", loginCalls)},
|
||||
})
|
||||
case "/api/v1/sys/vehicleRealStatuss":
|
||||
vehicleCalls++
|
||||
if vehicleCalls == 1 {
|
||||
_, _ = response.Write([]byte(`{"code":401,"data":[]}`))
|
||||
return
|
||||
}
|
||||
if request.Header.Get("Cookie") != "CSRF=csrf-value; R_SESS=token-2" {
|
||||
t.Errorf("session cookie = %q", request.Header.Get("Cookie"))
|
||||
}
|
||||
_, _ = response.Write([]byte(`{"code":200,"data":[]}`))
|
||||
default:
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewAuthenticatedAPIClient(
|
||||
server.URL,
|
||||
LoginCredentials{Username: "JXQN0003", Password: "JXQN0003-", MaxAttempts: 2},
|
||||
solver,
|
||||
time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.Vehicles(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loginCalls != 2 || solver.calls != 2 || vehicleCalls != 2 {
|
||||
t.Fatalf("login=%d solver=%d vehicles=%d", loginCalls, solver.calls, vehicleCalls)
|
||||
}
|
||||
}
|
||||
481
go/vehicle-gateway/internal/feichibridge/encoder.go
Normal file
481
go/vehicle-gateway/internal/feichibridge/encoder.go
Normal file
@@ -0,0 +1,481 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
CommandRealtime = byte(0x02)
|
||||
CommandReissue = byte(0x03)
|
||||
CommandLogin = byte(0x05)
|
||||
)
|
||||
|
||||
type Encoder struct{}
|
||||
|
||||
func (Encoder) DataFrame(command byte, vin string, at time.Time, record Record) ([]byte, error) {
|
||||
if command != CommandRealtime && command != CommandReissue {
|
||||
return nil, fmt.Errorf("unsupported data command 0x%02X", command)
|
||||
}
|
||||
body := encodeTime(at)
|
||||
units := 0
|
||||
if unit, ok := wholeVehicleUnit(record); ok {
|
||||
body = append(body, 0x01)
|
||||
body = append(body, unit...)
|
||||
units++
|
||||
}
|
||||
if unit, ok := motorUnit(record); ok {
|
||||
body = append(body, 0x02)
|
||||
body = append(body, unit...)
|
||||
units++
|
||||
}
|
||||
if unit, ok := fuelCellUnit(record); ok {
|
||||
body = append(body, 0x03)
|
||||
body = append(body, unit...)
|
||||
units++
|
||||
}
|
||||
if unit, ok := positionUnit(record); ok {
|
||||
body = append(body, 0x05)
|
||||
body = append(body, unit...)
|
||||
units++
|
||||
}
|
||||
if unit, ok := extremeUnit(record); ok {
|
||||
body = append(body, 0x06)
|
||||
body = append(body, unit...)
|
||||
units++
|
||||
}
|
||||
if unit, ok := alarmUnit(record); ok {
|
||||
body = append(body, 0x07)
|
||||
body = append(body, unit...)
|
||||
units++
|
||||
}
|
||||
for _, unit := range voltageUnits(record) {
|
||||
body = append(body, 0x08)
|
||||
body = append(body, unit...)
|
||||
units++
|
||||
}
|
||||
for _, unit := range temperatureUnits(record) {
|
||||
body = append(body, 0x09)
|
||||
body = append(body, unit...)
|
||||
units++
|
||||
}
|
||||
if units == 0 {
|
||||
return nil, errors.New("source record has no mappable GB/T 32960 units")
|
||||
}
|
||||
return buildFrame('#', command, 0xFE, vin, body)
|
||||
}
|
||||
|
||||
func LoginFrame(platformID, username, password string, serial uint16, now time.Time) ([]byte, error) {
|
||||
if len(username) > 12 {
|
||||
return nil, errors.New("GB/T 32960 platform username exceeds 12 bytes")
|
||||
}
|
||||
if len(password) > 20 {
|
||||
return nil, errors.New("GB/T 32960 platform password exceeds 20 bytes")
|
||||
}
|
||||
body := encodeTime(now)
|
||||
body = binary.BigEndian.AppendUint16(body, serial)
|
||||
body = appendPaddedASCII(body, username, 12)
|
||||
body = appendPaddedASCII(body, password, 20)
|
||||
body = append(body, 0x01)
|
||||
return buildFrame('#', CommandLogin, 0xFE, platformID, body)
|
||||
}
|
||||
|
||||
func buildFrame(start, command, response byte, vin string, body []byte) ([]byte, error) {
|
||||
if len(vin) != 17 {
|
||||
return nil, fmt.Errorf("GB/T 32960 identifier must be exactly 17 bytes, got %d", len(vin))
|
||||
}
|
||||
if len(body) > math.MaxUint16 {
|
||||
return nil, errors.New("GB/T 32960 body exceeds 65535 bytes")
|
||||
}
|
||||
frame := make([]byte, 24, 25+len(body))
|
||||
frame[0], frame[1] = start, start
|
||||
frame[2], frame[3] = command, response
|
||||
copy(frame[4:21], vin)
|
||||
frame[21] = 0x01
|
||||
binary.BigEndian.PutUint16(frame[22:24], uint16(len(body)))
|
||||
frame = append(frame, body...)
|
||||
frame = append(frame, bcc(frame[2:]))
|
||||
return frame, nil
|
||||
}
|
||||
|
||||
func wholeVehicleUnit(record Record) ([]byte, bool) {
|
||||
if !hasAny(record, "2201", "2202", "3201", "7615") {
|
||||
return nil, false
|
||||
}
|
||||
out := make([]byte, 20)
|
||||
out[0] = enum(recordValue(record, "3201"), map[string]byte{
|
||||
"启动": 1, "启动状态": 1, "行驶": 1, "熄火": 2, "熄火状态": 2, "其他": 3,
|
||||
}, 0xFE)
|
||||
out[1] = enum(recordValue(record, "2301"), map[string]byte{
|
||||
"停车充电": 1, "行驶充电": 2, "未充电": 3, "未充电状态": 3, "充电完成": 4,
|
||||
}, 0xFE)
|
||||
out[2] = enum(recordValue(record, "2213"), map[string]byte{
|
||||
"纯电": 1, "纯电动": 1, "混动": 2, "混合动力": 2, "燃油": 3,
|
||||
}, 0xFE)
|
||||
putScaledU16(out[3:5], recordValue(record, "2201"), 10, 0)
|
||||
putScaledU32(out[5:9], recordValue(record, "2202"), 10)
|
||||
putScaledU16(out[9:11], recordValue(record, "2613"), 10, 0)
|
||||
putScaledU16(out[11:13], recordValue(record, "2614"), 10, 1000)
|
||||
out[13] = byteValue(recordValue(record, "7615"))
|
||||
out[14] = enum(recordValue(record, "2214"), map[string]byte{"工作": 1, "断开": 2}, 0xFE)
|
||||
out[15] = gearValue(firstField(recordValue(record, "2203")))
|
||||
putU16(out[16:18], recordValue(record, "2617"))
|
||||
out[18] = byteValue(recordValue(record, "2208"))
|
||||
out[19] = byteValue(recordValue(record, "2209"))
|
||||
return out, true
|
||||
}
|
||||
|
||||
func motorUnit(record Record) ([]byte, bool) {
|
||||
// The source carries every motor as a key:value composite separated by "|".
|
||||
// Fields are the GB/T 32960 sequence numbers exposed by the platform metadata.
|
||||
composite := recordValue(record, "2308")
|
||||
if composite == "" {
|
||||
return nil, false
|
||||
}
|
||||
groups := parseCompositeGroups(composite)
|
||||
if len(groups) == 0 || len(groups) > 253 {
|
||||
return nil, false
|
||||
}
|
||||
out := []byte{byte(len(groups))}
|
||||
for index, group := range groups {
|
||||
out = append(out, byteValue(firstNonempty(group["2302"], strconv.Itoa(index+1))))
|
||||
out = append(out, enum(group["2303"], map[string]byte{
|
||||
"耗电": 1, "发电": 2, "关闭": 3, "准备": 4, "准备状态": 4,
|
||||
}, 0xFE))
|
||||
out = append(out, tempByte(group["2304"]))
|
||||
out = binary.BigEndian.AppendUint16(out, offsetU16(group["2305"], 1, 20000))
|
||||
out = binary.BigEndian.AppendUint16(out, offsetU16(group["2306"], 10, 2000))
|
||||
out = append(out, tempByte(group["2309"]))
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(group["2311"], 10, 0))
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(group["2312"], 10, 1000))
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func fuelCellUnit(record Record) ([]byte, bool) {
|
||||
if !hasAny(record, "2110", "2111", "2112", "2117", "2119") {
|
||||
return nil, false
|
||||
}
|
||||
temperatureGroups := parseSeriesGroups(recordValue(record, "2103"))
|
||||
var temperatures []string
|
||||
for _, group := range temperatureGroups {
|
||||
temperatures = append(temperatures, group.values...)
|
||||
}
|
||||
if len(temperatures) > math.MaxUint16 {
|
||||
temperatures = temperatures[:math.MaxUint16]
|
||||
}
|
||||
out := binary.BigEndian.AppendUint16(nil, scaledU16(recordValue(record, "2110"), 10, 0))
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(recordValue(record, "2111"), 10, 0))
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(recordValue(record, "2112"), 100, 0))
|
||||
out = binary.BigEndian.AppendUint16(out, uint16(len(temperatures)))
|
||||
for _, value := range temperatures {
|
||||
out = append(out, tempByte(value))
|
||||
}
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(recordValue(record, "2115"), 10, 40))
|
||||
out = append(out, byteValue(recordValue(record, "2116")))
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(recordValue(record, "2117"), 1, 0))
|
||||
out = append(out, byteValue(recordValue(record, "2118")))
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(recordValue(record, "2119"), 10, 0))
|
||||
out = append(out, byteValue(recordValue(record, "2120")))
|
||||
out = append(out, enum(recordValue(record, "2121"), map[string]byte{"工作": 1, "断开": 2}, 0xFE))
|
||||
return out, true
|
||||
}
|
||||
|
||||
func positionUnit(record Record) ([]byte, bool) {
|
||||
longitude, lonOK := floatValue(recordValue(record, "2502"))
|
||||
latitude, latOK := floatValue(recordValue(record, "2503"))
|
||||
if !lonOK || !latOK || longitude < 0 || latitude < 0 {
|
||||
return nil, false
|
||||
}
|
||||
status := byte(0)
|
||||
text := strings.TrimSpace(recordValue(record, "2501"))
|
||||
if text != "" && (strings.Contains(text, "无效") || text == "1") {
|
||||
status = 1
|
||||
}
|
||||
out := []byte{status}
|
||||
out = binary.BigEndian.AppendUint32(out, uint32(math.Round(longitude*1_000_000)))
|
||||
out = binary.BigEndian.AppendUint32(out, uint32(math.Round(latitude*1_000_000)))
|
||||
return out, true
|
||||
}
|
||||
|
||||
func extremeUnit(record Record) ([]byte, bool) {
|
||||
if !hasAny(record, "2601", "2602", "2603", "2604", "2605", "2606", "2607", "2608", "2609", "2610", "2611", "2612") {
|
||||
return nil, false
|
||||
}
|
||||
out := []byte{
|
||||
byteValue(recordValue(record, "2601")),
|
||||
byteValue(recordValue(record, "2602")),
|
||||
}
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(recordValue(record, "2603"), 1000, 0))
|
||||
out = append(out, byteValue(recordValue(record, "2604")), byteValue(recordValue(record, "2605")))
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(recordValue(record, "2606"), 1000, 0))
|
||||
out = append(out,
|
||||
byteValue(recordValue(record, "2607")),
|
||||
byteValue(recordValue(record, "2608")),
|
||||
tempByte(recordValue(record, "2609")),
|
||||
byteValue(recordValue(record, "2610")),
|
||||
byteValue(recordValue(record, "2611")),
|
||||
tempByte(recordValue(record, "2612")),
|
||||
)
|
||||
return out, true
|
||||
}
|
||||
|
||||
func alarmUnit(record Record) ([]byte, bool) {
|
||||
levelRaw := recordValue(record, "2900", "2901")
|
||||
var general uint32
|
||||
for bit := 0; bit < 32; bit++ {
|
||||
value := recordValue(record, strconv.Itoa(2901+bit))
|
||||
if truthy(value) {
|
||||
general |= 1 << bit
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(levelRaw) == "" && general == 0 {
|
||||
return nil, false
|
||||
}
|
||||
out := []byte{byteValue(levelRaw)}
|
||||
out = binary.BigEndian.AppendUint32(out, general)
|
||||
out = append(out, 0, 0, 0, 0)
|
||||
return out, true
|
||||
}
|
||||
|
||||
func voltageUnits(record Record) [][]byte {
|
||||
raw := recordValue(record, "2003", "batteryVoltages")
|
||||
groups := parseSeriesGroups(raw)
|
||||
var units [][]byte
|
||||
for _, group := range groups {
|
||||
for start := 0; start < len(group.values); start += 255 {
|
||||
end := start + 255
|
||||
if end > len(group.values) {
|
||||
end = len(group.values)
|
||||
}
|
||||
out := []byte{1, byte(group.id)}
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(recordValue(record, "2613"), 10, 0))
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(recordValue(record, "2614"), 10, 1000))
|
||||
out = binary.BigEndian.AppendUint16(out, uint16(len(group.values)))
|
||||
out = binary.BigEndian.AppendUint16(out, uint16(start+1))
|
||||
out = append(out, byte(end-start))
|
||||
for _, value := range group.values[start:end] {
|
||||
out = binary.BigEndian.AppendUint16(out, scaledU16(value, 1000, 0))
|
||||
}
|
||||
units = append(units, out)
|
||||
}
|
||||
}
|
||||
return units
|
||||
}
|
||||
|
||||
func temperatureUnits(record Record) [][]byte {
|
||||
groups := parseSeriesGroups(recordValue(record, "2103", "batteryTemperatures"))
|
||||
var units [][]byte
|
||||
for _, group := range groups {
|
||||
for start := 0; start < len(group.values); start += math.MaxUint16 {
|
||||
end := start + math.MaxUint16
|
||||
if end > len(group.values) {
|
||||
end = len(group.values)
|
||||
}
|
||||
out := []byte{1, byte(group.id)}
|
||||
out = binary.BigEndian.AppendUint16(out, uint16(end-start))
|
||||
for _, value := range group.values[start:end] {
|
||||
out = append(out, tempByte(value))
|
||||
}
|
||||
units = append(units, out)
|
||||
}
|
||||
}
|
||||
return units
|
||||
}
|
||||
|
||||
func parseCompositeGroups(raw string) []map[string]string {
|
||||
var groups []map[string]string
|
||||
for _, encoded := range strings.Split(raw, "|") {
|
||||
group := map[string]string{}
|
||||
for _, field := range strings.Split(encoded, ",") {
|
||||
key, value, found := strings.Cut(field, ":")
|
||||
if found {
|
||||
group[strings.TrimSpace(key)] = strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
if len(group) > 0 {
|
||||
groups = append(groups, group)
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
type seriesGroup struct {
|
||||
id int
|
||||
values []string
|
||||
}
|
||||
|
||||
func parseSeriesGroups(raw string) []seriesGroup {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil
|
||||
}
|
||||
var groups []seriesGroup
|
||||
for index, part := range strings.FieldsFunc(raw, func(r rune) bool { return r == ';' || r == '|' }) {
|
||||
group := seriesGroup{id: index + 1}
|
||||
if before, after, found := strings.Cut(part, ":"); found {
|
||||
if parsed, err := strconv.Atoi(strings.TrimSpace(before)); err == nil && parsed > 0 && parsed <= 255 {
|
||||
group.id = parsed
|
||||
}
|
||||
part = after
|
||||
}
|
||||
for _, value := range strings.FieldsFunc(part, func(r rune) bool {
|
||||
return r == '_' || r == ',' || r == ' ' || r == '[' || r == ']'
|
||||
}) {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
group.values = append(group.values, strings.TrimSpace(value))
|
||||
}
|
||||
}
|
||||
if len(group.values) > 0 {
|
||||
groups = append(groups, group)
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
func recordValue(record Record, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if value := strings.TrimSpace(record[key]); value != "" && value != "--" && value != "null" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func firstField(value string) string {
|
||||
fields := strings.Fields(value)
|
||||
if len(fields) == 0 {
|
||||
return ""
|
||||
}
|
||||
return fields[0]
|
||||
}
|
||||
|
||||
func firstNonempty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func hasAny(record Record, keys ...string) bool { return recordValue(record, keys...) != "" }
|
||||
|
||||
func floatValue(raw string) (float64, bool) {
|
||||
raw = strings.TrimSpace(strings.TrimSuffix(raw, "%"))
|
||||
if raw == "" {
|
||||
return 0, false
|
||||
}
|
||||
value, err := strconv.ParseFloat(raw, 64)
|
||||
return value, err == nil && !math.IsNaN(value) && !math.IsInf(value, 0)
|
||||
}
|
||||
|
||||
func byteValue(raw string) byte {
|
||||
value, ok := floatValue(raw)
|
||||
if !ok || value < 0 || value > 253 {
|
||||
return 0xFE
|
||||
}
|
||||
return byte(math.Round(value))
|
||||
}
|
||||
|
||||
func tempByte(raw string) byte {
|
||||
value, ok := floatValue(raw)
|
||||
if !ok || value < -40 || value > 210 {
|
||||
return 0xFE
|
||||
}
|
||||
return byte(math.Round(value + 40))
|
||||
}
|
||||
|
||||
func putU16(out []byte, raw string) { binary.BigEndian.PutUint16(out, scaledU16(raw, 1, 0)) }
|
||||
|
||||
func putScaledU16(out []byte, raw string, scale, offset float64) {
|
||||
binary.BigEndian.PutUint16(out, scaledU16(raw, scale, offset))
|
||||
}
|
||||
|
||||
func putScaledU32(out []byte, raw string, scale float64) {
|
||||
value, ok := floatValue(raw)
|
||||
if !ok || value < 0 || value*scale > math.MaxUint32-2 {
|
||||
binary.BigEndian.PutUint32(out, 0xFFFFFFFE)
|
||||
return
|
||||
}
|
||||
binary.BigEndian.PutUint32(out, uint32(math.Round(value*scale)))
|
||||
}
|
||||
|
||||
func scaledU16(raw string, scale, offset float64) uint16 {
|
||||
value, ok := floatValue(raw)
|
||||
encoded := (value + offset) * scale
|
||||
if !ok || encoded < 0 || encoded > math.MaxUint16-2 {
|
||||
return 0xFFFE
|
||||
}
|
||||
return uint16(math.Round(encoded))
|
||||
}
|
||||
|
||||
func offsetU16(raw string, scale, offset float64) uint16 {
|
||||
return scaledU16(raw, scale, offset)
|
||||
}
|
||||
|
||||
func enum(raw string, values map[string]byte, missing byte) byte {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return missing
|
||||
}
|
||||
if numeric, err := strconv.ParseUint(raw, 10, 8); err == nil {
|
||||
return byte(numeric)
|
||||
}
|
||||
for label, value := range values {
|
||||
if raw == label || strings.Contains(raw, label) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return missing
|
||||
}
|
||||
|
||||
func gearValue(raw string) byte {
|
||||
raw = strings.ToUpper(strings.TrimSpace(raw))
|
||||
switch raw {
|
||||
case "P", "P档":
|
||||
return 15
|
||||
case "R", "R档":
|
||||
return 13
|
||||
case "N", "N档":
|
||||
return 0
|
||||
case "D", "D档":
|
||||
return 14
|
||||
}
|
||||
raw = strings.TrimSuffix(raw, "档")
|
||||
raw = strings.TrimPrefix(raw, "D")
|
||||
return byteValue(raw)
|
||||
}
|
||||
|
||||
func truthy(raw string) bool {
|
||||
raw = strings.ToLower(strings.TrimSpace(raw))
|
||||
return raw != "" && raw != "0" && raw != "false" && raw != "无" && raw != "正常"
|
||||
}
|
||||
|
||||
func appendPaddedASCII(out []byte, value string, width int) []byte {
|
||||
start := len(out)
|
||||
out = append(out, make([]byte, width)...)
|
||||
copy(out[start:start+width], value)
|
||||
return out
|
||||
}
|
||||
|
||||
func encodeTime(value time.Time) []byte {
|
||||
local := value.In(shanghai)
|
||||
return []byte{
|
||||
byte(local.Year() - 2000), byte(local.Month()), byte(local.Day()),
|
||||
byte(local.Hour()), byte(local.Minute()), byte(local.Second()),
|
||||
}
|
||||
}
|
||||
|
||||
func bcc(value []byte) byte {
|
||||
var result byte
|
||||
for _, current := range value {
|
||||
result ^= current
|
||||
}
|
||||
return result
|
||||
}
|
||||
93
go/vehicle-gateway/internal/feichibridge/encoder_test.go
Normal file
93
go/vehicle-gateway/internal/feichibridge/encoder_test.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lingniu-vehicle-ingest/go/vehicle-gateway/internal/protocol/gb32960"
|
||||
)
|
||||
|
||||
func TestDataFrameMapsFeichiFields(t *testing.T) {
|
||||
at := time.Date(2026, 7, 17, 14, 5, 6, 0, shanghai)
|
||||
record := Record{
|
||||
"2000": "2026-07-17 14:05:06",
|
||||
"2201": "42.3", "2202": "12345.6", "2203": "D 0 0",
|
||||
"2208": "35", "2209": "0", "2213": "纯电",
|
||||
"2214": "工作", "2301": "未充电状态", "3201": "启动状态",
|
||||
"2613": "550.2", "2614": "-20.5", "2617": "2200", "7615": "78",
|
||||
"2501": "有效定位", "2502": "113.2644", "2503": "23.1291",
|
||||
"2601": "1", "2602": "8", "2603": "3.955",
|
||||
"2604": "1", "2605": "26", "2606": "3.821",
|
||||
"2607": "1", "2608": "3", "2609": "48",
|
||||
"2610": "1", "2611": "9", "2612": "37",
|
||||
"2003": "1:3.900_3.901_3.902",
|
||||
"2103": "1:35_36_37",
|
||||
}
|
||||
frame, err := (Encoder{}).DataFrame(CommandRealtime, "LTEST32960VIN0001", at, record)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env, err := gb32960.ParseFrame(frame, at.UnixMilli(), "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if env.MessageID != "0x02" || env.VIN != "LTEST32960VIN0001" {
|
||||
t.Fatalf("unexpected envelope: %#v", env)
|
||||
}
|
||||
if got := env.Fields["speed_kmh"]; got != 42.3 {
|
||||
t.Fatalf("speed = %#v", got)
|
||||
}
|
||||
if got := env.Fields["total_mileage_km"]; got != 12345.6 {
|
||||
t.Fatalf("mileage = %#v", got)
|
||||
}
|
||||
if got := env.Fields["soc_percent"]; got != 78 {
|
||||
t.Fatalf("soc = %#v", got)
|
||||
}
|
||||
if got := env.Fields["longitude"]; got != 113.2644 {
|
||||
t.Fatalf("longitude = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDataFrameSplitsMoreThan255CellVoltages(t *testing.T) {
|
||||
values := make([]string, 288)
|
||||
for index := range values {
|
||||
values[index] = fmt.Sprintf("%.3f", 3.5+float64(index)/1000)
|
||||
}
|
||||
frame, err := (Encoder{}).DataFrame(CommandReissue, "LTEST32960VIN0002", time.Now(), Record{
|
||||
"2003": "1:" + strings.Join(values, "_"),
|
||||
"2613": "530",
|
||||
"2614": "10",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := frame[24 : len(frame)-1]
|
||||
if got := strings.Count(string(body), string([]byte{0x08})); got < 2 {
|
||||
t.Fatalf("expected at least two voltage units, got %d", got)
|
||||
}
|
||||
if binary.BigEndian.Uint16(frame[22:24]) != uint16(len(body)) {
|
||||
t.Fatal("body length mismatch")
|
||||
}
|
||||
if _, err := gb32960.ParseFrame(frame, time.Now().UnixMilli(), "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginFrameLayout(t *testing.T) {
|
||||
frame, err := LoginFrame("FEICHIBRIDGE00001", "bridge", "secret", 7, time.Date(2026, 7, 17, 1, 2, 3, 0, shanghai))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if frame[2] != CommandLogin || frame[3] != 0xFE {
|
||||
t.Fatalf("unexpected login header: %x", frame[:4])
|
||||
}
|
||||
if got := binary.BigEndian.Uint16(frame[30:32]); got != 7 {
|
||||
t.Fatalf("serial = %d", got)
|
||||
}
|
||||
if got, want := frame[len(frame)-1], bcc(frame[2:len(frame)-1]); got != want {
|
||||
t.Fatalf("BCC = %x, want %x", got, want)
|
||||
}
|
||||
}
|
||||
209
go/vehicle-gateway/internal/feichibridge/login.go
Normal file
209
go/vehicle-gateway/internal/feichibridge/login.go
Normal file
@@ -0,0 +1,209 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const feichiPublicKey = `-----BEGIN PUBLIC KEY-----
|
||||
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOwmFtEk1oJxDU0NI4kVO0Jx0X
|
||||
nt+Abx+JKGUzcRzPwjUkd5z9Ice5rh87CCmj0XjZ5pPac6TtA3f0v5FqiK/kjQY5
|
||||
XMLti4weJ4dcp1/q1O7PCYxRX8WgetGxwsjxGn+uoZOZkclN1PFS4wRnKEso6+G/
|
||||
e60QGB29cZoo4jZnZwIDAQAB
|
||||
-----END PUBLIC KEY-----`
|
||||
|
||||
type LoginCredentials struct {
|
||||
Username string
|
||||
Password string
|
||||
MaxAttempts int
|
||||
RetryDelay time.Duration
|
||||
}
|
||||
|
||||
type loginSession struct {
|
||||
credentials LoginCredentials
|
||||
solver CaptchaSolver
|
||||
mu sync.Mutex
|
||||
ready atomic.Bool
|
||||
csrf atomic.Value
|
||||
token atomic.Value
|
||||
}
|
||||
|
||||
type firstLoginEnvelope struct {
|
||||
Code any `json:"code"`
|
||||
}
|
||||
|
||||
type captchaPayload struct {
|
||||
Src string `json:"src"`
|
||||
}
|
||||
|
||||
type loginPayload struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
func newLoginSession(credentials LoginCredentials, solver CaptchaSolver) (*loginSession, error) {
|
||||
credentials.Username = strings.TrimSpace(credentials.Username)
|
||||
if credentials.Username == "" || credentials.Password == "" {
|
||||
return nil, errors.New("Feichi username and password are required")
|
||||
}
|
||||
if solver == nil {
|
||||
return nil, errors.New("captcha solver is required")
|
||||
}
|
||||
if credentials.MaxAttempts <= 0 {
|
||||
credentials.MaxAttempts = 20
|
||||
}
|
||||
if credentials.RetryDelay <= 0 {
|
||||
credentials.RetryDelay = time.Second
|
||||
}
|
||||
session := &loginSession{credentials: credentials, solver: solver}
|
||||
session.csrf.Store("")
|
||||
session.token.Store("")
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *loginSession) invalidate() {
|
||||
s.ready.Store(false)
|
||||
}
|
||||
|
||||
func (s *loginSession) cookieHeader() string {
|
||||
var cookies []string
|
||||
if csrf := s.csrf.Load().(string); csrf != "" {
|
||||
cookies = append(cookies, "CSRF="+csrf)
|
||||
}
|
||||
if token := s.token.Load().(string); token != "" {
|
||||
cookies = append(cookies, "R_SESS="+token)
|
||||
}
|
||||
return strings.Join(cookies, "; ")
|
||||
}
|
||||
|
||||
func (s *loginSession) csrfHeader() string {
|
||||
return s.csrf.Load().(string)
|
||||
}
|
||||
|
||||
func (s *loginSession) ensure(ctx context.Context, client *APIClient) error {
|
||||
if s.ready.Load() {
|
||||
return nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.ready.Load() {
|
||||
return nil
|
||||
}
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= s.credentials.MaxAttempts; attempt++ {
|
||||
if err := s.loginAttempt(ctx, client); err == nil {
|
||||
s.ready.Store(true)
|
||||
return nil
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
if attempt < s.credentials.MaxAttempts {
|
||||
timer := time.NewTimer(s.credentials.RetryDelay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("Feichi automatic login failed after %d attempts: %w", s.credentials.MaxAttempts, lastErr)
|
||||
}
|
||||
|
||||
func (s *loginSession) loginAttempt(ctx context.Context, client *APIClient) error {
|
||||
s.ready.Store(false)
|
||||
s.token.Store("")
|
||||
var first firstLoginEnvelope
|
||||
headers, err := client.rawJSON(ctx, http.MethodGet, "api/v1/first-login", nil, &first)
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialize login session: %w", err)
|
||||
}
|
||||
if !apiCodeOK(first.Code) {
|
||||
return apiCodeError(first.Code)
|
||||
}
|
||||
csrf := strings.TrimSpace(headers.Get("x-api-csrf"))
|
||||
if csrf == "" {
|
||||
for _, rawCookie := range headers.Values("Set-Cookie") {
|
||||
cookie, parseErr := http.ParseSetCookie(rawCookie)
|
||||
if parseErr == nil && cookie.Name == "CSRF" {
|
||||
csrf = cookie.Value
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if csrf == "" {
|
||||
return errors.New("first-login response did not provide CSRF")
|
||||
}
|
||||
s.csrf.Store(csrf)
|
||||
|
||||
var captcha objectEnvelope[captchaPayload]
|
||||
if _, err := client.rawJSON(ctx, http.MethodGet, "api/v1/login/randCode", nil, &captcha); err != nil {
|
||||
return fmt.Errorf("request captcha: %w", err)
|
||||
}
|
||||
if !apiCodeOK(captcha.Code) {
|
||||
return apiCodeError(captcha.Code)
|
||||
}
|
||||
encodedImage := captcha.Data.Src
|
||||
if comma := strings.IndexByte(encodedImage, ','); comma >= 0 {
|
||||
encodedImage = encodedImage[comma+1:]
|
||||
}
|
||||
image, err := base64.StdEncoding.DecodeString(encodedImage)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode captcha image: %w", err)
|
||||
}
|
||||
validCode, err := s.solver.Solve(ctx, image)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
encrypted, err := encryptFeichiPassword(s.credentials.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var login objectEnvelope[loginPayload]
|
||||
if _, err := client.rawJSON(ctx, http.MethodPost, "api/v1/login", map[string]string{
|
||||
"username": s.credentials.Username,
|
||||
"password": encrypted,
|
||||
"validCode": validCode,
|
||||
}, &login); err != nil {
|
||||
return fmt.Errorf("submit login: %w", err)
|
||||
}
|
||||
if !apiCodeOK(login.Code) {
|
||||
return apiCodeError(login.Code)
|
||||
}
|
||||
token := strings.TrimSpace(login.Data.Token)
|
||||
if token == "" {
|
||||
return errors.New("login succeeded without R_SESS token")
|
||||
}
|
||||
s.token.Store(token)
|
||||
return nil
|
||||
}
|
||||
|
||||
func encryptFeichiPassword(password string) (string, error) {
|
||||
block, _ := pem.Decode([]byte(feichiPublicKey))
|
||||
if block == nil {
|
||||
return "", errors.New("decode Feichi RSA public key")
|
||||
}
|
||||
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse Feichi RSA public key: %w", err)
|
||||
}
|
||||
publicKey, ok := parsed.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return "", errors.New("Feichi public key is not RSA")
|
||||
}
|
||||
encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, []byte(password))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("encrypt Feichi password: %w", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(encrypted), nil
|
||||
}
|
||||
94
go/vehicle-gateway/internal/feichibridge/model.go
Normal file
94
go/vehicle-gateway/internal/feichibridge/model.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var shanghai = time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
|
||||
type Vehicle struct {
|
||||
VehicleID string `json:"vehicleId"`
|
||||
VIN string `json:"vin"`
|
||||
OnlineStatus any `json:"onlineStatus"`
|
||||
UpdateTime string `json:"updateTime"`
|
||||
RuleTypeName string `json:"ruleTypeName"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
VehicleID string `json:"vehicleId"`
|
||||
VIN string `json:"vin"`
|
||||
DataItems map[string]string `json:"dataItems"`
|
||||
}
|
||||
|
||||
type Record map[string]string
|
||||
|
||||
type collectionEnvelope[T any] struct {
|
||||
Code any `json:"code"`
|
||||
Data []T `json:"data"`
|
||||
}
|
||||
|
||||
type objectEnvelope[T any] struct {
|
||||
Code any `json:"code"`
|
||||
Data T `json:"data"`
|
||||
}
|
||||
|
||||
type historySegment struct {
|
||||
Subdata []Record `json:"subdata"`
|
||||
}
|
||||
|
||||
func apiCodeOK(code any) bool {
|
||||
switch value := code.(type) {
|
||||
case nil:
|
||||
return true
|
||||
case float64:
|
||||
return value == 0 || value == 200
|
||||
case string:
|
||||
return value == "" || value == "0" || value == "200"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func recordTime(record Record) (time.Time, error) {
|
||||
for _, key := range []string{"2000", "9999", "dataTime", "updateTime", "time"} {
|
||||
if raw := strings.TrimSpace(record[key]); raw != "" {
|
||||
return parseSourceTime(raw)
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("source record has no timestamp")
|
||||
}
|
||||
|
||||
func parseSourceTime(raw string) (time.Time, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
for _, layout := range []string{
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02T15:04:05",
|
||||
time.RFC3339Nano,
|
||||
} {
|
||||
if layout == time.RFC3339Nano {
|
||||
if parsed, err := time.Parse(layout, raw); err == nil {
|
||||
return parsed, nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
if parsed, err := time.ParseInLocation(layout, raw, shanghai); err == nil {
|
||||
return parsed, nil
|
||||
}
|
||||
}
|
||||
if unixMS, err := strconv.ParseInt(raw, 10, 64); err == nil {
|
||||
if unixMS < 10_000_000_000 {
|
||||
return time.Unix(unixMS, 0).In(shanghai), nil
|
||||
}
|
||||
return time.UnixMilli(unixMS).In(shanghai), nil
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("unsupported source timestamp %q", raw)
|
||||
}
|
||||
|
||||
func canonicalHash(record Record) string {
|
||||
encoded, _ := json.Marshal(record)
|
||||
return hashBytes(encoded)
|
||||
}
|
||||
469
go/vehicle-gateway/internal/feichibridge/service.go
Normal file
469
go/vehicle-gateway/internal/feichibridge/service.go
Normal file
@@ -0,0 +1,469 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"lingniu-vehicle-ingest/go/vehicle-gateway/internal/metrics"
|
||||
)
|
||||
|
||||
type Source interface {
|
||||
Vehicles(context.Context) ([]Vehicle, error)
|
||||
Snapshot(context.Context, string) (Snapshot, error)
|
||||
History(context.Context, string, time.Time, time.Time) ([]Record, error)
|
||||
}
|
||||
|
||||
type FrameTarget interface {
|
||||
Connect(context.Context) error
|
||||
Send(context.Context, []byte) error
|
||||
Close() error
|
||||
LastACK() time.Time
|
||||
}
|
||||
|
||||
type ServiceConfig struct {
|
||||
PollInterval time.Duration
|
||||
DiscoveryInterval time.Duration
|
||||
BackfillInterval time.Duration
|
||||
BackfillLookback time.Duration
|
||||
BackfillWindow time.Duration
|
||||
BackfillSafetyLag time.Duration
|
||||
SourceStaleAfter time.Duration
|
||||
FetchConcurrency int
|
||||
BackfillEnabled bool
|
||||
StaleReissueEnabled bool
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
config ServiceConfig
|
||||
source Source
|
||||
target FrameTarget
|
||||
state *StateStore
|
||||
encoder Encoder
|
||||
logger *slog.Logger
|
||||
metrics *metrics.Registry
|
||||
|
||||
mu sync.RWMutex
|
||||
vehicles []Vehicle
|
||||
lastSourceSuccess time.Time
|
||||
lastError error
|
||||
}
|
||||
|
||||
func NewService(config ServiceConfig, source Source, target FrameTarget, state *StateStore, logger *slog.Logger, registry *metrics.Registry) (*Service, error) {
|
||||
if source == nil || target == nil || state == nil {
|
||||
return nil, errors.New("source, target, and state are required")
|
||||
}
|
||||
if config.PollInterval <= 0 {
|
||||
config.PollInterval = 10 * time.Second
|
||||
}
|
||||
if config.DiscoveryInterval <= 0 {
|
||||
config.DiscoveryInterval = 5 * time.Minute
|
||||
}
|
||||
if config.BackfillInterval <= 0 {
|
||||
config.BackfillInterval = time.Hour
|
||||
}
|
||||
if config.BackfillLookback <= 0 {
|
||||
config.BackfillLookback = time.Hour
|
||||
}
|
||||
if config.BackfillWindow <= 0 {
|
||||
config.BackfillWindow = 20 * time.Minute
|
||||
}
|
||||
if config.BackfillSafetyLag <= 0 {
|
||||
config.BackfillSafetyLag = 30 * time.Second
|
||||
}
|
||||
if config.SourceStaleAfter <= 0 {
|
||||
config.SourceStaleAfter = 2 * time.Minute
|
||||
}
|
||||
if config.FetchConcurrency <= 0 {
|
||||
config.FetchConcurrency = 4
|
||||
}
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &Service{
|
||||
config: config, source: source, target: target, state: state,
|
||||
logger: logger, metrics: registry,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) Run(ctx context.Context) error {
|
||||
if err := s.target.Connect(ctx); err != nil {
|
||||
s.setError(err)
|
||||
return fmt.Errorf("connect GB/T 32960 target: %w", err)
|
||||
}
|
||||
if err := s.discover(ctx); err != nil {
|
||||
s.setError(err)
|
||||
return fmt.Errorf("initial vehicle discovery: %w", err)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.discoveryLoop(ctx)
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.realtimeLoop(ctx)
|
||||
}()
|
||||
if s.config.BackfillEnabled {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.backfillLoop(ctx)
|
||||
}()
|
||||
}
|
||||
<-ctx.Done()
|
||||
_ = s.target.Close()
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) Ready(context.Context) error {
|
||||
s.mu.RLock()
|
||||
lastSourceSuccess := s.lastSourceSuccess
|
||||
lastErr := s.lastError
|
||||
s.mu.RUnlock()
|
||||
maxSourceAge := max(3*s.config.PollInterval, time.Minute)
|
||||
if lastSourceSuccess.IsZero() || time.Since(lastSourceSuccess) > maxSourceAge {
|
||||
if lastErr != nil {
|
||||
return fmt.Errorf("source unavailable: %w", lastErr)
|
||||
}
|
||||
return errors.New("source has not completed a successful request")
|
||||
}
|
||||
lastACK := s.target.LastACK()
|
||||
if lastACK.IsZero() || time.Since(lastACK) > max(3*s.config.DiscoveryInterval, 10*time.Minute) {
|
||||
return errors.New("GB/T 32960 target has no recent ACK")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) discoveryLoop(ctx context.Context) {
|
||||
ticker := time.NewTicker(s.config.DiscoveryInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := s.discover(ctx); err != nil {
|
||||
s.recordFailure("discover", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) realtimeLoop(ctx context.Context) {
|
||||
s.pollRealtime(ctx)
|
||||
ticker := time.NewTicker(s.config.PollInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.pollRealtime(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) backfillLoop(ctx context.Context) {
|
||||
s.runBackfill(ctx)
|
||||
ticker := time.NewTicker(s.config.BackfillInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.runBackfill(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) discover(ctx context.Context) error {
|
||||
start := time.Now()
|
||||
vehicles, err := s.source.Vehicles(ctx)
|
||||
s.observeAPI("vehicles", start, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
filtered := make([]Vehicle, 0, len(vehicles))
|
||||
for _, vehicle := range vehicles {
|
||||
vehicle.VIN = strings.TrimSpace(vehicle.VIN)
|
||||
vehicle.VehicleID = strings.TrimSpace(vehicle.VehicleID)
|
||||
if len(vehicle.VIN) != 17 || vehicle.VehicleID == "" {
|
||||
continue
|
||||
}
|
||||
if vehicle.RuleTypeName != "" && !strings.Contains(strings.ToUpper(vehicle.RuleTypeName), "32960") {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, vehicle)
|
||||
}
|
||||
sort.Slice(filtered, func(i, j int) bool { return filtered[i].VIN < filtered[j].VIN })
|
||||
s.mu.Lock()
|
||||
s.vehicles = filtered
|
||||
s.lastSourceSuccess = time.Now()
|
||||
s.lastError = nil
|
||||
s.mu.Unlock()
|
||||
if s.metrics != nil {
|
||||
s.metrics.SetGauge("vehicle_feichi_bridge_vehicles", nil, float64(len(filtered)))
|
||||
}
|
||||
s.logger.Info("feichi vehicles discovered", "count", len(filtered))
|
||||
return nil
|
||||
}
|
||||
|
||||
type fetchedSnapshot struct {
|
||||
vehicle Vehicle
|
||||
record Record
|
||||
at time.Time
|
||||
hash string
|
||||
err error
|
||||
duration time.Duration
|
||||
}
|
||||
|
||||
func (s *Service) pollRealtime(ctx context.Context) {
|
||||
vehicles := s.vehicleSnapshot()
|
||||
jobs := make(chan Vehicle)
|
||||
results := make(chan fetchedSnapshot, len(vehicles))
|
||||
var wg sync.WaitGroup
|
||||
for worker := 0; worker < min(s.config.FetchConcurrency, len(vehicles)); worker++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for vehicle := range jobs {
|
||||
start := time.Now()
|
||||
snapshot, err := s.source.Snapshot(ctx, vehicle.VehicleID)
|
||||
result := fetchedSnapshot{vehicle: vehicle, duration: time.Since(start), err: err}
|
||||
if err == nil {
|
||||
result.record = Record(snapshot.DataItems)
|
||||
result.at, result.err = recordTime(result.record)
|
||||
result.hash = canonicalHash(result.record)
|
||||
}
|
||||
results <- result
|
||||
}
|
||||
}()
|
||||
}
|
||||
for _, vehicle := range vehicles {
|
||||
jobs <- vehicle
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
var snapshots []fetchedSnapshot
|
||||
for result := range results {
|
||||
s.observeAPIWithDuration("snapshot", result.duration, result.err)
|
||||
if result.err != nil {
|
||||
s.recordFailure("snapshot", fmt.Errorf("VIN %s: %w", result.vehicle.VIN, result.err))
|
||||
continue
|
||||
}
|
||||
snapshots = append(snapshots, result)
|
||||
s.markSourceSuccess()
|
||||
}
|
||||
sort.Slice(snapshots, func(i, j int) bool {
|
||||
if snapshots[i].at.Equal(snapshots[j].at) {
|
||||
return snapshots[i].vehicle.VIN < snapshots[j].vehicle.VIN
|
||||
}
|
||||
return snapshots[i].at.Before(snapshots[j].at)
|
||||
})
|
||||
for _, snapshot := range snapshots {
|
||||
if time.Since(snapshot.at) > s.config.SourceStaleAfter {
|
||||
if s.config.StaleReissueEnabled {
|
||||
s.reissueStaleSnapshot(ctx, snapshot)
|
||||
}
|
||||
continue
|
||||
}
|
||||
current := s.state.Vehicle(snapshot.vehicle.VIN)
|
||||
if snapshot.at.Before(current.LastRealtimeTime) ||
|
||||
(snapshot.at.Equal(current.LastRealtimeTime) && snapshot.hash == current.LastRealtimeHash) {
|
||||
continue
|
||||
}
|
||||
frame, err := s.encoder.DataFrame(CommandRealtime, snapshot.vehicle.VIN, snapshot.at, snapshot.record)
|
||||
if err != nil {
|
||||
s.recordFailure("encode", fmt.Errorf("VIN %s: %w", snapshot.vehicle.VIN, err))
|
||||
continue
|
||||
}
|
||||
if err := s.target.Send(ctx, frame); err != nil {
|
||||
s.recordFrame(CommandRealtime, "error", snapshot.vehicle.VIN, snapshot.at)
|
||||
s.recordFailure("send", fmt.Errorf("VIN %s: %w", snapshot.vehicle.VIN, err))
|
||||
continue
|
||||
}
|
||||
if err := s.state.CommitRealtime(snapshot.vehicle.VIN, snapshot.at, snapshot.hash); err != nil {
|
||||
s.recordFailure("state", err)
|
||||
continue
|
||||
}
|
||||
s.recordFrame(CommandRealtime, "acked", snapshot.vehicle.VIN, snapshot.at)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) reissueStaleSnapshot(ctx context.Context, snapshot fetchedSnapshot) {
|
||||
current := s.state.Vehicle(snapshot.vehicle.VIN)
|
||||
if snapshot.at.Before(current.LastSnapshotReissueTime) ||
|
||||
(snapshot.at.Equal(current.LastSnapshotReissueTime) && snapshot.hash == current.LastSnapshotReissueHash) {
|
||||
return
|
||||
}
|
||||
frame, err := s.encoder.DataFrame(CommandReissue, snapshot.vehicle.VIN, snapshot.at, snapshot.record)
|
||||
if err != nil {
|
||||
s.recordFailure("encode_stale_reissue", fmt.Errorf("VIN %s: %w", snapshot.vehicle.VIN, err))
|
||||
return
|
||||
}
|
||||
if err := s.target.Send(ctx, frame); err != nil {
|
||||
s.recordFrame(CommandReissue, "error", snapshot.vehicle.VIN, snapshot.at)
|
||||
s.recordFailure("send_stale_reissue", fmt.Errorf("VIN %s: %w", snapshot.vehicle.VIN, err))
|
||||
return
|
||||
}
|
||||
if err := s.state.CommitSnapshotReissue(snapshot.vehicle.VIN, snapshot.at, snapshot.hash); err != nil {
|
||||
s.recordFailure("state", err)
|
||||
return
|
||||
}
|
||||
s.recordFrame(CommandReissue, "acked", snapshot.vehicle.VIN, snapshot.at)
|
||||
}
|
||||
|
||||
func (s *Service) runBackfill(ctx context.Context) {
|
||||
for _, vehicle := range s.vehicleSnapshot() {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err := s.backfillVehicle(ctx, vehicle); err != nil {
|
||||
s.recordFailure("backfill", fmt.Errorf("VIN %s: %w", vehicle.VIN, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) backfillVehicle(ctx context.Context, vehicle Vehicle) error {
|
||||
end := time.Now().Add(-s.config.BackfillSafetyLag)
|
||||
cursor := s.state.Vehicle(vehicle.VIN).BackfillCursor
|
||||
if cursor.IsZero() {
|
||||
cursor = end.Add(-s.config.BackfillLookback)
|
||||
}
|
||||
for cursor.Before(end) {
|
||||
windowEnd := cursor.Add(s.config.BackfillWindow)
|
||||
if windowEnd.After(end) {
|
||||
windowEnd = end
|
||||
}
|
||||
start := time.Now()
|
||||
records, err := s.source.History(ctx, vehicle.VIN, cursor, windowEnd)
|
||||
s.observeAPI("history", start, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sort.Slice(records, func(i, j int) bool {
|
||||
left, _ := recordTime(records[i])
|
||||
right, _ := recordTime(records[j])
|
||||
return left.Before(right)
|
||||
})
|
||||
committed := cursor
|
||||
for _, record := range records {
|
||||
at, err := recordTime(record)
|
||||
if err != nil || !at.After(cursor) || at.After(windowEnd) {
|
||||
continue
|
||||
}
|
||||
frame, err := s.encoder.DataFrame(CommandReissue, vehicle.VIN, at, record)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.target.Send(ctx, frame); err != nil {
|
||||
s.recordFrame(CommandReissue, "error", vehicle.VIN, at)
|
||||
return err
|
||||
}
|
||||
if err := s.state.CommitBackfill(vehicle.VIN, at); err != nil {
|
||||
return err
|
||||
}
|
||||
s.recordFrame(CommandReissue, "acked", vehicle.VIN, at)
|
||||
committed = at
|
||||
}
|
||||
if !committed.After(cursor) || committed.Before(windowEnd) {
|
||||
if err := s.state.AdvanceBackfillCursor(vehicle.VIN, windowEnd); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
cursor = windowEnd
|
||||
s.markSourceSuccess()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) vehicleSnapshot() []Vehicle {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return append([]Vehicle(nil), s.vehicles...)
|
||||
}
|
||||
|
||||
func (s *Service) markSourceSuccess() {
|
||||
s.mu.Lock()
|
||||
s.lastSourceSuccess = time.Now()
|
||||
s.lastError = nil
|
||||
s.mu.Unlock()
|
||||
if s.metrics != nil {
|
||||
metrics.RecordLastActivity(s.metrics, "vehicle_feichi_bridge_source_last_success_unix_seconds", nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) setError(err error) {
|
||||
s.mu.Lock()
|
||||
s.lastError = err
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Service) recordFailure(operation string, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
s.setError(err)
|
||||
if s.metrics != nil {
|
||||
s.metrics.IncCounter("vehicle_feichi_bridge_errors_total", metrics.Labels{"operation": operation})
|
||||
}
|
||||
s.logger.Error("feichi bridge operation failed", "operation", operation, "error", err)
|
||||
}
|
||||
|
||||
func (s *Service) observeAPI(operation string, start time.Time, err error) {
|
||||
s.observeAPIWithDuration(operation, time.Since(start), err)
|
||||
}
|
||||
|
||||
func (s *Service) observeAPIWithDuration(operation string, duration time.Duration, err error) {
|
||||
if s.metrics == nil {
|
||||
return
|
||||
}
|
||||
status := "ok"
|
||||
if err != nil {
|
||||
status = "error"
|
||||
}
|
||||
s.metrics.IncCounter("vehicle_feichi_bridge_api_requests_total", metrics.Labels{"operation": operation, "status": status})
|
||||
s.metrics.ObserveHistogram(
|
||||
"vehicle_feichi_bridge_api_request_duration_seconds",
|
||||
metrics.Labels{"operation": operation},
|
||||
[]float64{0.1, 0.25, 0.5, 1, 2, 5},
|
||||
duration.Seconds(),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Service) recordFrame(command byte, status, vin string, sourceTime time.Time) {
|
||||
if s.metrics != nil {
|
||||
s.metrics.IncCounter("vehicle_feichi_bridge_frames_total", metrics.Labels{
|
||||
"command": fmt.Sprintf("0x%02X", command),
|
||||
"status": status,
|
||||
})
|
||||
}
|
||||
if status == "acked" {
|
||||
if s.metrics != nil {
|
||||
metrics.RecordLastActivity(s.metrics, "vehicle_feichi_bridge_target_last_ack_unix_seconds", nil)
|
||||
s.metrics.SetGauge(
|
||||
"vehicle_feichi_bridge_vehicle_last_ack_unix_seconds",
|
||||
metrics.Labels{"vin": vin, "command": fmt.Sprintf("0x%02X", command)},
|
||||
float64(time.Now().Unix()),
|
||||
)
|
||||
}
|
||||
s.logger.Info(
|
||||
"GB/T 32960 vehicle frame acknowledged",
|
||||
"vin", vin,
|
||||
"command", fmt.Sprintf("0x%02X", command),
|
||||
"source_time", sourceTime,
|
||||
)
|
||||
}
|
||||
}
|
||||
123
go/vehicle-gateway/internal/feichibridge/service_test.go
Normal file
123
go/vehicle-gateway/internal/feichibridge/service_test.go
Normal file
@@ -0,0 +1,123 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fakeSource struct {
|
||||
vehicles []Vehicle
|
||||
record Record
|
||||
}
|
||||
|
||||
func (f *fakeSource) Vehicles(context.Context) ([]Vehicle, error) {
|
||||
return append([]Vehicle(nil), f.vehicles...), nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) Snapshot(context.Context, string) (Snapshot, error) {
|
||||
return Snapshot{DataItems: map[string]string(f.record)}, nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) History(context.Context, string, time.Time, time.Time) ([]Record, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type fakeTarget struct {
|
||||
mu sync.Mutex
|
||||
frames [][]byte
|
||||
sendErr error
|
||||
lastACK time.Time
|
||||
}
|
||||
|
||||
func (f *fakeTarget) Connect(context.Context) error { return nil }
|
||||
func (f *fakeTarget) Close() error { return nil }
|
||||
func (f *fakeTarget) LastACK() time.Time { return f.lastACK }
|
||||
func (f *fakeTarget) Send(_ context.Context, frame []byte) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.sendErr != nil {
|
||||
return f.sendErr
|
||||
}
|
||||
f.frames = append(f.frames, append([]byte(nil), frame...))
|
||||
f.lastACK = time.Now()
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestRealtimeCommitsOnlyAfterACKAndDeduplicates(t *testing.T) {
|
||||
now := time.Now().In(shanghai).Truncate(time.Second)
|
||||
source := &fakeSource{
|
||||
vehicles: []Vehicle{{
|
||||
VehicleID: "id-1", VIN: "LTEST32960VIN0001", RuleTypeName: "GB_T32960",
|
||||
}},
|
||||
record: Record{"2000": now.Format("2006-01-02 15:04:05"), "2201": "10"},
|
||||
}
|
||||
target := &fakeTarget{}
|
||||
store, err := OpenStateStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service, err := NewService(ServiceConfig{
|
||||
SourceStaleAfter: time.Minute,
|
||||
FetchConcurrency: 1,
|
||||
}, source, target, store, slog.Default(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.discover(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.pollRealtime(context.Background())
|
||||
service.pollRealtime(context.Background())
|
||||
if len(target.frames) != 1 {
|
||||
t.Fatalf("frames = %d, want 1", len(target.frames))
|
||||
}
|
||||
if got := store.Vehicle("LTEST32960VIN0001"); !got.LastRealtimeTime.Equal(now) {
|
||||
t.Fatalf("committed state = %#v", got)
|
||||
}
|
||||
|
||||
source.record = Record{"2000": now.Add(time.Second).Format("2006-01-02 15:04:05"), "2201": "11"}
|
||||
target.sendErr = errors.New("target down")
|
||||
service.pollRealtime(context.Background())
|
||||
if got := store.Vehicle("LTEST32960VIN0001"); !got.LastRealtimeTime.Equal(now) {
|
||||
t.Fatalf("cursor advanced without ACK: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaleSnapshotIsReissuedOnlyOnce(t *testing.T) {
|
||||
at := time.Now().In(shanghai).Add(-24 * time.Hour).Truncate(time.Second)
|
||||
vin := "LTEST32960VIN0002"
|
||||
source := &fakeSource{
|
||||
vehicles: []Vehicle{{VehicleID: "id-2", VIN: vin, RuleTypeName: "GB_T32960"}},
|
||||
record: Record{"2000": at.Format("2006-01-02 15:04:05"), "2201": "0"},
|
||||
}
|
||||
target := &fakeTarget{}
|
||||
store, err := OpenStateStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service, err := NewService(ServiceConfig{
|
||||
SourceStaleAfter: time.Minute,
|
||||
FetchConcurrency: 1,
|
||||
StaleReissueEnabled: true,
|
||||
}, source, target, store, slog.Default(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.discover(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.pollRealtime(context.Background())
|
||||
service.pollRealtime(context.Background())
|
||||
if len(target.frames) != 1 || target.frames[0][2] != CommandReissue {
|
||||
t.Fatalf("frames = %d command = %#v", len(target.frames), target.frames)
|
||||
}
|
||||
state := store.Vehicle(vin)
|
||||
if !state.LastSnapshotReissueTime.Equal(at) || state.LastSnapshotReissueACKAt.IsZero() {
|
||||
t.Fatalf("reissue state = %#v", state)
|
||||
}
|
||||
}
|
||||
160
go/vehicle-gateway/internal/feichibridge/state.go
Normal file
160
go/vehicle-gateway/internal/feichibridge/state.go
Normal file
@@ -0,0 +1,160 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type VehicleState struct {
|
||||
LastRealtimeTime time.Time `json:"last_realtime_time,omitempty"`
|
||||
LastRealtimeHash string `json:"last_realtime_hash,omitempty"`
|
||||
LastRealtimeACKAt time.Time `json:"last_realtime_ack_at,omitempty"`
|
||||
LastSnapshotReissueTime time.Time `json:"last_snapshot_reissue_time,omitempty"`
|
||||
LastSnapshotReissueHash string `json:"last_snapshot_reissue_hash,omitempty"`
|
||||
LastSnapshotReissueACKAt time.Time `json:"last_snapshot_reissue_ack_at,omitempty"`
|
||||
BackfillCursor time.Time `json:"backfill_cursor,omitempty"`
|
||||
LastBackfillACKAt time.Time `json:"last_backfill_ack_at,omitempty"`
|
||||
}
|
||||
|
||||
func (s *StateStore) CommitSnapshotReissue(vin string, at time.Time, hash string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
current := s.state.Vehicles[vin]
|
||||
current.LastSnapshotReissueTime = at
|
||||
current.LastSnapshotReissueHash = hash
|
||||
current.LastSnapshotReissueACKAt = time.Now()
|
||||
s.state.Vehicles[vin] = current
|
||||
return s.saveLocked()
|
||||
}
|
||||
|
||||
type persistentState struct {
|
||||
Version int `json:"version"`
|
||||
PlatformSerial uint16 `json:"platform_serial"`
|
||||
Vehicles map[string]VehicleState `json:"vehicles"`
|
||||
}
|
||||
|
||||
type StateStore struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
state persistentState
|
||||
}
|
||||
|
||||
func OpenStateStore(path string) (*StateStore, error) {
|
||||
store := &StateStore{
|
||||
path: path,
|
||||
state: persistentState{
|
||||
Version: 1,
|
||||
Vehicles: map[string]VehicleState{},
|
||||
},
|
||||
}
|
||||
encoded, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return store, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read bridge state: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal(encoded, &store.state); err != nil {
|
||||
return nil, fmt.Errorf("decode bridge state: %w", err)
|
||||
}
|
||||
if store.state.Vehicles == nil {
|
||||
store.state.Vehicles = map[string]VehicleState{}
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
func (s *StateStore) Vehicle(vin string) VehicleState {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.state.Vehicles[vin]
|
||||
}
|
||||
|
||||
func (s *StateStore) CommitRealtime(vin string, at time.Time, hash string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
current := s.state.Vehicles[vin]
|
||||
current.LastRealtimeTime = at
|
||||
current.LastRealtimeHash = hash
|
||||
current.LastRealtimeACKAt = time.Now()
|
||||
s.state.Vehicles[vin] = current
|
||||
return s.saveLocked()
|
||||
}
|
||||
|
||||
func (s *StateStore) CommitBackfill(vin string, at time.Time) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
current := s.state.Vehicles[vin]
|
||||
current.BackfillCursor = at
|
||||
current.LastBackfillACKAt = time.Now()
|
||||
s.state.Vehicles[vin] = current
|
||||
return s.saveLocked()
|
||||
}
|
||||
|
||||
func (s *StateStore) AdvanceBackfillCursor(vin string, at time.Time) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
current := s.state.Vehicles[vin]
|
||||
current.BackfillCursor = at
|
||||
s.state.Vehicles[vin] = current
|
||||
return s.saveLocked()
|
||||
}
|
||||
|
||||
func (s *StateStore) NextPlatformSerial() (uint16, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.state.PlatformSerial++
|
||||
if s.state.PlatformSerial == 0 {
|
||||
s.state.PlatformSerial = 1
|
||||
}
|
||||
if err := s.saveLocked(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return s.state.PlatformSerial, nil
|
||||
}
|
||||
|
||||
func (s *StateStore) saveLocked() error {
|
||||
if err := os.MkdirAll(filepath.Dir(s.path), 0o750); err != nil {
|
||||
return fmt.Errorf("create bridge state directory: %w", err)
|
||||
}
|
||||
encoded, err := json.MarshalIndent(s.state, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
temp, err := os.CreateTemp(filepath.Dir(s.path), ".state-*.json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tempName := temp.Name()
|
||||
defer os.Remove(tempName)
|
||||
if err := temp.Chmod(0o600); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := temp.Write(encoded); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
if err := temp.Sync(); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
if err := temp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tempName, s.path); err != nil {
|
||||
return fmt.Errorf("replace bridge state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hashBytes(value []byte) string {
|
||||
sum := sha256.Sum256(value)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
38
go/vehicle-gateway/internal/feichibridge/state_test.go
Normal file
38
go/vehicle-gateway/internal/feichibridge/state_test.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestStateStorePersistsAcknowledgedCursor(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "nested", "state.json")
|
||||
store, err := OpenStateStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := time.Date(2026, 7, 17, 12, 0, 0, 0, time.UTC)
|
||||
if err := store.CommitRealtime("LTEST32960VIN0001", at, "hash"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.CommitBackfill("LTEST32960VIN0001", at.Add(-time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened, err := OpenStateStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := reopened.Vehicle("LTEST32960VIN0001")
|
||||
if !got.LastRealtimeTime.Equal(at) || got.LastRealtimeHash != "hash" {
|
||||
t.Fatalf("state = %#v", got)
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("state mode = %o", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
193
go/vehicle-gateway/internal/feichibridge/target.go
Normal file
193
go/vehicle-gateway/internal/feichibridge/target.go
Normal file
@@ -0,0 +1,193 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TargetConfig struct {
|
||||
Address string
|
||||
PlatformID string
|
||||
Username string
|
||||
Password string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
type Target struct {
|
||||
mu sync.Mutex
|
||||
config TargetConfig
|
||||
state *StateStore
|
||||
dialer net.Dialer
|
||||
conn net.Conn
|
||||
lastACK time.Time
|
||||
}
|
||||
|
||||
func NewTarget(config TargetConfig, state *StateStore) (*Target, error) {
|
||||
if strings.TrimSpace(config.Address) == "" {
|
||||
return nil, errors.New("GB/T 32960 target address is required")
|
||||
}
|
||||
if len(config.PlatformID) != 17 {
|
||||
return nil, fmt.Errorf("target platform ID must be exactly 17 bytes")
|
||||
}
|
||||
if state == nil {
|
||||
return nil, errors.New("state store is required")
|
||||
}
|
||||
if config.Timeout <= 0 {
|
||||
config.Timeout = 10 * time.Second
|
||||
}
|
||||
return &Target{
|
||||
config: config,
|
||||
state: state,
|
||||
dialer: net.Dialer{Timeout: config.Timeout, KeepAlive: 30 * time.Second},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *Target) Send(ctx context.Context, frame []byte) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
if err := t.ensureConnected(ctx); err != nil {
|
||||
lastErr = err
|
||||
t.closeLocked()
|
||||
continue
|
||||
}
|
||||
if err := t.sendAndACK(ctx, frame); err != nil {
|
||||
lastErr = err
|
||||
t.closeLocked()
|
||||
continue
|
||||
}
|
||||
t.lastACK = time.Now()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("send GB/T 32960 frame after reconnect: %w", lastErr)
|
||||
}
|
||||
|
||||
func (t *Target) Connect(ctx context.Context) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if err := t.ensureConnected(ctx); err != nil {
|
||||
t.closeLocked()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Target) Close() error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.conn == nil {
|
||||
return nil
|
||||
}
|
||||
err := t.conn.Close()
|
||||
t.conn = nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *Target) LastACK() time.Time {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.lastACK
|
||||
}
|
||||
|
||||
func (t *Target) ensureConnected(ctx context.Context) error {
|
||||
if t.conn != nil {
|
||||
return nil
|
||||
}
|
||||
conn, err := t.dialer.DialContext(ctx, "tcp", t.config.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial target %s: %w", t.config.Address, err)
|
||||
}
|
||||
t.conn = conn
|
||||
serial, err := t.state.NextPlatformSerial()
|
||||
if err != nil {
|
||||
return fmt.Errorf("allocate platform login serial: %w", err)
|
||||
}
|
||||
login, err := LoginFrame(t.config.PlatformID, t.config.Username, t.config.Password, serial, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := t.sendAndACK(ctx, login); err != nil {
|
||||
return fmt.Errorf("GB/T 32960 platform login: %w", err)
|
||||
}
|
||||
t.lastACK = time.Now()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Target) sendAndACK(ctx context.Context, frame []byte) error {
|
||||
if t.conn == nil {
|
||||
return errors.New("target connection is closed")
|
||||
}
|
||||
deadline := time.Now().Add(t.config.Timeout)
|
||||
if contextDeadline, ok := ctx.Deadline(); ok && contextDeadline.Before(deadline) {
|
||||
deadline = contextDeadline
|
||||
}
|
||||
if err := t.conn.SetDeadline(deadline); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeFull(t.conn, frame); err != nil {
|
||||
return fmt.Errorf("write target frame: %w", err)
|
||||
}
|
||||
response, err := readFrame(t.conn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read target ACK: %w", err)
|
||||
}
|
||||
if response[2] != frame[2] {
|
||||
return fmt.Errorf("target ACK command mismatch: got 0x%02X want 0x%02X", response[2], frame[2])
|
||||
}
|
||||
if response[3] != 0x01 {
|
||||
return fmt.Errorf("target rejected command 0x%02X with response 0x%02X", response[2], response[3])
|
||||
}
|
||||
if string(response[4:21]) != string(frame[4:21]) {
|
||||
return errors.New("target ACK identifier mismatch")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Target) closeLocked() {
|
||||
if t.conn != nil {
|
||||
_ = t.conn.Close()
|
||||
t.conn = nil
|
||||
}
|
||||
}
|
||||
|
||||
func readFrame(reader io.Reader) ([]byte, error) {
|
||||
header := make([]byte, 24)
|
||||
if _, err := io.ReadFull(reader, header); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if (header[0] != '#' || header[1] != '#') && (header[0] != '$' || header[1] != '$') {
|
||||
return nil, fmt.Errorf("bad GB/T 32960 ACK start %q", header[:2])
|
||||
}
|
||||
bodyLength := int(binary.BigEndian.Uint16(header[22:24]))
|
||||
tail := make([]byte, bodyLength+1)
|
||||
if _, err := io.ReadFull(reader, tail); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
frame := append(header, tail...)
|
||||
if got, want := bcc(frame[2:len(frame)-1]), frame[len(frame)-1]; got != want {
|
||||
return nil, fmt.Errorf("bad GB/T 32960 ACK BCC: got 0x%02X want 0x%02X", got, want)
|
||||
}
|
||||
return frame, nil
|
||||
}
|
||||
|
||||
func writeFull(writer io.Writer, value []byte) error {
|
||||
for len(value) > 0 {
|
||||
written, err := writer.Write(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if written == 0 {
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
value = value[written:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
83
go/vehicle-gateway/internal/feichibridge/target_test.go
Normal file
83
go/vehicle-gateway/internal/feichibridge/target_test.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package feichibridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTargetLogsInAndWaitsForACK(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
var commands []byte
|
||||
var mu sync.Mutex
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
conn, acceptErr := listener.Accept()
|
||||
if acceptErr != nil {
|
||||
done <- acceptErr
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
for count := 0; count < 2; count++ {
|
||||
frame, readErr := readFrame(conn)
|
||||
if readErr != nil {
|
||||
done <- readErr
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
commands = append(commands, frame[2])
|
||||
mu.Unlock()
|
||||
body := []byte(nil)
|
||||
if len(frame) >= 31 {
|
||||
body = append(body, frame[24:30]...)
|
||||
}
|
||||
ack, buildErr := buildFrame('#', frame[2], 0x01, string(frame[4:21]), body)
|
||||
if buildErr != nil {
|
||||
done <- buildErr
|
||||
return
|
||||
}
|
||||
if writeErr := writeFull(conn, ack); writeErr != nil {
|
||||
done <- writeErr
|
||||
return
|
||||
}
|
||||
}
|
||||
done <- nil
|
||||
}()
|
||||
|
||||
store, err := OpenStateStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target, err := NewTarget(TargetConfig{
|
||||
Address: listener.Addr().String(), PlatformID: "FEICHIBRIDGE00001",
|
||||
Username: "bridge", Password: "secret", Timeout: time.Second,
|
||||
}, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
frame, err := (Encoder{}).DataFrame(CommandRealtime, "LTEST32960VIN0001", time.Now(), Record{"2201": "1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := target.Send(context.Background(), frame); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(commands) != 2 || commands[0] != CommandLogin || commands[1] != CommandRealtime {
|
||||
t.Fatalf("commands = %x", commands)
|
||||
}
|
||||
if target.LastACK().IsZero() {
|
||||
t.Fatal("last ACK was not recorded")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user