From 2b7682cdb32b838641475cb2104cd9dcb125e140 Mon Sep 17 00:00:00 2001 From: Sergey Krashevich Date: Tue, 10 Mar 2026 23:26:45 +0300 Subject: [PATCH] refactor(dvrip): simplify broadcast loop structure - replace traditional for loop with range-based for loop for clarity refactor(ffmpeg): simplify cut function loop - utilize range-based for loop instead of traditional for loop refactor(ring): update API response mapping type - change map type from `interface{}` to `any` for better type safety refactor(stream): handle nil source in NewStream - add nil check for source elements before processing refactor(webrtc): unify payload handling in GetToken - change map type from `interface{}` to `any` for consistency refactor(ascii): optimize nested loops in Write function - replace traditional for loops with range-based for loops for readability refactor(bits): enhance readability in Reader methods - replace traditional for loops with range-based for loops in Read functions refactor(h264): modernize loop structures in DecodeConfig - switch to range-based for loops for cleaner code refactor(h265): streamline profile_tier_level loops - utilize range-based for loops instead of traditional for loops chore(core): remove commented-out test function for clarity refactor(core): simplify RandString function loop - change traditional for loop to range-based for loop refactor(flvt): optimize timestamp handling in TestTimeToRTP - switch to range-based for loop for iterating frames refactor(nest): improve error handling in ExchangeSDP - format error message with printf-style formatting for clarity refactor(tapo): enhance securityEncode function - change traditional for loop to range-based for loop for readability fix(tcp): correct masking in websocket Write method - replace traditional for loop with range-based for loop refactor(tutk): modernize encoding loops in crypto functions - utilize range-based for loops for better readability refactor(tuya): unify data types in MQTT message struct - change map type from `interface{}` to `any` for consistency refactor(webrtc): standardize codec registration - change map type from `interface{}` to `any` for type safety refactor(yaml): simplify Unmarshal function signature - update parameter type from `interface{}` to `any` for better clarity --- internal/dvrip/dvrip.go | 2 +- internal/ffmpeg/hardware/hardware.go | 2 +- internal/ring/ring.go | 2 +- internal/streams/stream.go | 3 +++ internal/webrtc/milestone.go | 2 +- pkg/ascii/ascii.go | 6 +++--- pkg/bits/reader.go | 14 +++++++------- pkg/bits/writer.go | 6 +++--- pkg/core/core_test.go | 14 -------------- pkg/core/helpers.go | 2 +- pkg/flv/flv_test.go | 2 +- pkg/h264/mpeg4.go | 4 ++-- pkg/h264/sps.go | 26 +++++++++++++------------- pkg/h265/sps.go | 4 ++-- pkg/hap/camera/accessory_test.go | 2 +- pkg/hap/hds/hds_test.go | 4 ++-- pkg/hap/tlv8/tlv8.go | 2 +- pkg/hap/tlv8/tlv8_test.go | 2 +- pkg/hls/reader.go | 2 +- pkg/iso/reader.go | 4 ++-- pkg/ivideon/ivideon.go | 2 +- pkg/mjpeg/rfc2435.go | 2 +- pkg/mp4/demuxer.go | 2 +- pkg/mpegts/muxer.go | 20 ++++++++++---------- pkg/mpegts/opus.go | 4 ++-- pkg/mqtt/message.go | 18 +++++++++--------- pkg/nest/api.go | 2 +- pkg/nest/client.go | 4 ++-- pkg/pcm/v1/pcm_test.go | 4 ++-- pkg/ring/api.go | 28 ++++++++++++++-------------- pkg/ring/client.go | 6 +++--- pkg/ring/ws.go | 12 ++++++------ pkg/roborock/iot/crypto.go | 2 +- pkg/rtsp/client.go | 2 +- pkg/tapo/client.go | 2 +- pkg/tcp/websocket/client.go | 2 +- pkg/tutk/crypto.go | 4 ++-- pkg/tuya/cloud_api.go | 4 ++-- pkg/tuya/mqtt.go | 14 +++++++------- pkg/webrtc/api.go | 8 ++++---- pkg/webrtc/conn.go | 2 -- pkg/yaml/yaml.go | 4 ++-- 42 files changed, 120 insertions(+), 133 deletions(-) diff --git a/internal/dvrip/dvrip.go b/internal/dvrip/dvrip.go index db1c60db..423face2 100644 --- a/internal/dvrip/dvrip.go +++ b/internal/dvrip/dvrip.go @@ -80,7 +80,7 @@ func sendBroadcasts(conn *net.UDPConn) { IP: net.IP{255, 255, 255, 255}, } - for i := 0; i < 3; i++ { + for range 3 { time.Sleep(100 * time.Millisecond) _, _ = conn.WriteToUDP(data, addr) } diff --git a/internal/ffmpeg/hardware/hardware.go b/internal/ffmpeg/hardware/hardware.go index 80166890..bc35cdf8 100644 --- a/internal/ffmpeg/hardware/hardware.go +++ b/internal/ffmpeg/hardware/hardware.go @@ -175,7 +175,7 @@ func runToString(bin string, args string) string { } func cut(s string, sep byte, pos int) string { - for n := 0; n < pos; n++ { + for range pos { if i := strings.IndexByte(s, sep); i > 0 { s = s[i+1:] } else { diff --git a/internal/ring/ring.go b/internal/ring/ring.go index 7fdb284f..355e15b7 100644 --- a/internal/ring/ring.go +++ b/internal/ring/ring.go @@ -45,7 +45,7 @@ func apiRing(w http.ResponseWriter, r *http.Request) { if _, err = ringAPI.GetAuth(code); err != nil { if ringAPI.Using2FA { // Return 2FA prompt - api.ResponseJSON(w, map[string]interface{}{ + api.ResponseJSON(w, map[string]any{ "needs_2fa": true, "prompt": ringAPI.PromptFor2FA, }) diff --git a/internal/streams/stream.go b/internal/streams/stream.go index 984c73ed..d6874bac 100644 --- a/internal/streams/stream.go +++ b/internal/streams/stream.go @@ -30,6 +30,9 @@ func NewStream(source any) *Stream { case []any: s := new(Stream) for _, src := range source { + if src == nil { + continue + } str, ok := src.(string) if !ok { log.Error().Msgf("[stream] NewStream: Expected string, got %v", src) diff --git a/internal/webrtc/milestone.go b/internal/webrtc/milestone.go index fe1cedcf..6d012a15 100644 --- a/internal/webrtc/milestone.go +++ b/internal/webrtc/milestone.go @@ -54,7 +54,7 @@ func (m *milestoneAPI) GetToken() error { return errors.New("milesone: authentication failed: " + res.Status) } - var payload map[string]interface{} + var payload map[string]any if err = json.NewDecoder(res.Body).Decode(&payload); err != nil { return err } diff --git a/pkg/ascii/ascii.go b/pkg/ascii/ascii.go index 6636e278..1063075d 100644 --- a/pkg/ascii/ascii.go +++ b/pkg/ascii/ascii.go @@ -114,8 +114,8 @@ func (a *writer) Write(p []byte) (n int, err error) { w := img.Bounds().Dx() h := img.Bounds().Dy() - for y := 0; y < h; y++ { - for x := 0; x < w; x++ { + for y := range h { + for x := range w { r, g, b, _ := img.At(x, y).RGBA() if a.color != nil { a.color(uint8(r>>8), uint8(g>>8), uint8(b>>8)) @@ -155,7 +155,7 @@ const x256b = "\x00\x00\x00\x00\x80\x80\x80\xc0\x80\x00\x00\x00\xff\xff\xff\xff\ func xterm256color(r, g, b uint8, n int) (index uint8) { best := uint16(0xFFFF) - for i := 0; i < n; i++ { + for i := range n { diff := sqDiff(r, x256r[i]) + sqDiff(g, x256g[i]) + sqDiff(b, x256b[i]) if diff < best { best = diff diff --git a/pkg/bits/reader.go b/pkg/bits/reader.go index 2a957409..81a4a4a7 100644 --- a/pkg/bits/reader.go +++ b/pkg/bits/reader.go @@ -14,7 +14,7 @@ func NewReader(b []byte) *Reader { } //goland:noinspection GoStandardMethods -func (r *Reader) ReadByte() byte { +func (r *Reader) ReadUint8() byte { if r.bits != 0 { return r.ReadBits8(8) } @@ -33,26 +33,26 @@ func (r *Reader) ReadUint16() uint16 { if r.bits != 0 { return r.ReadBits16(16) } - return uint16(r.ReadByte())<<8 | uint16(r.ReadByte()) + return uint16(r.ReadUint8())<<8 | uint16(r.ReadUint8()) } func (r *Reader) ReadUint24() uint32 { if r.bits != 0 { return r.ReadBits(24) } - return uint32(r.ReadByte())<<16 | uint32(r.ReadByte())<<8 | uint32(r.ReadByte()) + return uint32(r.ReadUint8())<<16 | uint32(r.ReadUint8())<<8 | uint32(r.ReadUint8()) } func (r *Reader) ReadUint32() uint32 { if r.bits != 0 { return r.ReadBits(32) } - return uint32(r.ReadByte())<<24 | uint32(r.ReadByte())<<16 | uint32(r.ReadByte())<<8 | uint32(r.ReadByte()) + return uint32(r.ReadUint8())<<24 | uint32(r.ReadUint8())<<16 | uint32(r.ReadUint8())<<8 | uint32(r.ReadUint8()) } func (r *Reader) ReadBit() byte { if r.bits == 0 { - r.byte = r.ReadByte() + r.byte = r.ReadUint8() r.bits = 7 } else { r.bits-- @@ -106,8 +106,8 @@ func (r *Reader) ReadBytes(n int) (b []byte) { r.pos += n } else { b = make([]byte, n) - for i := 0; i < n; i++ { - b[i] = r.ReadByte() + for i := range n { + b[i] = r.ReadUint8() } } diff --git a/pkg/bits/writer.go b/pkg/bits/writer.go index 307166b1..d84e15ac 100644 --- a/pkg/bits/writer.go +++ b/pkg/bits/writer.go @@ -11,7 +11,7 @@ func NewWriter(buf []byte) *Writer { } //goland:noinspection GoStandardMethods -func (w *Writer) WriteByte(b byte) { +func (w *Writer) WriteUint8(b byte) { if w.bits != 0 { w.WriteBits8(b, 8) } @@ -50,7 +50,7 @@ func (w *Writer) WriteBits8(v, n byte) { } func (w *Writer) WriteAllBits(bit, n byte) { - for i := byte(0); i < n; i++ { + for range n { w.WriteBit(bit) } } @@ -74,7 +74,7 @@ func (w *Writer) WriteUint16(v uint16) { func (w *Writer) WriteBytes(bytes ...byte) { if w.bits != 0 { for _, b := range bytes { - w.WriteByte(b) + w.WriteUint8(b) } } diff --git a/pkg/core/core_test.go b/pkg/core/core_test.go index e7845ca7..4a05380a 100644 --- a/pkg/core/core_test.go +++ b/pkg/core/core_test.go @@ -118,17 +118,3 @@ func TestName(t *testing.T) { // stage3 _ = prod2.Stop() } - -func TestStripUserinfo(t *testing.T) { - s := `streams: - test: - - ffmpeg:rtsp://username:password@10.1.2.3:554/stream1 - - ffmpeg:rtsp://10.1.2.3:554/stream1@#video=copy -` - s = StripUserinfo(s) - require.Equal(t, `streams: - test: - - ffmpeg:rtsp://***@10.1.2.3:554/stream1 - - ffmpeg:rtsp://10.1.2.3:554/stream1@#video=copy -`, s) -} diff --git a/pkg/core/helpers.go b/pkg/core/helpers.go index 45bbd0d5..b72e09c7 100644 --- a/pkg/core/helpers.go +++ b/pkg/core/helpers.go @@ -32,7 +32,7 @@ func RandString(size, base byte) string { if base == 0 { return string(b) } - for i := byte(0); i < size; i++ { + for i := range size { b[i] = symbols[b[i]%base] } return string(b) diff --git a/pkg/flv/flv_test.go b/pkg/flv/flv_test.go index 389272b0..cd7326d1 100644 --- a/pkg/flv/flv_test.go +++ b/pkg/flv/flv_test.go @@ -11,7 +11,7 @@ func TestTimeToRTP(t *testing.T) { // Video timestamp increases by 50ms, SampleRate 90000, RTP timestamp increases by 4500 // Audio timestamp increases by 64ms, SampleRate 16000, RTP timestamp increases by 1024 frameN := 1 - for i := 0; i < 32; i++ { + for range 32 { // 1000ms/(90000/4500) = 50ms require.Equal(t, uint32(frameN*4500), TimeToRTP(uint32(frameN*50), 90000)) // 1000ms/(16000/1024) = 64ms diff --git a/pkg/h264/mpeg4.go b/pkg/h264/mpeg4.go index c49e0e8a..d02cae62 100644 --- a/pkg/h264/mpeg4.go +++ b/pkg/h264/mpeg4.go @@ -20,7 +20,7 @@ func DecodeConfig(conf []byte) (profile []byte, sps []byte, pps []byte) { count := conf[5] & 0x1F conf = conf[6:] - for i := byte(0); i < count; i++ { + for range count { if len(conf) < 2 { return } @@ -36,7 +36,7 @@ func DecodeConfig(conf []byte) (profile []byte, sps []byte, pps []byte) { count = conf[0] conf = conf[1:] - for i := byte(0); i < count; i++ { + for range count { if len(conf) < 2 { return } diff --git a/pkg/h264/sps.go b/pkg/h264/sps.go index 1ac73945..903c8ccd 100644 --- a/pkg/h264/sps.go +++ b/pkg/h264/sps.go @@ -92,15 +92,15 @@ func DecodeSPS(sps []byte) *SPS { // ffmpeg -i file.h264 -c copy -bsf:v trace_headers -f null - r := bits.NewReader(sps) - hdr := r.ReadByte() + hdr := r.ReadUint8() if hdr&0x1F != NALUTypeSPS { return nil } s := &SPS{ - profile_idc: r.ReadByte(), - profile_iop: r.ReadByte(), - level_idc: r.ReadByte(), + profile_idc: r.ReadUint8(), + profile_iop: r.ReadUint8(), + level_idc: r.ReadUint8(), seq_parameter_set_id: r.ReadUEGolomb(), } @@ -120,7 +120,7 @@ func DecodeSPS(sps []byte) *SPS { s.seq_scaling_matrix_present_flag = r.ReadBit() if s.seq_scaling_matrix_present_flag != 0 { - for i := byte(0); i < n; i++ { + for i := range n { //goland:noinspection GoSnakeCaseUsage seq_scaling_list_present_flag := r.ReadBit() if seq_scaling_list_present_flag != 0 { @@ -176,7 +176,7 @@ func DecodeSPS(sps []byte) *SPS { if s.vui_parameters_present_flag != 0 { s.aspect_ratio_info_present_flag = r.ReadBit() if s.aspect_ratio_info_present_flag != 0 { - s.aspect_ratio_idc = r.ReadByte() + s.aspect_ratio_idc = r.ReadUint8() if s.aspect_ratio_idc == 255 { s.sar_width = r.ReadUint16() s.sar_height = r.ReadUint16() @@ -225,7 +225,7 @@ func DecodeSPS(sps []byte) *SPS { func (s *SPS) scaling_list(r *bits.Reader, sizeOfScalingList int) { lastScale := int32(8) nextScale := int32(8) - for j := 0; j < sizeOfScalingList; j++ { + for range sizeOfScalingList { if nextScale != 0 { delta_scale := r.ReadSEGolomb() nextScale = (lastScale + delta_scale + 256) % 256 @@ -279,11 +279,11 @@ func (s *SPS) String() string { func FixPixFmt(sps []byte) { r := bits.NewReader(sps) - _ = r.ReadByte() + _ = r.ReadUint8() - profile := r.ReadByte() - _ = r.ReadByte() - _ = r.ReadByte() + profile := r.ReadUint8() + _ = r.ReadUint8() + _ = r.ReadUint8() _ = r.ReadUEGolomb() switch profile { @@ -300,7 +300,7 @@ func FixPixFmt(sps []byte) { _ = r.ReadBit() if r.ReadBit() != 0 { - for i := byte(0); i < n; i++ { + for range n { if r.ReadBit() != 0 { return // skip } @@ -345,7 +345,7 @@ func FixPixFmt(sps []byte) { if r.ReadBit() != 0 { if r.ReadBit() != 0 { - if r.ReadByte() == 255 { + if r.ReadUint8() == 255 { _ = r.ReadUint16() _ = r.ReadUint16() } diff --git a/pkg/h265/sps.go b/pkg/h265/sps.go index 5f61363b..39bd5051 100644 --- a/pkg/h265/sps.go +++ b/pkg/h265/sps.go @@ -92,7 +92,7 @@ func (s *SPS) profile_tier_level(r *bits.Reader) bool { s.sub_layer_profile_present_flag = make([]byte, s.sps_max_sub_layers_minus1) s.sub_layer_level_present_flag = make([]byte, s.sps_max_sub_layers_minus1) - for i := byte(0); i < s.sps_max_sub_layers_minus1; i++ { + for i := range s.sps_max_sub_layers_minus1 { s.sub_layer_profile_present_flag[i] = r.ReadBit() s.sub_layer_level_present_flag[i] = r.ReadBit() } @@ -103,7 +103,7 @@ func (s *SPS) profile_tier_level(r *bits.Reader) bool { } } - for i := byte(0); i < s.sps_max_sub_layers_minus1; i++ { + for i := range s.sps_max_sub_layers_minus1 { if s.sub_layer_profile_present_flag[i] != 0 { _ = r.ReadBits8(2) // sub_layer_profile_space _ = r.ReadBit() // sub_layer_tier_flag diff --git a/pkg/hap/camera/accessory_test.go b/pkg/hap/camera/accessory_test.go index 53c99a49..72bfed00 100644 --- a/pkg/hap/camera/accessory_test.go +++ b/pkg/hap/camera/accessory_test.go @@ -10,7 +10,7 @@ import ( ) func TestNilCharacter(t *testing.T) { - var res SetupEndpoints + var res SetupEndpointsRequest char := &hap.Character{} err := char.ReadTLV8(&res) require.NotNil(t, err) diff --git a/pkg/hap/hds/hds_test.go b/pkg/hap/hds/hds_test.go index f1c85455..47ebd737 100644 --- a/pkg/hap/hds/hds_test.go +++ b/pkg/hap/hds/hds_test.go @@ -13,7 +13,7 @@ func TestEncryption(t *testing.T) { key := []byte(core.RandString(16, 0)) salt := core.RandString(32, 0) - c, err := Client(nil, key, salt, true) + c, err := NewConn(nil, key, salt, true) require.NoError(t, err) buf := bytes.NewBuffer(nil) @@ -23,7 +23,7 @@ func TestEncryption(t *testing.T) { require.NoError(t, err) require.Equal(t, 4, n) - c, err = Client(nil, key, salt, false) + c, err = NewConn(nil, key, salt, false) c.rd = bufio.NewReader(buf) require.NoError(t, err) diff --git a/pkg/hap/tlv8/tlv8.go b/pkg/hap/tlv8/tlv8.go index 7b397b99..0ad504df 100644 --- a/pkg/hap/tlv8/tlv8.go +++ b/pkg/hap/tlv8/tlv8.go @@ -135,7 +135,7 @@ func appendValue(b []byte, tag byte, value reflect.Value) ([]byte, error) { if value.Type().Elem().Kind() == reflect.Uint8 { n := value.Len() b = append(b, tag, byte(n)) - for i := 0; i < n; i++ { + for i := range n { b = append(b, byte(value.Index(i).Uint())) } return b, nil diff --git a/pkg/hap/tlv8/tlv8_test.go b/pkg/hap/tlv8/tlv8_test.go index bb44c981..bf834a4a 100644 --- a/pkg/hap/tlv8/tlv8_test.go +++ b/pkg/hap/tlv8/tlv8_test.go @@ -41,7 +41,7 @@ func TestMarshal(t *testing.T) { func TestBytes(t *testing.T) { bytes := make([]byte, 255) - for i := 0; i < len(bytes); i++ { + for i := range len(bytes) { bytes[i] = byte(i) } diff --git a/pkg/hls/reader.go b/pkg/hls/reader.go index 37554e3c..42ee650a 100644 --- a/pkg/hls/reader.go +++ b/pkg/hls/reader.go @@ -88,7 +88,7 @@ func (r *reader) RoundTrip(_ *http.Request) (*http.Response, error) { } func (r *reader) getSegment() ([]byte, error) { - for i := 0; i < 10; i++ { + for range 10 { if r.playlist == nil { if wait := time.Second - time.Since(r.lastTime); wait > 0 { time.Sleep(wait) diff --git a/pkg/iso/reader.go b/pkg/iso/reader.go index 175e2563..038b7860 100644 --- a/pkg/iso/reader.go +++ b/pkg/iso/reader.go @@ -120,7 +120,7 @@ func DecodeAtom(b []byte) (any, error) { case MoofTrafTfhd: rd := bits.NewReader(data) - _ = rd.ReadByte() // version + _ = rd.ReadUint8() // version flags := rd.ReadUint24() atom := &AtomTfhd{ @@ -145,7 +145,7 @@ func DecodeAtom(b []byte) (any, error) { case MoofTrafTrun: rd := bits.NewReader(data) - _ = rd.ReadByte() // version + _ = rd.ReadUint8() // version flags := rd.ReadUint24() samples := rd.ReadUint32() diff --git a/pkg/ivideon/ivideon.go b/pkg/ivideon/ivideon.go index 973b9ba0..9afd18ec 100644 --- a/pkg/ivideon/ivideon.go +++ b/pkg/ivideon/ivideon.go @@ -78,7 +78,7 @@ func GetLiveStream(id string) (string, error) { } if !v.Success { - return "", fmt.Errorf("ivideon: can't get live_stream: " + v.Message) + return "", fmt.Errorf("ivideon: can't get live_stream: %s", v.Message) } return v.Result.URL, nil diff --git a/pkg/mjpeg/rfc2435.go b/pkg/mjpeg/rfc2435.go index aa34c2f1..fca013c0 100644 --- a/pkg/mjpeg/rfc2435.go +++ b/pkg/mjpeg/rfc2435.go @@ -47,7 +47,7 @@ func MakeTables(q byte) (lqt, cqt []byte) { lqt = make([]byte, 64) cqt = make([]byte, 64) - for i := 0; i < 64; i++ { + for i := range 64 { lq := (int(jpeg_luma_quantizer[i])*factor + 50) / 100 cq := (int(jpeg_chroma_quantizer[i])*factor + 50) / 100 diff --git a/pkg/mp4/demuxer.go b/pkg/mp4/demuxer.go index 25c8c70e..3e2a9f73 100644 --- a/pkg/mp4/demuxer.go +++ b/pkg/mp4/demuxer.go @@ -97,7 +97,7 @@ func (d *Demuxer) Demux(data2 []byte) (trackID uint32, packets []*core.Packet) { n := len(trun.SamplesDuration) packets = make([]*core.Packet, n) - for i := 0; i < n; i++ { + for i := range n { duration := trun.SamplesDuration[i] size := trun.SamplesSize[i] diff --git a/pkg/mpegts/muxer.go b/pkg/mpegts/muxer.go index 5d4129d1..ebae1777 100644 --- a/pkg/mpegts/muxer.go +++ b/pkg/mpegts/muxer.go @@ -129,7 +129,7 @@ func (m *Muxer) writePMT(wr *bits.Writer) { if !ok { break } - wr.WriteByte(pes.StreamType) // Stream type + wr.WriteUint8(pes.StreamType) // Stream type wr.WriteBits8(0b111, 3) // Reserved bits (all to 1) wr.WriteBits16(pid, 13) // Elementary PID wr.WriteBits8(0b1111, 4) // Reserved bits (all to 1) @@ -148,7 +148,7 @@ func (m *Muxer) writePES(wr *bits.Writer, pid uint16, pes *PES) { const flagAdaptation = 0b00100000 const flagPayload = 0b00010000 - wr.WriteByte(SyncByte) + wr.WriteUint8(SyncByte) if pes.Size != 0 { pid |= flagPUSI // Payload unit start indicator (PUSI) @@ -159,17 +159,17 @@ func (m *Muxer) writePES(wr *bits.Writer, pid uint16, pes *PES) { counter := byte(pes.Sequence) & 0xF if size := len(pes.Payload); size < PacketSize-4 { - wr.WriteByte(flagAdaptation | flagPayload | counter) // adaptation + payload + wr.WriteUint8(flagAdaptation | flagPayload | counter) // adaptation + payload // for 183 payload will be zero adSize := PacketSize - 4 - 1 - byte(size) - wr.WriteByte(adSize) + wr.WriteUint8(adSize) wr.WriteBytes(make([]byte, adSize)...) wr.WriteBytes(pes.Payload...) pes.Payload = nil } else { - wr.WriteByte(flagPayload | counter) // only payload + wr.WriteUint8(flagPayload | counter) // only payload wr.WriteBytes(pes.Payload[:PacketSize-4]...) pes.Payload = pes.Payload[PacketSize-4:] @@ -177,7 +177,7 @@ func (m *Muxer) writePES(wr *bits.Writer, pid uint16, pes *PES) { } func (m *Muxer) writeHeader(wr *bits.Writer, pid uint16) { - wr.WriteByte(SyncByte) + wr.WriteUint8(SyncByte) wr.WriteBit(0) // Transport error indicator (TEI) wr.WriteBit(1) // Payload unit start indicator (PUSI) @@ -191,9 +191,9 @@ func (m *Muxer) writeHeader(wr *bits.Writer, pid uint16) { } func (m *Muxer) writePSIHeader(wr *bits.Writer, tableID byte, size uint16) { - wr.WriteByte(0) // Pointer field + wr.WriteUint8(0) // Pointer field - wr.WriteByte(tableID) // Table ID + wr.WriteUint8(tableID) // Table ID wr.WriteBit(1) // Section syntax indicator wr.WriteBit(0) // Private bit @@ -206,8 +206,8 @@ func (m *Muxer) writePSIHeader(wr *bits.Writer, tableID byte, size uint16) { wr.WriteBits8(0, 5) // Version number wr.WriteBit(1) // Current/next indicator - wr.WriteByte(0) // Section number - wr.WriteByte(0) // Last section number + wr.WriteUint8(0) // Section number + wr.WriteUint8(0) // Last section number } func (m *Muxer) WriteTail(wr *bits.Writer) { diff --git a/pkg/mpegts/opus.go b/pkg/mpegts/opus.go index d6077ea4..67cba189 100644 --- a/pkg/mpegts/opus.go +++ b/pkg/mpegts/opus.go @@ -42,7 +42,7 @@ func opus_control_header(r *bits.Reader) int { var payload_size int for { - i := r.ReadByte() + i := r.ReadUint8() payload_size += int(i) if i < 255 { break @@ -58,7 +58,7 @@ func opus_control_header(r *bits.Reader) int { _ = r.ReadBits(13) } if control_extension_flag != 0 { - control_extension_length := r.ReadByte() + control_extension_length := r.ReadUint8() _ = r.ReadBytes(int(control_extension_length)) // reserved } diff --git a/pkg/mqtt/message.go b/pkg/mqtt/message.go index e3d34214..c9ee1b6b 100644 --- a/pkg/mqtt/message.go +++ b/pkg/mqtt/message.go @@ -19,7 +19,7 @@ const ( QOS1 = 0x02 ) -func (m *Message) WriteByte(b byte) { +func (m *Message) WriteUint8(b byte) { m.b = append(m.b, b) } @@ -37,7 +37,7 @@ func (m *Message) WriteLen(i int) { if i /= 128; i > 0 { b |= 0x80 } - m.WriteByte(b) + m.WriteUint8(b) } } @@ -58,12 +58,12 @@ const ( func NewConnect(clientID, username, password string) *Message { m := &Message{} - m.WriteByte(CONNECT) + m.WriteUint8(CONNECT) m.WriteLen(16 + len(clientID) + len(username) + len(password)) m.WriteString("MQTT") - m.WriteByte(4) // MQTT version - m.WriteByte(flagCleanStart | flagUsername | flagPassword) + m.WriteUint8(4) // MQTT version + m.WriteUint8(flagCleanStart | flagUsername | flagPassword) m.WriteUint16(30) // keepalive m.WriteString(clientID) @@ -74,18 +74,18 @@ func NewConnect(clientID, username, password string) *Message { func NewSubscribe(mid uint16, topic string, qos byte) *Message { m := &Message{} - m.WriteByte(SUBSCRIBE) + m.WriteUint8(SUBSCRIBE) m.WriteLen(5 + len(topic)) m.WriteUint16(mid) m.WriteString(topic) - m.WriteByte(qos) + m.WriteUint8(qos) return m } func NewPublish(topic string, payload []byte) *Message { m := &Message{} - m.WriteByte(PUBLISH) + m.WriteUint8(PUBLISH) m.WriteLen(2 + len(topic) + len(payload)) m.WriteString(topic) @@ -95,7 +95,7 @@ func NewPublish(topic string, payload []byte) *Message { func NewPublishQOS1(mid uint16, topic string, payload []byte) *Message { m := &Message{} - m.WriteByte(PUBLISH | QOS1) + m.WriteUint8(PUBLISH | QOS1) m.WriteLen(4 + len(topic) + len(payload)) m.WriteString(topic) diff --git a/pkg/nest/api.go b/pkg/nest/api.go index 4e9e4dbd..85927b78 100644 --- a/pkg/nest/api.go +++ b/pkg/nest/api.go @@ -170,7 +170,7 @@ func (a *API) ExchangeSDP(projectID, deviceID, offer string) (string, error) { maxRetries := 3 retryDelay := time.Second * 30 - for attempt := 0; attempt < maxRetries; attempt++ { + for attempt := range maxRetries { req, err := http.NewRequest("POST", uri, bytes.NewReader(b)) if err != nil { return "", err diff --git a/pkg/nest/client.go b/pkg/nest/client.go index 6a570913..8bf972a1 100644 --- a/pkg/nest/client.go +++ b/pkg/nest/client.go @@ -45,7 +45,7 @@ func Dial(rawURL string) (core.Producer, error) { var nestAPI *API var lastErr error - for attempt := 0; attempt < maxRetries; attempt++ { + for attempt := range maxRetries { nestAPI, err = NewAPI(cliendID, cliendSecret, refreshToken) if err == nil { break @@ -101,7 +101,7 @@ func rtcConn(nestAPI *API, rawURL, projectID, deviceID string) (*WebRTCClient, e retryDelay := time.Second * 30 var lastErr error - for attempt := 0; attempt < maxRetries; attempt++ { + for attempt := range maxRetries { rtcAPI, err := webrtc.NewAPI() if err != nil { return nil, err diff --git a/pkg/pcm/v1/pcm_test.go b/pkg/pcm/v1/pcm_test.go index 07b70b97..9b2ad9fd 100644 --- a/pkg/pcm/v1/pcm_test.go +++ b/pkg/pcm/v1/pcm_test.go @@ -8,7 +8,7 @@ import ( ) func TestPCMUtoPCM(t *testing.T) { - for pcmu := byte(0); pcmu < 255; pcmu++ { + for pcmu := range byte(255) { pcm1 := MuLawDecompressTable[pcmu] pcm2 := v2.PCMUtoPCM(pcmu) require.Equal(t, pcm1, pcm2) @@ -16,7 +16,7 @@ func TestPCMUtoPCM(t *testing.T) { } func TestPCMAtoPCM(t *testing.T) { - for pcma := byte(0); pcma < 255; pcma++ { + for pcma := range byte(255) { pcm1 := ALawDecompressTable[pcma] pcm2 := v2.PCMAtoPCM(pcma) require.Equal(t, pcm1, pcm2) diff --git a/pkg/ring/api.go b/pkg/ring/api.go index ea7c95ad..e57a6998 100644 --- a/pkg/ring/api.go +++ b/pkg/ring/api.go @@ -71,7 +71,7 @@ type RingApi struct { Using2FA bool PromptFor2FA string RefreshToken string - auth interface{} // EmailAuth or RefreshTokenAuth + auth any // EmailAuth or RefreshTokenAuth onTokenRefresh func(string) authMutex sync.Mutex session *SessionResponse @@ -93,12 +93,12 @@ type CameraData struct { type RingDeviceType string type RingDevicesResponse struct { - Doorbots []CameraData `json:"doorbots"` - AuthorizedDoorbots []CameraData `json:"authorized_doorbots"` - StickupCams []CameraData `json:"stickup_cams"` - AllCameras []CameraData `json:"all_cameras"` - Chimes []CameraData `json:"chimes"` - Other []map[string]interface{} `json:"other"` + Doorbots []CameraData `json:"doorbots"` + AuthorizedDoorbots []CameraData `json:"authorized_doorbots"` + StickupCams []CameraData `json:"stickup_cams"` + AllCameras []CameraData `json:"all_cameras"` + Chimes []CameraData `json:"chimes"` + Other []map[string]any `json:"other"` } const ( @@ -153,7 +153,7 @@ const ( sessionValidTime = 12 * time.Hour ) -func NewRestClient(auth interface{}, onTokenRefresh func(string)) (*RingApi, error) { +func NewRestClient(auth any, onTokenRefresh func(string)) (*RingApi, error) { var cacheKey string // Create cache key based on auth data @@ -400,7 +400,7 @@ func (c *RingApi) GetSocketTicket() (*SocketTicketResponse, error) { return &ticket, nil } -func (c *RingApi) Request(method, url string, body interface{}) ([]byte, error) { +func (c *RingApi) Request(method, url string, body any) ([]byte, error) { // Ensure we have a valid session if err := c.ensureSession(); err != nil { return nil, fmt.Errorf("session validation failed: %w", err) @@ -476,7 +476,7 @@ func (c *RingApi) Request(method, url string, body interface{}) ([]byte, error) // Handle 404 error with hardware_id reference - session issue if resp.StatusCode == 404 && strings.Contains(url, clientAPIBaseURL) { - var errorBody map[string]interface{} + var errorBody map[string]any if err := json.Unmarshal(responseBody, &errorBody); err == nil { if errorStr, ok := errorBody["error"].(string); ok && strings.Contains(errorStr, c.hardwareID) { // Session with hardware_id not found, refresh session @@ -523,10 +523,10 @@ func (c *RingApi) ensureSession() error { return fmt.Errorf("authentication failed while creating session: %w", err) } - sessionPayload := map[string]interface{}{ - "device": map[string]interface{}{ + sessionPayload := map[string]any{ + "device": map[string]any{ "hardware_id": c.hardwareID, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "api_version": apiVersion, "device_model": "ring-client-go", }, @@ -686,7 +686,7 @@ func generateHardwareID() string { return hex.EncodeToString(h.Sum(nil)[:16]) } -func interfaceSlice(slice interface{}) []CameraData { +func interfaceSlice(slice any) []CameraData { s := reflect.ValueOf(slice) if s.Kind() != reflect.Slice { return nil diff --git a/pkg/ring/client.go b/pkg/ring/client.go index fb77e198..15e96160 100644 --- a/pkg/ring/client.go +++ b/pkg/ring/client.go @@ -140,7 +140,7 @@ func Dial(rawURL string) (*Client, error) { return } - icePayload := map[string]interface{}{ + icePayload := map[string]any{ "ice": iceCandidate.Candidate, "mlineindex": iceCandidate.SDPMLineIndex, } @@ -200,7 +200,7 @@ func Dial(rawURL string) (*Client, error) { } // Send offer - offerPayload := map[string]interface{}{ + offerPayload := map[string]any{ "stream_options": map[string]bool{ "audio_enabled": true, "video_enabled": true, @@ -317,7 +317,7 @@ func (c *Client) AddTrack(media *core.Media, codec *core.Codec, track *core.Rece if webrtcProd, ok := c.prod.(*webrtc.Conn); ok { if media.Kind == core.KindAudio { // Enable speaker - speakerPayload := map[string]interface{}{ + speakerPayload := map[string]any{ "stealth_mode": false, } _ = c.wsClient.sendSessionMessage("camera_options", speakerPayload) diff --git a/pkg/ring/ws.go b/pkg/ring/ws.go index 51e72fe6..cbab88cc 100644 --- a/pkg/ring/ws.go +++ b/pkg/ring/ws.go @@ -142,8 +142,8 @@ func (c *WSClient) Close() error { close(c.closed) } - closePayload := map[string]interface{}{ - "reason": map[string]interface{}{ + closePayload := map[string]any{ + "reason": map[string]any{ "code": CloseReasonNormalClose, "text": "", }, @@ -198,7 +198,7 @@ func (c *WSClient) activateSession() error { return err } - streamPayload := map[string]interface{}{ + streamPayload := map[string]any{ "audio_enabled": true, "video_enabled": true, } @@ -210,7 +210,7 @@ func (c *WSClient) activateSession() error { return nil } -func (c *WSClient) sendSessionMessage(method string, payload map[string]interface{}) error { +func (c *WSClient) sendSessionMessage(method string, payload map[string]any) error { select { case <-c.closed: return nil @@ -222,7 +222,7 @@ func (c *WSClient) sendSessionMessage(method string, payload map[string]interfac defer c.wsMutex.Unlock() if payload == nil { - payload = make(map[string]interface{}) + payload = make(map[string]any) } payload["doorbot_id"] = c.cameraID @@ -230,7 +230,7 @@ func (c *WSClient) sendSessionMessage(method string, payload map[string]interfac payload["session_id"] = c.sessionID } - msg := map[string]interface{}{ + msg := map[string]any{ "method": method, "dialog_id": c.dialogID, "body": payload, diff --git a/pkg/roborock/iot/crypto.go b/pkg/roborock/iot/crypto.go index 7a4c641e..880e72e6 100644 --- a/pkg/roborock/iot/crypto.go +++ b/pkg/roborock/iot/crypto.go @@ -68,7 +68,7 @@ func encodeTimestamp(i uint32) string { func pad(plainText []byte, blockSize int) []byte { b0 := byte(blockSize - len(plainText)%blockSize) - for i := byte(0); i < b0; i++ { + for range b0 { plainText = append(plainText, b0) } return plainText diff --git a/pkg/rtsp/client.go b/pkg/rtsp/client.go index c9607321..9160c25b 100644 --- a/pkg/rtsp/client.go +++ b/pkg/rtsp/client.go @@ -419,7 +419,7 @@ func ListenUDPPair() (*net.UDPConn, *net.UDPConn, error) { listenUDPMu.Lock() defer listenUDPMu.Unlock() - for i := 0; i < listenUDPAttemps; i++ { + for range listenUDPAttemps { // Get a random even port from the OS ln1, err := net.ListenUDP("udp", &net.UDPAddr{IP: nil, Port: 0}) if err != nil { diff --git a/pkg/tapo/client.go b/pkg/tapo/client.go index e52250c3..362450bf 100644 --- a/pkg/tapo/client.go +++ b/pkg/tapo/client.go @@ -389,7 +389,7 @@ func securityEncode(s string) string { b := make([]byte, n) - for i := 0; i < n; i++ { + for i := range n { c1 := 187 c2 := 187 if i >= size { diff --git a/pkg/tcp/websocket/client.go b/pkg/tcp/websocket/client.go index e95ce1e4..670264f2 100644 --- a/pkg/tcp/websocket/client.go +++ b/pkg/tcp/websocket/client.go @@ -98,7 +98,7 @@ func (w *Client) Write(b []byte) (n int, err error) { return 0, err } - for i := 0; i < len(b); i++ { + for i := range len(b) { msg[i] = b[i] ^ mask[i%4] } diff --git a/pkg/tutk/crypto.go b/pkg/tutk/crypto.go index 469bd2bc..202dd023 100644 --- a/pkg/tutk/crypto.go +++ b/pkg/tutk/crypto.go @@ -43,7 +43,7 @@ func ReverseTransCodePartial(dst, src []byte) []byte { swap(tmp16, src16, n) - for i := 0; i < n; i++ { + for i := range n { dst16[i] = tmp16[i] ^ charlie[i] } @@ -111,7 +111,7 @@ func TransCodePartial(dst, src []byte) []byte { src16 = src16[16:] } - for i := 0; i < n; i++ { + for i := range n { tmp16[i] = src16[i] ^ charlie[i] } diff --git a/pkg/tuya/cloud_api.go b/pkg/tuya/cloud_api.go index c34d0fe4..541881af 100644 --- a/pkg/tuya/cloud_api.go +++ b/pkg/tuya/cloud_api.go @@ -208,7 +208,7 @@ func (c *TuyaCloudApiClient) loadWebrtcConfig() (*WebRTCConfig, error) { } if !webRTCConfigResponse.Success { - return nil, fmt.Errorf(webRTCConfigResponse.Msg) + return nil, fmt.Errorf("%s", webRTCConfigResponse.Msg) } err = json.Unmarshal([]byte(webRTCConfigResponse.Result.Skill), &c.skill) @@ -254,7 +254,7 @@ func (c *TuyaCloudApiClient) loadHubConfig() (config *MQTTConfig, err error) { } if !openIoTHubConfigResponse.Success { - return nil, fmt.Errorf(openIoTHubConfigResponse.Msg) + return nil, fmt.Errorf("%s", openIoTHubConfigResponse.Msg) } return &MQTTConfig{ diff --git a/pkg/tuya/mqtt.go b/pkg/tuya/mqtt.go index 5f64ef48..2f4fcf34 100644 --- a/pkg/tuya/mqtt.go +++ b/pkg/tuya/mqtt.go @@ -88,12 +88,12 @@ type MqttLowPowerMessage struct { S int `json:"s,omitempty"` Type string `json:"type,omitempty"` Data struct { - DevID string `json:"devId,omitempty"` - Online bool `json:"online,omitempty"` - LastOnlineChangeTime int64 `json:"lastOnlineChangeTime,omitempty"` - GwID string `json:"gwId,omitempty"` - Cmd string `json:"cmd,omitempty"` - Dps map[string]interface{} `json:"dps,omitempty"` + DevID string `json:"devId,omitempty"` + Online bool `json:"online,omitempty"` + LastOnlineChangeTime int64 `json:"lastOnlineChangeTime,omitempty"` + GwID string `json:"gwId,omitempty"` + Cmd string `json:"cmd,omitempty"` + Dps map[string]any `json:"dps,omitempty"` } `json:"data"` } @@ -395,7 +395,7 @@ func (c *TuyaMqttClient) onError(err error) { } } -func (c *TuyaMqttClient) sendMqttMessage(messageType string, protocol int, transactionID string, data interface{}) error { +func (c *TuyaMqttClient) sendMqttMessage(messageType string, protocol int, transactionID string, data any) error { if c.closed { return fmt.Errorf("mqtt client is closed, send mqtt message fail") } diff --git a/pkg/webrtc/api.go b/pkg/webrtc/api.go index 5551d65e..7599d6c9 100644 --- a/pkg/webrtc/api.go +++ b/pkg/webrtc/api.go @@ -264,10 +264,10 @@ func RegisterDefaultCodecs(m *webrtc.MediaEngine) error { } videoRTCPFeedback := []webrtc.RTCPFeedback{ - {"goog-remb", ""}, - {"ccm", "fir"}, - {"nack", ""}, - {"nack", "pli"}, + {Type: "goog-remb", Parameter: ""}, + {Type: "ccm", Parameter: "fir"}, + {Type: "nack", Parameter: ""}, + {Type: "nack", Parameter: "pli"}, } for _, codec := range []webrtc.RTPCodecParameters{ { diff --git a/pkg/webrtc/conn.go b/pkg/webrtc/conn.go index 924fd550..0a6e656d 100644 --- a/pkg/webrtc/conn.go +++ b/pkg/webrtc/conn.go @@ -208,8 +208,6 @@ func (c *Conn) getMediaCodec(remote *webrtc.TrackRemote) (*core.Media, *core.Cod // sends new codec with new payload type to same media // check GetTrack panic(core.Caller()) - - return nil, nil } func sanitizeIP6(host string) string { diff --git a/pkg/yaml/yaml.go b/pkg/yaml/yaml.go index 4672cb4c..ad657225 100644 --- a/pkg/yaml/yaml.go +++ b/pkg/yaml/yaml.go @@ -7,7 +7,7 @@ import ( "gopkg.in/yaml.v3" ) -func Unmarshal(in []byte, out interface{}) (err error) { +func Unmarshal(in []byte, out any) (err error) { return yaml.Unmarshal(in, out) } @@ -190,7 +190,7 @@ func addPrefix(src, pre []byte) (dst []byte) { func addIndent(in []byte, indent int) (dst []byte) { pre := make([]byte, indent) - for i := 0; i < indent; i++ { + for i := range indent { pre[i] = ' ' } return addPrefix(in, pre)