pax_global_header00006660000000000000000000000064142510131410014502gustar00rootroot0000000000000052 comment=4a0298918a92d7e285bdbf4e8e7ccedfdcd7a241 golang-github-k0swe-wsjtx-go-4.0.1/000077500000000000000000000000001425101314100170425ustar00rootroot00000000000000golang-github-k0swe-wsjtx-go-4.0.1/.github/000077500000000000000000000000001425101314100204025ustar00rootroot00000000000000golang-github-k0swe-wsjtx-go-4.0.1/.github/auto_assign.yml000066400000000000000000000012721425101314100234430ustar00rootroot00000000000000# Set to true to add reviewers to pull requests addReviewers: true # Set to true to add assignees to pull requests addAssignees: author # A list of reviewers to be added to pull requests (GitHub user name) reviewers: - xylo04 # A number of reviewers added to the pull request # Set 0 to add all the reviewers (default: 0) numberOfReviewers: 0 # A list of assignees, overrides reviewers if set # assignees: # - assigneeA # A number of assignees to add to the pull request # Set to 0 to add all of the assignees. # Uses numberOfReviewers if unset. # numberOfAssignees: 2 # A list of keywords to be skipped the process that add reviewers if pull requests include it # skipKeywords: # - wip golang-github-k0swe-wsjtx-go-4.0.1/.github/renovate.json000066400000000000000000000011241425101314100231160ustar00rootroot00000000000000{ "extends": [ ":separateMajorReleases", ":combinePatchMinorReleases", ":ignoreUnstable", ":prImmediately", ":semanticPrefixFixDepsChoreOthers", ":automergeDisabled", ":ignoreModulesAndTests", ":autodetectPinVersions", ":prHourlyLimit2", ":prConcurrentLimit20", "group:monorepos", "group:recommended", "helpers:disableTypesNodeMajor" ], "schedule": ["after 3am and before 7am on Tuesday"], "timezone": "America/Denver", "packageRules": [ { "matchUpdateTypes": ["patch", "pin", "digest"], "automerge": true } ] } golang-github-k0swe-wsjtx-go-4.0.1/.github/workflows/000077500000000000000000000000001425101314100224375ustar00rootroot00000000000000golang-github-k0swe-wsjtx-go-4.0.1/.github/workflows/assign_pr.yml000066400000000000000000000002431425101314100251460ustar00rootroot00000000000000name: 'Auto Assign' on: pull_request: types: [opened, ready_for_review] jobs: add-reviewers: uses: k0swe/.github/.github/workflows/assign_pr.yml@main golang-github-k0swe-wsjtx-go-4.0.1/.github/workflows/test.yml000066400000000000000000000007431425101314100241450ustar00rootroot00000000000000name: Test on: [push, pull_request] jobs: test: name: Run unit tests strategy: matrix: go-version: [ 1.15.x ] os: [ ubuntu-latest ] runs-on: ${{ matrix.os }} steps: - name: Install Go uses: actions/setup-go@v3 with: go-version: ${{ matrix.go-version }} - name: Checkout code uses: actions/checkout@v3 - name: Test run: go test ./... - name: Vet run: go vet ./... golang-github-k0swe-wsjtx-go-4.0.1/.gitignore000066400000000000000000000000711425101314100210300ustar00rootroot00000000000000# Generated driver binary wsjtx-go .idea/ .vscode/ .pc golang-github-k0swe-wsjtx-go-4.0.1/LICENSE000066400000000000000000000261161425101314100200550ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2020 Chris Keller Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. golang-github-k0swe-wsjtx-go-4.0.1/Makefile000066400000000000000000000002021425101314100204740ustar00rootroot00000000000000.PHONY: all all: test .PHONY: clean clean: rm ../golang-github-k0swe-wsjtx-go* .PHONY: test test: go test ./... go vet ./... golang-github-k0swe-wsjtx-go-4.0.1/README.md000066400000000000000000000020641425101314100203230ustar00rootroot00000000000000[![PkgGoDev](https://pkg.go.dev/badge/github.com/k0swe/wsjtx-go/v4)](https://pkg.go.dev/github.com/k0swe/wsjtx-go/v4) [![Go Report Card](https://goreportcard.com/badge/github.com/k0swe/wsjtx-go/v4)](https://goreportcard.com/report/github.com/k0swe/wsjtx-go/v4) [![Test](https://github.com/k0swe/wsjtx-go/workflows/Test/badge.svg?branch=v3)](https://github.com/k0swe/wsjtx-go/actions/workflows/test.yml?query=branch%3Av3) # wsjtx-go Golang binding for the WSJT-X amateur radio software's UDP communication interface. This library supports receiving and sending all WSJT-X message types up through WSJT-X v2.5.2. This is meant to be a fairly thin binding API, so familiarity with WSJT-X's [`NetworkMessage.hpp`](https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp) is recommended. ## Run This repository is designed as a library but includes a simple driver program to document basic integration. WSJT-X must be running and generating UDP packets for the driver to pick them up. From this directory: ```shell script go run cmd/main.go ``` golang-github-k0swe-wsjtx-go-4.0.1/cmd/000077500000000000000000000000001425101314100176055ustar00rootroot00000000000000golang-github-k0swe-wsjtx-go-4.0.1/cmd/main.go000066400000000000000000000046401425101314100210640ustar00rootroot00000000000000package main import ( "bufio" "log" "os" "reflect" "strings" "github.com/k0swe/wsjtx-go/v4" ) // Simple driver binary for wsjtx-go library. func main() { log.Println("Listening for WSJT-X...") wsjtxServer, err := wsjtx.MakeServer() if err != nil { log.Fatalf("%v", err) } wsjtxChannel := make(chan interface{}, 5) errChannel := make(chan error, 5) go wsjtxServer.ListenToWsjtx(wsjtxChannel, errChannel) stdinChannel := make(chan string, 5) go stdinCmd(stdinChannel) for { select { case err := <-errChannel: log.Printf("error: %v", err) case message := <-wsjtxChannel: handleServerMessage(message) case command := <-stdinChannel: command = strings.ToLower(command) handleCommand(command, wsjtxServer) } } } // Goroutine to listen to stdin. func stdinCmd(c chan string) { scanner := bufio.NewScanner(os.Stdin) for { for scanner.Scan() { input := scanner.Text() c <- input } if err := scanner.Err(); err != nil { log.Println(err) os.Exit(1) } } } // When we receive WSJT-X messages, display them. func handleServerMessage(message interface{}) { switch message.(type) { case wsjtx.HeartbeatMessage: log.Println("Heartbeat:", message) case wsjtx.StatusMessage: log.Println("Status:", message) case wsjtx.DecodeMessage: log.Println("Decode:", message) case wsjtx.ClearMessage: log.Println("Clear:", message) case wsjtx.QsoLoggedMessage: log.Println("QSO Logged:", message) case wsjtx.CloseMessage: log.Println("Close:", message) case wsjtx.WSPRDecodeMessage: log.Println("WSPR Decode:", message) case wsjtx.LoggedAdifMessage: log.Println("Logged Adif:", message) default: log.Println("Other:", reflect.TypeOf(message), message) } } // When we get a command from stdin, send WSJT-X a message. func handleCommand(command string, wsjtxServer wsjtx.Server) { var err error switch command { case "hb": log.Println("Sending Heartbeat") err = wsjtxServer.Heartbeat(wsjtx.HeartbeatMessage{ Id: "wsjtx-go", MaxSchema: 2, Version: "0.3.1", Revision: "e0d45c929", }) case "clear": log.Println("Sending Clear") err = wsjtxServer.Clear(wsjtx.ClearMessage{Id: "WSJT-X", Window: 2}) case "close": log.Println("Sending Close") err = wsjtxServer.Close(wsjtx.CloseMessage{Id: "WSJT-X"}) case "replay": log.Println("Sending Replay") err = wsjtxServer.Replay(wsjtx.ReplayMessage{Id: "WSJT-X"}) } if err != nil { log.Println(err) } } golang-github-k0swe-wsjtx-go-4.0.1/encoder.go000066400000000000000000000111551425101314100210130ustar00rootroot00000000000000package wsjtx import ( "bytes" "encoding/binary" "math" "github.com/mazznoer/csscolorparser" ) func encodeHeartbeat(msg HeartbeatMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(heartbeatNum) e.encodeUtf8(msg.Id) e.encodeUint32(msg.MaxSchema) e.encodeUtf8(msg.Version) e.encodeUtf8(msg.Revision) return e.finish() } func encodeClear(msg ClearMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(clearNum) e.encodeUtf8(msg.Id) e.encodeUint8(msg.Window) return e.finish() } func encodeReply(msg ReplyMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(replyNum) e.encodeUtf8(msg.Id) e.encodeUint32(msg.Time) e.encodeInt32(msg.Snr) e.encodeFloat64(msg.DeltaTimeSec) e.encodeUint32(msg.DeltaFrequencyHz) e.encodeUtf8(msg.Mode) e.encodeUtf8(msg.Message) e.encodeBool(msg.LowConfidence) e.encodeUint8(msg.Modifiers) return e.finish() } func encodeClose(msg CloseMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(closeNum) e.encodeUtf8(msg.Id) return e.finish() } func encodeReplay(msg ReplayMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(replayNum) e.encodeUtf8(msg.Id) return e.finish() } func encodeHaltTx(msg HaltTxMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(haltTxNum) e.encodeUtf8(msg.Id) e.encodeBool(msg.AutoTxOnly) return e.finish() } func encodeFreeText(msg FreeTextMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(freeTextNum) e.encodeUtf8(msg.Id) e.encodeUtf8(msg.Text) e.encodeBool(msg.Send) return e.finish() } func encodeLocation(msg LocationMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(locationNum) e.encodeUtf8(msg.Id) e.encodeUtf8(msg.Location) return e.finish() } func encodeHighlightCallsign(msg HighlightCallsignMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(highlightCallsignNum) e.encodeUtf8(msg.Id) e.encodeUtf8(msg.Callsign) if err := e.encodeColor(msg.BackgroundColor, msg.Reset); err != nil { return []byte{}, err } if err := e.encodeColor(msg.ForegroundColor, msg.Reset); err != nil { return []byte{}, err } e.encodeBool(msg.HighlightLast) return e.finish() } func encodeSwitchConfiguration(msg SwitchConfigurationMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(switchConfigurationNum) e.encodeUtf8(msg.Id) e.encodeUtf8(msg.ConfigurationName) return e.finish() } func encodeConfigure(msg ConfigureMessage) ([]byte, error) { e := newEncoder() e.encodeUint32(configureNum) e.encodeUtf8(msg.Id) e.encodeUtf8(msg.Mode) e.encodeUint32(msg.FrequencyTolerance) e.encodeUtf8(msg.Submode) e.encodeBool(msg.FastMode) e.encodeUint32(msg.TRPeriod) e.encodeUint32(msg.RxDF) e.encodeUtf8(msg.DXCall) e.encodeUtf8(msg.DXGrid) e.encodeBool(msg.GenerateMessages) return e.finish() } type encoder struct { buf *bytes.Buffer } func newEncoder() encoder { e := encoder{bytes.NewBuffer(make([]byte, bufLen))} e.buf.Reset() e.encodeUint32(magic) e.encodeUint32(schema) return e } func (e encoder) encodeUint8(num uint8) { e.buf.WriteByte(num) } func (e encoder) encodeUint16(num uint16) { bin := make([]byte, 2) binary.BigEndian.PutUint16(bin, num) e.buf.Write(bin) } func (e encoder) encodeUint32(num uint32) { bin := make([]byte, 4) binary.BigEndian.PutUint32(bin, num) e.buf.Write(bin) } func (e encoder) encodeUint64(num uint64) { bin := make([]byte, 8) binary.BigEndian.PutUint64(bin, num) e.buf.Write(bin) } func (e encoder) encodeBool(b bool) { if b { e.encodeUint8(1) } else { e.encodeUint8(0) } } func (e encoder) encodeInt32(num int32) { e.encodeUint32(uint32(num)) } func (e encoder) encodeFloat64(num float64) { e.encodeUint64(math.Float64bits(num)) } func (e encoder) encodeUtf8(str string) { strlen := uint32(len(str)) if strlen == 0 { e.encodeUint32(qDataStreamNull) return } e.encodeUint32(strlen) e.buf.WriteString(str) } func (e encoder) encodeColor(color string, invalid bool) error { // Spec enum: https://github.com/radekp/qt/blob/b881d8fb/src/gui/painting/qcolor.h#L70 const invalidSpec = uint8(0) const rgbSpec = uint8(1) const pad = uint16(0) spec := rgbSpec if invalid { spec = invalidSpec } // pre-multiplied to range 0x0 to 0xffff c, err := csscolorparser.Parse(color) if err != nil { return err } r, g, b, a := c.RGBA() // Field type and order: https://github.com/radekp/qt/blob/b881d8fb/src/gui/painting/qcolor.cpp#L2506 e.encodeUint8(spec) e.encodeUint16(uint16(a)) e.encodeUint16(uint16(r)) e.encodeUint16(uint16(g)) e.encodeUint16(uint16(b)) e.encodeUint16(pad) return nil } func (e encoder) finish() ([]byte, error) { ret := make([]byte, e.buf.Len()) _, err := e.buf.Read(ret) return ret, err } golang-github-k0swe-wsjtx-go-4.0.1/encoder_test.go000066400000000000000000000240351425101314100220530ustar00rootroot00000000000000package wsjtx import ( "encoding/hex" "reflect" "testing" ) func Test_encodeHeartbeat(t *testing.T) { type args struct { msg HeartbeatMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeHeartbeat", args: args{msg: HeartbeatMessage{ Id: "WSJT-X", MaxSchema: 3, Version: "2.2.2", Revision: "0d9b96"}}, want: decodeHex("adbccbda00000002000000000000000657534a542d580000000300000005322e322e3200000006306439623936"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeHeartbeat(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeHeartbeat() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeHeartbeat() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeClear(t *testing.T) { type args struct { msg ClearMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeClear", args: args{msg: ClearMessage{"WSJT-X", 2}}, want: decodeHex("adbccbda00000002000000030000000657534a542d5802"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeClear(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeClear() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeClear() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeReply(t *testing.T) { type args struct { msg ReplyMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeReply", args: args{msg: ReplyMessage{ Id: "WSJT-X", Time: 39435000, Snr: -5, DeltaTimeSec: 0.20000000298023224, DeltaFrequencyHz: 1302, Mode: "~", Message: "JA2EJP N4BP 73", LowConfidence: false, Modifiers: 0, }}, want: decodeHex("adbccbda00000002000000040000000657534a542d580259baf8fffffffb3fc99999a000000000000516000000017e0000000e4a4132454a50204e3442502037330000"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeReply(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeReply() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeReply() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeClose(t *testing.T) { type args struct { msg CloseMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeClose", args: args{msg: CloseMessage{"WSJT-X"}}, want: decodeHex("adbccbda00000002000000060000000657534a542d58"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeClose(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeClose() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeClose() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeReplay(t *testing.T) { type args struct { msg ReplayMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeReplay", args: args{msg: ReplayMessage{"WSJT-X"}}, want: decodeHex("adbccbda00000002000000070000000657534a542d58"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeReplay(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeReplay() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeReplay() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeHaltTx(t *testing.T) { type args struct { msg HaltTxMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeHaltTx", args: args{msg: HaltTxMessage{"WSJT-X", false}}, want: decodeHex("adbccbda00000002000000080000000657534a542d5800"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeHaltTx(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeHaltTx() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeHaltTx() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeFreeText(t *testing.T) { type args struct { msg FreeTextMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeFreeText", args: args{msg: FreeTextMessage{"WSJT-X", "😊 de πŸ‡ΊπŸ‡Έ", true}}, want: decodeHex("adbccbda00000002000000090000000657534a542d5800000010f09f988a20646520f09f87baf09f87b801"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeFreeText(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeFreeText() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeFreeText() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeLocation(t *testing.T) { type args struct { msg LocationMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeLocation", args: args{msg: LocationMessage{"WSJT-X", "DM79hu"}}, want: decodeHex("adbccbda000000020000000b0000000657534a542d5800000006444d37396875"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeLocation(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeLocation() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeLocation() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeHighlightCallsign(t *testing.T) { type args struct { msg HighlightCallsignMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeHighlightCallsign", args: args{msg: HighlightCallsignMessage{ Id: "WSJT-X", Callsign: "KM4ACK", BackgroundColor: "#eb4034", ForegroundColor: "#25272e", HighlightLast: true, Reset: false, }}, want: decodeHex("adbccbda000000020000000d0000000657534a542d58000000064b4d3441434b01ffffebeb40403434000001ffff252527272e2e000001"), wantErr: false, }, { name: "encodeHighlightCallsign_reset", args: args{msg: HighlightCallsignMessage{ Id: "WSJT-X", Callsign: "KM4ACK", BackgroundColor: "white", ForegroundColor: "white", HighlightLast: false, Reset: true, }}, want: decodeHex("adbccbda000000020000000d0000000657534a542d58000000064b4d3441434b00ffffffffffffffff000000ffffffffffffffff000000"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeHighlightCallsign(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeHighlightCallsign() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeHighlightCallsign() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeSwitchConfiguration(t *testing.T) { type args struct { msg SwitchConfigurationMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeSwitchConfiguration", args: args{msg: SwitchConfigurationMessage{"WSJT-X", "MyAlternateConfiguration"}}, want: decodeHex("adbccbda000000020000000e0000000657534a542d58000000184d79416c7465726e617465436f6e66696775726174696f6e"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeSwitchConfiguration(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeSwitchConfiguration() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeSwitchConfiguration() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func Test_encodeConfigure(t *testing.T) { type args struct { msg ConfigureMessage } tests := []struct { name string args args want []byte wantErr bool }{ { name: "encodeConfigure", args: args{msg: ConfigureMessage{ Id: "WSJT-X", Mode: "FT4", FrequencyTolerance: 35, Submode: "", FastMode: true, TRPeriod: 60, RxDF: 1000, DXCall: "T3ST", DXGrid: "JK73", GenerateMessages: true, }}, want: decodeHex("adbccbda000000020000000f0000000657534a542d580000000346543400000023ffffffff010000003c000003e80000000454335354000000044a4b373301"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := encodeConfigure(tt.args.msg) if (err != nil) != tt.wantErr { t.Errorf("encodeConfigure() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("encodeConfigure() got = %v, want %v", hex.EncodeToString(got), hex.EncodeToString(tt.want)) } }) } } func decodeHex(str string) []byte { bits, _ := hex.DecodeString(str) return bits } golang-github-k0swe-wsjtx-go-4.0.1/go.mod000066400000000000000000000003121425101314100201440ustar00rootroot00000000000000module github.com/k0swe/wsjtx-go/v4 go 1.15 require ( github.com/leemcloughlin/jdn v0.0.0-20201102080031-6f88db6a6bf2 github.com/mazznoer/csscolorparser v0.1.2 github.com/stretchr/testify v1.7.1 ) golang-github-k0swe-wsjtx-go-4.0.1/go.sum000066400000000000000000000026421425101314100202010ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/leemcloughlin/jdn v0.0.0-20201102080031-6f88db6a6bf2 h1:CdyD5OzAIzNFzpJ9WQRjJWj4pVRxZ9v15xdHnhvUPdw= github.com/leemcloughlin/jdn v0.0.0-20201102080031-6f88db6a6bf2/go.mod h1:LAowglanJPLb6WYSx3D1Ht/XE54OGIr0i4mz9kdbXrs= github.com/mazznoer/csscolorparser v0.1.2 h1:/UBHuQg792ePmGFzTQAC9u+XbFr7/HzP/Gj70Phyz2A= github.com/mazznoer/csscolorparser v0.1.2/go.mod h1:Aj22+L/rYN/Y6bj3bYqO3N6g1dtdHtGfQ32xZ5PJQic= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= golang-github-k0swe-wsjtx-go-4.0.1/integration/000077500000000000000000000000001425101314100213655ustar00rootroot00000000000000golang-github-k0swe-wsjtx-go-4.0.1/integration/receive_test.go000066400000000000000000000163241425101314100244030ustar00rootroot00000000000000package integration import ( "encoding/hex" "testing" "time" "github.com/k0swe/wsjtx-go/v4" ) type receiveCase struct { name string args []byte want receiveResult } type receiveResult struct { msg interface{} err error } func (s *integrationTestSuite) TestReceiveCases() { tests := []receiveCase{ { name: "Heartbeat", args: decode(`adbccbda00000002000000000000000657534a542d580000000200000005322e322e3200000006306439623936`), want: receiveResult{wsjtx.HeartbeatMessage{ Id: "WSJT-X", MaxSchema: 2, Version: "2.2.2", Revision: "0d9b96", }, nil}, }, { name: "Status 2.2.2", args: decode(`adbccbda00000002000000010000000657534a542d5800000000006bf0d000000003465438ffffffff000000032d313500000003465438000000000003730000079e000000054b3053574500000006444d37394c56ffffffff00ffffffff0000ffffffffffffffff0000000744656661756c74`), want: receiveResult{wsjtx.StatusMessage{ Id: "WSJT-X", DialFrequency: 7074000, Mode: "FT8", DxCall: "", Report: "-15", TxMode: "FT8", TxEnabled: false, Transmitting: false, Decoding: false, RxDF: 883, TxDF: 1950, DeCall: "K0SWE", DeGrid: "DM79LV", DxGrid: "", TxWatchdog: false, SubMode: "", FastMode: false, SpecialOperationMode: 0, FrequencyTolerance: 4294967295, TRPeriod: 4294967295, ConfigurationName: "Default", }, wsjtx.ParseError}, }, { name: "Status 2.3.1", args: decode(`adbccbda00000002000000010000000657534a542d5800000000006bf0d000000003465438ffffffff000000032d313500000003465438000000000003730000079e000000054b3053574500000006444d37394c56ffffffff00ffffffff0000ffffffffffffffff0000000744656661756c7400000000`), want: receiveResult{wsjtx.StatusMessage{ Id: "WSJT-X", DialFrequency: 7074000, Mode: "FT8", DxCall: "", Report: "-15", TxMode: "FT8", TxEnabled: false, Transmitting: false, Decoding: false, RxDF: 883, TxDF: 1950, DeCall: "K0SWE", DeGrid: "DM79LV", DxGrid: "", TxWatchdog: false, SubMode: "", FastMode: false, SpecialOperationMode: 0, FrequencyTolerance: 4294967295, TRPeriod: 4294967295, ConfigurationName: "Default", TxMessage: "", }, nil}, }, { name: "Decode", args: decode(`adbccbda00000002000000020000000657534a542d58010259baf8fffffffb3fc99999a000000000000516000000017e0000000e4a4132454a50204e3442502037330000`), want: receiveResult{wsjtx.DecodeMessage{ Id: "WSJT-X", New: true, Time: 39435000, Snr: -5, DeltaTimeSec: 0.20000000298023224, DeltaFrequencyHz: 1302, Mode: "~", Message: "JA2EJP N4BP 73", LowConfidence: false, OffAir: false, }, nil}, }, { name: "Clear", args: decode(`adbccbda00000002000000030000000657534a542d58`), want: receiveResult{wsjtx.ClearMessage{ Id: "WSJT-X", }, nil}, }, { name: "QSO Logged", args: decode(`adbccbda00000002000000050000000657534a542d5800000000002586110277ac48010000000454335354000000044a4b373300000000006bf86e00000003465438000000022d33000000022d37000000013500000007436f6d6d656e74000000034a6f6500000000002586110276c1e801000000055433535452000000054b3053574500000006444d37394c5600000002314200000002314400000003494f4e`), want: receiveResult{wsjtx.QsoLoggedMessage{ Id: "WSJT-X", DateTimeOff: parseTime("2020-10-30 11:29:57 +0000 UTC"), DxCall: "T3ST", DxGrid: "JK73", TxFrequency: 7075950, Mode: "FT8", ReportSent: "-3", ReportReceived: "-7", TxPower: "5", Comments: "Comment", Name: "Joe", DateTimeOn: parseTime("2020-10-30 11:28:57 +0000 UTC"), OperatorCall: "T3STR", MyCall: "K0SWE", MyGrid: "DM79LV", ExchangeSent: "1B", ExchangeReceived: "1D", ADIFPropagationMode: "ION", }, nil}, }, { name: "Close", args: decode(`adbccbda00000002000000060000000657534a542d58`), want: receiveResult{wsjtx.CloseMessage{ Id: "WSJT-X", }, nil}, }, { name: "WSPR Decode", args: decode(`adbccbda000000020000000a0000000657534a542d580102b5f840ffffffeebfe000000000000000000000006b6c7300000000000000054b3654475700000004434d39350000001700`), want: receiveResult{wsjtx.WSPRDecodeMessage{ Id: "WSJT-X", New: true, Time: 45480000, Snr: -18, DeltaTime: -0.5, Frequency: 7040115, Drift: 0, Callsign: "K6TGW", Grid: "CM95", Power: 23, OffAir: false, }, nil}, }, { name: "Logged Adif", args: decode(`adbccbda000000020000000c0000000657534a542d580000015c0a3c616469665f7665723a353e332e312e300a3c70726f6772616d69643a363e57534a542d580a3c454f483e0a3c63616c6c3a343e54335354203c677269647371756172653a343e4a4b3733203c6d6f64653a333e465438203c7273745f73656e743a323e2d38203c7273745f726376643a323e2d39203c71736f5f646174653a383e3230323031303330203c74696d655f6f6e3a363e313230383136203c71736f5f646174655f6f66663a383e3230323031303330203c74696d655f6f66663a363e313230393136203c62616e643a333e34306d203c667265713a383e372e303735393530203c73746174696f6e5f63616c6c7369676e3a353e4b30535745203c6d795f677269647371756172653a363e444d37394c56203c74785f7077723a313e35203c636f6d6d656e743a373e436f6d6d656e74203c6e616d653a343e4a657373203c6f70657261746f723a353e5433535452203c454f523e`), want: receiveResult{wsjtx.LoggedAdifMessage{ Id: "WSJT-X", Adif: ` 3.1.0 WSJT-X T3ST JK73 FT8 -8 -9 20201030 120816 20201030 120916 40m 7.075950 K0SWE DM79LV 5 Comment Jess T3STR `, }, nil}, }, } for _, tt := range tests { s.runReceiveTest(tt) } } func (s *integrationTestSuite) runReceiveTest(tt receiveCase) { s.T().Run(tt.name, func(t *testing.T) { msgPassed, errPassed := false, false if tt.want.err == nil { errPassed = true } _, err := s.fake.SendMessage(tt.args) s.Require().NoError(err) for { select { case msg := <-s.msgChan: s.Require().Equal(tt.want.msg, msg) msgPassed = true if msgPassed && errPassed { return } case chErr := <-s.errChan: s.Require().ErrorIs(chErr, tt.want.err) errPassed = true if msgPassed && errPassed { return } case <-time.After(50 * time.Millisecond): s.Fail("timeout") return } } }) } func decode(s string) []byte { input, _ := hex.DecodeString(s) return input } func parseTime(str string) time.Time { ret, _ := time.Parse("2006-01-02 15:04:05 -0700 MST", str) return ret } golang-github-k0swe-wsjtx-go-4.0.1/integration/send_test.go000066400000000000000000000125711425101314100237120ustar00rootroot00000000000000package integration import ( "math" "time" "github.com/k0swe/wsjtx-go/v4" ) func (s *integrationTestSuite) TestSendHeartbeat() { s.primeConnection() msg := wsjtx.HeartbeatMessage{ Id: "WSJT-X", MaxSchema: 3, Version: "2.2.2", Revision: "0d9b96"} want := decode(`adbccbda00000002000000000000000657534a542d580000000300000005322e322e3200000006306439623936`) s.T().Log("sending heartbeat struct") err := s.server.Heartbeat(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendClear() { s.primeConnection() msg := wsjtx.ClearMessage{Id: "WSJT-X", Window: 2} want := decode(`adbccbda00000002000000030000000657534a542d5802`) s.T().Log("sending clear struct") err := s.server.Clear(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendReply() { s.primeConnection() msg := wsjtx.ReplyMessage{ Id: "WSJT-X", Time: 1234, Snr: -15, DeltaTimeSec: 0.5, DeltaFrequencyHz: 2345, Mode: "FT8", Message: "CQ K0SWE DM79", LowConfidence: false, Modifiers: 0, } want := decode(`adbccbda00000002000000040000000657534a542d58000004d2fffffff13fe000000000000000000929000000034654380000000d4351204b3053574520444d37390000`) s.T().Log("sending reply struct") err := s.server.Reply(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendClose() { s.primeConnection() msg := wsjtx.CloseMessage{Id: "WSJT-X"} want := decode(`adbccbda00000002000000060000000657534a542d58`) s.T().Log("sending close struct") err := s.server.Close(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendReplay() { s.primeConnection() msg := wsjtx.ReplayMessage{Id: "WSJT-X"} want := decode(`adbccbda00000002000000070000000657534a542d58`) s.T().Log("sending replay struct") err := s.server.Replay(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendHaltTx() { s.primeConnection() msg := wsjtx.HaltTxMessage{Id: "WSJT-X", AutoTxOnly: false} want := decode(`adbccbda00000002000000080000000657534a542d5800`) s.T().Log("sending haltTx struct") err := s.server.HaltTx(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendFreeText() { s.primeConnection() msg := wsjtx.FreeTextMessage{ Id: "WSJT-X", Text: "J72IMS K0SWE R-15", Send: true, } want := decode(`adbccbda00000002000000090000000657534a542d58000000114a3732494d53204b3053574520522d313501`) s.T().Log("sending freeText struct") err := s.server.FreeText(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendLocation() { s.primeConnection() msg := wsjtx.LocationMessage{Id: "WSJT-X", Location: "DM79jx"} want := decode(`adbccbda000000020000000b0000000657534a542d5800000006444d37396a78`) s.T().Log("sending location struct") err := s.server.Location(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendHighlightCallsign() { s.primeConnection() msg := wsjtx.HighlightCallsignMessage{ Id: "WSJT-X", Callsign: "KM4ACK", BackgroundColor: "red", ForegroundColor: "black", HighlightLast: true, Reset: false, } want := decode(`adbccbda000000020000000d0000000657534a542d58000000064b4d3441434b01ffffffff00000000000001ffff000000000000000001`) s.T().Log("sending highlightCallsign struct") err := s.server.HighlightCallsign(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendSwitchConfiguration() { s.primeConnection() msg := wsjtx.SwitchConfigurationMessage{Id: "WSJT-X", ConfigurationName: "IC-7300"} want := decode(`adbccbda000000020000000e0000000657534a542d580000000749432d37333030`) s.T().Log("sending switchConfiguration struct") err := s.server.SwitchConfiguration(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) TestSendConfigure() { s.primeConnection() msg := wsjtx.ConfigureMessage{ Id: "WSJT-X", Mode: "JT9", FrequencyTolerance: math.MaxUint32, Submode: "", FastMode: false, TRPeriod: 0, RxDF: math.MaxUint32, DXCall: "KI6NAZ", DXGrid: "DM03", GenerateMessages: false, } want := decode(`adbccbda000000020000000f0000000657534a542d58000000034a5439ffffffffffffffff0000000000ffffffff000000064b49364e415a00000004444d303300`) s.T().Log("sending configure struct") err := s.server.Configure(msg) s.Require().NoError(err) s.waitForReceiveAndCheck(want) } func (s *integrationTestSuite) waitForReceiveAndCheck(want []byte) { for { select { case got := <-s.fake.ReceiveChan: s.T().Log("got receive bytes back from fake") s.Require().Equal(want, got) return case <-time.After(50 * time.Millisecond): s.Fail("timeout") return } } } func (s *integrationTestSuite) primeConnection() { // Because this is UDP, the server doesn't have an address for WSJTX until WSJTX has sent the // server a message. clearMsg := decode(`adbccbda00000002000000030000000657534a542d58`) _, err := s.fake.SendMessage(clearMsg) s.Require().NoError(err) <-s.msgChan s.T().Log("connection is primed for a send test") } golang-github-k0swe-wsjtx-go-4.0.1/integration/suite_test.go000066400000000000000000000020141425101314100241010ustar00rootroot00000000000000package integration import ( "net" "strconv" "testing" "github.com/k0swe/wsjtx-go/v4" "github.com/stretchr/testify/suite" ) type integrationTestSuite struct { suite.Suite server wsjtx.Server msgChan chan interface{} errChan chan error fake *WsjtxFake } func TestIntegrationSuite(t *testing.T) { suite.Run(t, &integrationTestSuite{}) } func (s *integrationTestSuite) SetupSuite() { var err error s.msgChan = make(chan interface{}, 5) s.errChan = make(chan error, 5) s.server, err = wsjtx.MakeServerGiven(net.ParseIP("127.0.0.1"), 0) s.Require().NoError(err) go s.server.ListenToWsjtx(s.msgChan, s.errChan) s.T().Log("suite started server listening") } func (s *integrationTestSuite) SetupTest() { _, portStr, _ := net.SplitHostPort(s.server.LocalAddr().String()) port, _ := strconv.Atoi(portStr) var err error s.fake, err = NewFake(&net.UDPAddr{Port: port}, s.T()) s.Require().NoError(err) s.T().Log("suite reports fake is connected") } func (s *integrationTestSuite) TearDownTest() { s.fake.Stop() } golang-github-k0swe-wsjtx-go-4.0.1/integration/wsjtx-fake.go000066400000000000000000000032161425101314100240010ustar00rootroot00000000000000package integration import ( "errors" "fmt" "io" "net" "os" "testing" "time" ) // WsjtxFake is a test double that acts like WSJTX. It connects to the wsjtx-go server as a client, // but is actually a stub controlled by the integration test cases. type WsjtxFake struct { t *testing.T conn *net.UDPConn ReceiveChan chan []byte stop chan bool } // NewFake initializes a new fake WSJTX program on an OS-assigned port. func NewFake(addr *net.UDPAddr, t *testing.T) (*WsjtxFake, error) { conn, err := net.DialUDP("udp", &net.UDPAddr{Port: 0}, addr) if err != nil { return &WsjtxFake{}, err } t.Logf("fake is connected to %v", conn.RemoteAddr()) w := &WsjtxFake{t, conn, make(chan []byte, 5), make(chan bool, 1)} go w.handleReceive() return w, nil } // SendMessage immediately sends the given payload out from the WSJTX fake. func (w *WsjtxFake) SendMessage(payload []byte) (int, error) { w.t.Log("sending message") return w.conn.Write(payload) } func (w *WsjtxFake) handleReceive() { b := make([]byte, 2048) w.t.Log("listening for receives") for { select { case <-w.stop: w.t.Log("stopping") close(w.ReceiveChan) _ = w.conn.Close() return default: _ = w.conn.SetDeadline(time.Now().Add(1 * time.Millisecond)) n, err := w.conn.Read(b) if err != nil { if err != io.EOF && !errors.Is(err, os.ErrDeadlineExceeded) { w.t.Log(fmt.Errorf("got an error while reading UDP: %w", err)) } } if n > 0 { tmp := make([]byte, n) copy(tmp, b[:n]) w.t.Logf("received %d bytes, putting on channel", n) w.ReceiveChan <- tmp } } } } func (w *WsjtxFake) Stop() { w.stop <- true } golang-github-k0swe-wsjtx-go-4.0.1/messages.go000066400000000000000000000264221425101314100212060ustar00rootroot00000000000000package wsjtx import ( "time" ) /* The heartbeat message shall be sent on a periodic basis every 15 seconds. This message is intended to be used by servers to detect the presence of a client and also the unexpected disappearance of a client and by clients to learn the schema negotiated by the server after it receives the initial heartbeat message from a client. Out/In. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l110 */ type HeartbeatMessage struct { Id string `json:"id"` MaxSchema uint32 `json:"maxSchemaVersion"` Version string `json:"version"` Revision string `json:"revision"` } const heartbeatNum = 0 /* WSJT-X sends this status message when various internal state changes to allow the server to track the relevant state of each client without the need for polling commands. Out only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l141 */ type StatusMessage struct { Id string `json:"id"` DialFrequency uint64 `json:"dialFrequency"` Mode string `json:"mode"` DxCall string `json:"dxCall"` Report string `json:"report"` TxMode string `json:"txMode"` TxEnabled bool `json:"txEnabled"` Transmitting bool `json:"transmitting"` Decoding bool `json:"decoding"` RxDF uint32 `json:"rxDeltaFreq"` TxDF uint32 `json:"txDeltaFreq"` DeCall string `json:"deCall"` DeGrid string `json:"deGrid"` DxGrid string `json:"dxGrid"` TxWatchdog bool `json:"txWatchdog"` SubMode string `json:"submode"` FastMode bool `json:"fastMode"` SpecialOperationMode uint8 `json:"specialMode"` FrequencyTolerance uint32 `json:"frequencyTolerance"` TRPeriod uint32 `json:"txRxPeriod"` ConfigurationName string `json:"configName"` TxMessage string `json:"txMessage"` } const statusNum = 1 /* The decode message is sent when a new decode is completed, in this case the 'New' field is true. It is also used in response to a "Replay" message where each old decode in the "Band activity" window, that has not been erased, is sent in order as a one of these messages with the 'New' field set to false. Out only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l208 */ type DecodeMessage struct { Id string `json:"id"` New bool `json:"new"` Time uint32 `json:"time"` Snr int32 `json:"snr"` DeltaTimeSec float64 `json:"deltaTime"` DeltaFrequencyHz uint32 `json:"deltaFrequency"` Mode string `json:"mode"` Message string `json:"message"` LowConfidence bool `json:"lowConfidence"` OffAir bool `json:"offAir"` } const decodeNum = 2 /* This message is send when all prior "Decode" messages in the "Band Activity" window have been discarded and therefore are no long available for actioning with a "Reply" message. The Window argument can be one of the following values: 0 - clear the "Band Activity" window (default) 1 - clear the "Rx Frequency" window 2 - clear both "Band Activity" and "Rx Frequency" windows Out/In. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l234 */ type ClearMessage struct { Id string `json:"id"` Window uint8 `json:"window"` // In only } const clearNum = 3 /* In order for a server to provide a useful cooperative service to WSJT-X it is possible for it to initiate a QSO by sending this message to a client. WSJT-X filters this message and only acts upon it if the message exactly describes a prior decode and that decode is a CQ or QRZ message. The action taken is exactly equivalent to the user double clicking the message in the "Band activity" window. In only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l255 */ type ReplyMessage struct { Id string `json:"id"` Time uint32 `json:"time"` Snr int32 `json:"snr"` DeltaTimeSec float64 `json:"deltaTime"` DeltaFrequencyHz uint32 `json:"deltaFrequency"` Mode string `json:"mode"` Message string `json:"message"` LowConfidence bool `json:"lowConfidence"` Modifiers uint8 `json:"modifiers"` } const replyNum = 4 /* The QSO logged message is sent when the WSJT-X user accepts the "Log QSO" dialog by clicking the "OK" button. Out only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l295 */ type QsoLoggedMessage struct { Id string `json:"id"` DateTimeOff time.Time `json:"dateTimeOff"` DxCall string `json:"dxCall"` DxGrid string `json:"dxGrid"` TxFrequency uint64 `json:"txFrequency"` Mode string `json:"mode"` ReportSent string `json:"reportSent"` ReportReceived string `json:"reportReceived"` TxPower string `json:"txPower"` Comments string `json:"comments"` Name string `json:"name"` DateTimeOn time.Time `json:"dateTimeOn"` OperatorCall string `json:"operatorCall"` MyCall string `json:"myCall"` MyGrid string `json:"myGrid"` ExchangeSent string `json:"exchangeSent"` ExchangeReceived string `json:"exchangeReceived"` ADIFPropagationMode string `json:"propagationMode"` } const qsoLoggedNum = 5 /* Close is sent by a client immediately prior to it shutting down gracefully. Out/In. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l320 */ type CloseMessage struct { Id string `json:"id"` } const closeNum = 6 /* When a server starts it may be useful for it to determine the state of preexisting clients. Sending this message to each client as it is discovered will cause that client (WSJT-X) to send a "Decode" message for each decode currently in its "Band activity" window. In only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l328 */ type ReplayMessage struct { Id string `json:"id"` } const replayNum = 7 /* The server may stop a client from transmitting messages either immediately or at the end of the current transmission period using this message. In only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l343 */ type HaltTxMessage struct { Id string `json:"id"` AutoTxOnly bool `json:"autoTxOnly"` } const haltTxNum = 8 /* This message allows the server to set the current free text message content. Sending this message with a non-empty "Text" field is equivalent to typing a new message (old contents are discarded) in to the WSJT-X free text message field or "Tx5" field (both are updated) and if the "Send" flag is set then clicking the "Now" radio button for the "Tx5" field if tab one is current or clicking the "Free msg" radio button if tab two is current. In only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l352 */ type FreeTextMessage struct { Id string `json:"id"` Text string `json:"text"` Send bool `json:"send"` } const freeTextNum = 9 /* The decode message is sent when a new decode is completed, in this case the 'New' field is true. Out only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l383 */ type WSPRDecodeMessage struct { Id string `json:"id"` New bool `json:"new"` Time uint32 `json:"time"` Snr int32 `json:"snr"` DeltaTime float64 `json:"deltaTime"` Frequency uint64 `json:"frequency"` Drift int32 `json:"drift"` Callsign string `json:"callsign"` Grid string `json:"grid"` Power int32 `json:"power"` OffAir bool `json:"offAir"` } const wsprDecodeNum = 10 /* This message allows the server to set the current current geographical location of operation. The supplied location is not persistent but is used as a session lifetime replacement loction that overrides the Maidenhead grid locater set in the application settings. In only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l406 */ type LocationMessage struct { Id string `json:"id"` Location string `json:"location"` } const locationNum = 11 /* The logged ADIF message is sent to the server(s) when the WSJT-X user accepts the "Log QSO" dialog by clicking the "OK" button. Out only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l423 */ type LoggedAdifMessage struct { Id string `json:"id"` Adif string `json:"adif"` } const loggedAdifNum = 12 /* The server may send this message at any time. The message specifies the background and foreground color that will be used to highlight the specified callsign in the decoded messages printed in the Band Activity panel. To clear and cancel highlighting send an invalid QColor value for either or both of the background and foreground fields. In only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l444 */ type HighlightCallsignMessage struct { Id string `json:"id"` Callsign string `json:"callsign"` BackgroundColor string `json:"backgroundColor"` ForegroundColor string `json:"foregroundColor"` HighlightLast bool `json:"highlightLast"` // This field is not part of the WSJT-X message and is specific to the golang library. It is a // necessary addition to be able to reset the highlighting. QT's color has a sentinel value in // QColor to signal an "invalid" color; golang image/color doesn't have that, so we add this // field. If this is true, BackgroundColor and ForegroundColor become "invalid" colors. Reset bool `json:"reset"` } const highlightCallsignNum = 13 /* The server may send this message at any time. The message specifies the name of the configuration to switch to. The new configuration must exist. In only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l445 */ type SwitchConfigurationMessage struct { Id string `json:"id"` ConfigurationName string `json:"configurationName"` } const switchConfigurationNum = 14 /* The server may send this message at any time. The message specifies various configuration options. For utf8 string fields an empty value implies no change, for the quint32 Rx DF and Frequency Tolerance fields the maximum quint32 value implies no change. Invalid or unrecognized values will be silently ignored. In only. https://sourceforge.net/p/wsjt/wsjtx/ci/wsjtx-2.5.2/tree/Network/NetworkMessage.hpp#l479 */ type ConfigureMessage struct { Id string `json:"id"` Mode string `json:"mode"` FrequencyTolerance uint32 `json:"frequencyTolerance"` Submode string `json:"submode"` FastMode bool `json:"fastMode"` TRPeriod uint32 `json:"trPeriod"` RxDF uint32 `json:"rxDF"` DXCall string `json:"dxCall"` DXGrid string `json:"dxGrid"` GenerateMessages bool `json:"generateMessages"` } const configureNum = 15 golang-github-k0swe-wsjtx-go-4.0.1/parser.go000066400000000000000000000225001425101314100206640ustar00rootroot00000000000000package wsjtx import ( "encoding/binary" "errors" "fmt" "math" "reflect" "time" "github.com/leemcloughlin/jdn" ) type parser struct { buffer []byte length int cursor int } var ParseError = errors.New("parse error") var notEnoughBytes = fmt.Errorf("%w: fewer bytes than expected, maybe an older version of WSJTX", ParseError) // Parse messages following the interface laid out in // https://sourceforge.net/p/wsjt/wsjtx/ci/master/tree/Network/NetworkMessage.hpp. This only parses // "Out" or "In/Out" message types and does not include "In" types because they will never be // received by WSJT-X. func parseMessage(buffer []byte, length int) (interface{}, error) { p := parser{buffer: buffer, length: length, cursor: 0} m, err := p.parseUint32() if err != nil { return nil, ParseError } if m != magic { return nil, fmt.Errorf("%w: packet is not speaking the WSJT-X protocol", ParseError) } sch, err := p.parseUint32() if err != nil { return nil, ParseError } if sch != schema { return nil, fmt.Errorf("%w: got a schema version I wasn't expecting: %d", ParseError, sch) } messageType, _ := p.parseUint32() switch messageType { case heartbeatNum: heartbeat, err := p.parseHeartbeat() if err != nil { return heartbeat, err } err = p.checkParse(heartbeat) return heartbeat, err case statusNum: status, err := p.parseStatus() if err != nil { return status, err } err = p.checkParse(status) return status, err case decodeNum: decode, err := p.parseDecode() if err != nil { return decode, err } err = p.checkParse(decode) return decode, err case clearNum: clear, err := p.parseClear() if err != nil { return clear, err } err = p.checkParse(clear) return clear, err case qsoLoggedNum: qsoLogged, err := p.parseQsoLogged() if err != nil { return qsoLogged, err } err = p.checkParse(qsoLogged) return qsoLogged, err case closeNum: closeMsg, err := p.parseClose() if err != nil { return closeMsg, err } err = p.checkParse(closeMsg) return closeMsg, err case wsprDecodeNum: wspr, err := p.parseWsprDecode() if err != nil { return wspr, err } err = p.checkParse(wspr) return wspr, err case loggedAdifNum: loggedAdif, err := p.parseLoggedAdif() if err != nil { return loggedAdif, err } err = p.checkParse(loggedAdif) return loggedAdif, err } return nil, fmt.Errorf("%w: unknown message type %d", ParseError, messageType) } // Quick sanity check that we parsed all of the message bytes func (p *parser) checkParse(message interface{}) error { if p.cursor != p.length { return fmt.Errorf("%w %s: there were %d bytes left over", ParseError, reflect.TypeOf(message).Name(), p.length-p.cursor) } return nil } func (p *parser) parseHeartbeat() (HeartbeatMessage, error) { var err error heartbeatMessage := HeartbeatMessage{} heartbeatMessage.Id, err = p.parseUtf8() heartbeatMessage.MaxSchema, err = p.parseUint32() heartbeatMessage.Version, err = p.parseUtf8() heartbeatMessage.Revision, err = p.parseUtf8() return heartbeatMessage, err } func (p *parser) parseStatus() (StatusMessage, error) { var err error statusMessage := StatusMessage{} statusMessage.Id, err = p.parseUtf8() statusMessage.DialFrequency, err = p.parseUint64() statusMessage.Mode, err = p.parseUtf8() statusMessage.DxCall, err = p.parseUtf8() statusMessage.Report, err = p.parseUtf8() statusMessage.TxMode, err = p.parseUtf8() statusMessage.TxEnabled, err = p.parseBool() statusMessage.Transmitting, err = p.parseBool() statusMessage.Decoding, err = p.parseBool() statusMessage.RxDF, err = p.parseUint32() statusMessage.TxDF, err = p.parseUint32() statusMessage.DeCall, err = p.parseUtf8() statusMessage.DeGrid, err = p.parseUtf8() statusMessage.DxGrid, err = p.parseUtf8() statusMessage.TxWatchdog, err = p.parseBool() statusMessage.SubMode, err = p.parseUtf8() statusMessage.FastMode, err = p.parseBool() statusMessage.SpecialOperationMode, err = p.parseUint8() statusMessage.FrequencyTolerance, err = p.parseUint32() statusMessage.TRPeriod, err = p.parseUint32() statusMessage.ConfigurationName, err = p.parseUtf8() statusMessage.TxMessage, err = p.parseUtf8() return statusMessage, err } func (p *parser) parseDecode() (DecodeMessage, error) { var err error decodeMessage := DecodeMessage{} decodeMessage.Id, err = p.parseUtf8() decodeMessage.New, err = p.parseBool() decodeMessage.Time, err = p.parseUint32() decodeMessage.Snr, err = p.parseInt32() decodeMessage.DeltaTimeSec, err = p.parseFloat64() decodeMessage.DeltaFrequencyHz, err = p.parseUint32() decodeMessage.Mode, err = p.parseUtf8() decodeMessage.Message, err = p.parseUtf8() decodeMessage.LowConfidence, err = p.parseBool() decodeMessage.OffAir, err = p.parseBool() return decodeMessage, err } func (p *parser) parseClear() (ClearMessage, error) { var err error clearMessage := ClearMessage{} clearMessage.Id, err = p.parseUtf8() return clearMessage, err } func (p *parser) parseQsoLogged() (QsoLoggedMessage, error) { var err error qsoLoggedMessage := QsoLoggedMessage{} qsoLoggedMessage.Id, err = p.parseUtf8() qsoLoggedMessage.DateTimeOff, err = p.parseQDateTime() qsoLoggedMessage.DxCall, err = p.parseUtf8() qsoLoggedMessage.DxGrid, err = p.parseUtf8() qsoLoggedMessage.TxFrequency, err = p.parseUint64() qsoLoggedMessage.Mode, err = p.parseUtf8() qsoLoggedMessage.ReportSent, err = p.parseUtf8() qsoLoggedMessage.ReportReceived, err = p.parseUtf8() qsoLoggedMessage.TxPower, err = p.parseUtf8() qsoLoggedMessage.Comments, err = p.parseUtf8() qsoLoggedMessage.Name, err = p.parseUtf8() qsoLoggedMessage.DateTimeOn, err = p.parseQDateTime() qsoLoggedMessage.OperatorCall, err = p.parseUtf8() qsoLoggedMessage.MyCall, err = p.parseUtf8() qsoLoggedMessage.MyGrid, err = p.parseUtf8() qsoLoggedMessage.ExchangeSent, err = p.parseUtf8() qsoLoggedMessage.ExchangeReceived, err = p.parseUtf8() qsoLoggedMessage.ADIFPropagationMode, err = p.parseUtf8() return qsoLoggedMessage, err } func (p *parser) parseClose() (CloseMessage, error) { var err error closeMessage := CloseMessage{} closeMessage.Id, err = p.parseUtf8() return closeMessage, err } func (p *parser) parseWsprDecode() (WSPRDecodeMessage, error) { var err error wsprDecodeMessage := WSPRDecodeMessage{} wsprDecodeMessage.Id, err = p.parseUtf8() wsprDecodeMessage.New, err = p.parseBool() wsprDecodeMessage.Time, err = p.parseUint32() wsprDecodeMessage.Snr, err = p.parseInt32() wsprDecodeMessage.DeltaTime, err = p.parseFloat64() wsprDecodeMessage.Frequency, err = p.parseUint64() wsprDecodeMessage.Drift, err = p.parseInt32() wsprDecodeMessage.Callsign, err = p.parseUtf8() wsprDecodeMessage.Grid, err = p.parseUtf8() wsprDecodeMessage.Power, err = p.parseInt32() wsprDecodeMessage.OffAir, err = p.parseBool() return wsprDecodeMessage, err } func (p *parser) parseLoggedAdif() (LoggedAdifMessage, error) { var err error loggedAdifMessage := LoggedAdifMessage{} loggedAdifMessage.Id, err = p.parseUtf8() loggedAdifMessage.Adif, err = p.parseUtf8() return loggedAdifMessage, err } func (p *parser) parseUint8() (uint8, error) { if len(p.buffer) < p.cursor { return 0, notEnoughBytes } value := p.buffer[p.cursor] p.cursor += 1 return value, nil } func (p *parser) parseUtf8() (string, error) { strlen, err := p.parseUint32() if err != nil { return "", err } if strlen == uint32(qDataStreamNull) { // this is a sentinel value meaning "null" in QDataStream, but Golang can't have nil strings strlen = 0 } end := p.cursor + int(strlen) value := string(p.buffer[p.cursor:end]) p.cursor += int(strlen) return value, nil } func (p *parser) parseUint32() (uint32, error) { end := p.cursor + 4 if len(p.buffer) < end { return 0, notEnoughBytes } value := binary.BigEndian.Uint32(p.buffer[p.cursor:end]) p.cursor += 4 return value, nil } func (p *parser) parseInt32() (int32, error) { end := p.cursor + 4 if len(p.buffer) < end { return 0, notEnoughBytes } value := int32(binary.BigEndian.Uint32(p.buffer[p.cursor:end])) p.cursor += 4 return value, nil } func (p *parser) parseUint64() (uint64, error) { end := p.cursor + 8 if len(p.buffer) < end { return 0, notEnoughBytes } value := binary.BigEndian.Uint64(p.buffer[p.cursor:end]) p.cursor += 8 return value, nil } func (p *parser) parseFloat64() (float64, error) { end := p.cursor + 8 if len(p.buffer) < end { return 0, notEnoughBytes } bits := binary.BigEndian.Uint64(p.buffer[p.cursor:end]) value := math.Float64frombits(bits) p.cursor += 8 return value, nil } func (p *parser) parseBool() (bool, error) { if len(p.buffer) < p.cursor { return false, notEnoughBytes } value := p.buffer[p.cursor] != 0 p.cursor += 1 return value, nil } func (p *parser) parseQDateTime() (time.Time, error) { julianDay, err := p.parseUint64() year, month, day := jdn.FromNumber(int(julianDay)) msMid, err := p.parseUint32() msSinceMidnight := int(msMid) hour := msSinceMidnight / 3600000 msSinceMidnight -= hour * 3600000 minute := msSinceMidnight / 60000 msSinceMidnight -= minute * 60000 second := msSinceMidnight / 1000 timespec, err := p.parseUint8() var value time.Time switch timespec { case 0: // local value = time.Date(year, month, day, hour, minute, second, 0, time.Local) case 1: // UTC value = time.Date(year, month, day, hour, minute, second, 0, time.UTC) default: return value, fmt.Errorf("got a timespec I wasn't expecting: %d", timespec) } return value, err } golang-github-k0swe-wsjtx-go-4.0.1/parser_test.go000066400000000000000000000155571425101314100217410ustar00rootroot00000000000000package wsjtx import ( "encoding/hex" "errors" "reflect" "testing" "time" ) type parseArgs struct { buffer []byte length int } type parseResult struct { message interface{} err error } func TestParseMessage(t *testing.T) { tests := []struct { name string args parseArgs want parseResult }{ { name: "Parse Heartbeat", args: argsFrom(`adbccbda00000002000000000000000657534a542d580000000300000005322e322e3200000006306439623936`), want: parseResult{HeartbeatMessage{ Id: "WSJT-X", MaxSchema: 3, Version: "2.2.2", Revision: "0d9b96", }, nil}, }, { name: "Parse Status 2.2.2", args: argsFrom(`adbccbda00000002000000010000000657534a542d5800000000006bf0d000000003465438ffffffff000000032d313500000003465438000000000003730000079e000000054b3053574500000006444d37394c56ffffffff00ffffffff0000ffffffffffffffff0000000744656661756c74`), want: parseResult{StatusMessage{ Id: "WSJT-X", DialFrequency: 7074000, Mode: "FT8", DxCall: "", Report: "-15", TxMode: "FT8", TxEnabled: false, Transmitting: false, Decoding: false, RxDF: 883, TxDF: 1950, DeCall: "K0SWE", DeGrid: "DM79LV", DxGrid: "", TxWatchdog: false, SubMode: "", FastMode: false, SpecialOperationMode: 0, FrequencyTolerance: 4294967295, TRPeriod: 4294967295, ConfigurationName: "Default", }, ParseError}, }, { name: "Parse Status 2.3.1", args: argsFrom(`adbccbda00000002000000010000000657534a542d5800000000006bf0d000000003465438ffffffff000000032d313500000003465438000000000003730000079e000000054b3053574500000006444d37394c56ffffffff00ffffffff0000ffffffffffffffff0000000744656661756c7400000000`), want: parseResult{StatusMessage{ Id: "WSJT-X", DialFrequency: 7074000, Mode: "FT8", DxCall: "", Report: "-15", TxMode: "FT8", TxEnabled: false, Transmitting: false, Decoding: false, RxDF: 883, TxDF: 1950, DeCall: "K0SWE", DeGrid: "DM79LV", DxGrid: "", TxWatchdog: false, SubMode: "", FastMode: false, SpecialOperationMode: 0, FrequencyTolerance: 4294967295, TRPeriod: 4294967295, ConfigurationName: "Default", TxMessage: "", }, nil}, }, { name: "Parse Decode", args: argsFrom(`adbccbda00000002000000020000000657534a542d58010259baf8fffffffb3fc99999a000000000000516000000017e0000000e4a4132454a50204e3442502037330000`), want: parseResult{DecodeMessage{ Id: "WSJT-X", New: true, Time: 39435000, Snr: -5, DeltaTimeSec: 0.20000000298023224, DeltaFrequencyHz: 1302, Mode: "~", Message: "JA2EJP N4BP 73", LowConfidence: false, OffAir: false, }, nil}, }, { name: "Parse Clear", args: argsFrom(`adbccbda00000002000000030000000657534a542d58`), want: parseResult{ClearMessage{ Id: "WSJT-X", }, nil}, }, { name: "Parse QSO Logged", args: argsFrom(`adbccbda00000002000000050000000657534a542d5800000000002586110277ac48010000000454335354000000044a4b373300000000006bf86e00000003465438000000022d33000000022d37000000013500000007436f6d6d656e74000000034a6f6500000000002586110276c1e801000000055433535452000000054b3053574500000006444d37394c5600000002314200000002314400000003494f4e`), want: parseResult{QsoLoggedMessage{ Id: "WSJT-X", DateTimeOff: parseTime("2020-10-30 11:29:57 +0000 UTC"), DxCall: "T3ST", DxGrid: "JK73", TxFrequency: 7075950, Mode: "FT8", ReportSent: "-3", ReportReceived: "-7", TxPower: "5", Comments: "Comment", Name: "Joe", DateTimeOn: parseTime("2020-10-30 11:28:57 +0000 UTC"), OperatorCall: "T3STR", MyCall: "K0SWE", MyGrid: "DM79LV", ExchangeSent: "1B", ExchangeReceived: "1D", ADIFPropagationMode: "ION", }, nil}, }, { name: "Parse Close", args: argsFrom(`adbccbda00000002000000060000000657534a542d58`), want: parseResult{CloseMessage{ Id: "WSJT-X", }, nil}, }, { name: "Parse WSPR Decode", args: argsFrom(`adbccbda000000020000000a0000000657534a542d580102b5f840ffffffeebfe000000000000000000000006b6c7300000000000000054b3654475700000004434d39350000001700`), want: parseResult{WSPRDecodeMessage{ Id: "WSJT-X", New: true, Time: 45480000, Snr: -18, DeltaTime: -0.5, Frequency: 7040115, Drift: 0, Callsign: "K6TGW", Grid: "CM95", Power: 23, OffAir: false, }, nil}, }, { name: "Parse Logged Adif", args: argsFrom(`adbccbda000000020000000c0000000657534a542d580000015c0a3c616469665f7665723a353e332e312e300a3c70726f6772616d69643a363e57534a542d580a3c454f483e0a3c63616c6c3a343e54335354203c677269647371756172653a343e4a4b3733203c6d6f64653a333e465438203c7273745f73656e743a323e2d38203c7273745f726376643a323e2d39203c71736f5f646174653a383e3230323031303330203c74696d655f6f6e3a363e313230383136203c71736f5f646174655f6f66663a383e3230323031303330203c74696d655f6f66663a363e313230393136203c62616e643a333e34306d203c667265713a383e372e303735393530203c73746174696f6e5f63616c6c7369676e3a353e4b30535745203c6d795f677269647371756172653a363e444d37394c56203c74785f7077723a313e35203c636f6d6d656e743a373e436f6d6d656e74203c6e616d653a343e4a657373203c6f70657261746f723a353e5433535452203c454f523e`), want: parseResult{LoggedAdifMessage{ Id: "WSJT-X", Adif: ` 3.1.0 WSJT-X T3ST JK73 FT8 -8 -9 20201030 120816 20201030 120916 40m 7.075950 K0SWE DM79LV 5 Comment Jess T3STR `, }, nil}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := parseMessage(tt.args.buffer, tt.args.length) if !errors.Is(err, tt.want.err) { t.Error(err) } if !reflect.DeepEqual(got, tt.want.message) { t.Errorf("\nwant %v\ngot %v", tt.want.message, got) } }) } } func parseTime(str string) time.Time { ret, _ := time.Parse("2006-01-02 15:04:05 -0700 MST", str) return ret } func argsFrom(str string) parseArgs { bytes, _ := hex.DecodeString(str) return parseArgs{ buffer: bytes, length: len(bytes), } } golang-github-k0swe-wsjtx-go-4.0.1/server.go000066400000000000000000000115651425101314100207070ustar00rootroot00000000000000package wsjtx import ( "errors" "fmt" "net" "runtime" ) const magic = 0xadbccbda const schema = 2 const qDataStreamNull = 0xffffffff const bufLen = 1024 const localhostAddr = "127.0.0.1" const multicastAddr = "224.0.0.1" const wsjtxPort = 2237 type Server struct { conn *net.UDPConn remoteAddr *net.UDPAddr listening bool } var NotConnectedError = fmt.Errorf("haven't heard from wsjtx yet, don't know where to send commands") // MakeServer creates a multicast UDP connection to communicate with WSJT-X on the default address // and port. func MakeServer() (Server, error) { var defaultWsjtxAddr net.IP switch runtime.GOOS { case "windows": defaultWsjtxAddr = net.ParseIP(localhostAddr) default: defaultWsjtxAddr = net.ParseIP(multicastAddr) } return MakeServerGiven(defaultWsjtxAddr, wsjtxPort) } // MakeServerGiven creates a UDP connection to communicate with WSJT-X on the given address and // port. func MakeServerGiven(ipAddr net.IP, port uint) (Server, error) { addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%v:%d", ipAddr, port)) if err != nil { return Server{}, err } var conn *net.UDPConn if ipAddr.IsMulticast() { conn, err = net.ListenMulticastUDP(addr.Network(), nil, addr) } else { conn, err = net.ListenUDP(addr.Network(), addr) } if err != nil { return Server{}, err } if conn == nil { return Server{}, errors.New("wsjtx udp connection not opened") } return Server{conn, nil, false}, nil } func (s *Server) LocalAddr() net.Addr { return s.conn.LocalAddr() } // ListenToWsjtx listens for messages from WSJT-X. When heard, the messages are parsed and then // placed in the given message channel. If parsing errors occur, those are reported on the errors // channel. If a fatal error happens, e.g. the network connection gets closed, the channels are // closed and the goroutine ends. func (s *Server) ListenToWsjtx(c chan interface{}, e chan error) { s.listening = true defer close(c) defer close(e) for { b := make([]byte, bufLen) if s.conn == nil { e <- errors.New("wsjtx connection is nil") s.listening = false return } length, rAddr, err := s.conn.ReadFromUDP(b) if err != nil { e <- fmt.Errorf("problem reading from wsjtx: %w", err) s.listening = false return } s.remoteAddr = rAddr message, err := parseMessage(b, length) if err != nil { e <- err } if message != nil { c <- message } } } // Listening returns whether the ListenToWsjtx goroutine is currently running. func (s *Server) Listening() bool { return s.listening } // Heartbeat sends a heartbeat message to WSJT-X. func (s *Server) Heartbeat(msg HeartbeatMessage) error { msgBytes, _ := encodeHeartbeat(msg) return s.tryWrite(msgBytes) } // Clear sends a message to WSJT-X to clear the band activity window, the RX frequency window, or // both. func (s *Server) Clear(msg ClearMessage) error { msgBytes, _ := encodeClear(msg) return s.tryWrite(msgBytes) } // Reply initiates a reply to an earlier decode. The decode message must have started with CQ or // QRZ. func (s *Server) Reply(msg ReplyMessage) error { msgBytes, _ := encodeReply(msg) return s.tryWrite(msgBytes) } // Close sends a message to WSJT-X to close the program. func (s *Server) Close(msg CloseMessage) error { msgBytes, _ := encodeClose(msg) return s.tryWrite(msgBytes) } // Replay sends a message to WSJT-X to replay QSOs in the Band Activity window. func (s *Server) Replay(msg ReplayMessage) error { msgBytes, _ := encodeReplay(msg) return s.tryWrite(msgBytes) } // HaltTx sends a message to WSJT-X to halt transmission. func (s *Server) HaltTx(msg HaltTxMessage) error { msgBytes, _ := encodeHaltTx(msg) return s.tryWrite(msgBytes) } // FreeText sends a message to WSJT-X to set the free text of the TX message. func (s *Server) FreeText(msg FreeTextMessage) error { msgBytes, _ := encodeFreeText(msg) return s.tryWrite(msgBytes) } // Location sends a message to WSJT-X to set this station's Maidenhead grid. func (s *Server) Location(msg LocationMessage) error { msgBytes, _ := encodeLocation(msg) return s.tryWrite(msgBytes) } // HighlightCallsign sends a message to WSJT-X to set callsign highlighting. func (s *Server) HighlightCallsign(msg HighlightCallsignMessage) error { msgBytes, _ := encodeHighlightCallsign(msg) return s.tryWrite(msgBytes) } // SwitchConfiguration sends a message to WSJT-X to switch to a different pre-defined configuration. func (s *Server) SwitchConfiguration(msg SwitchConfigurationMessage) error { msgBytes, _ := encodeSwitchConfiguration(msg) return s.tryWrite(msgBytes) } // Configure sends a message to WSJT-X to change various configuration options. func (s *Server) Configure(msg ConfigureMessage) error { msgBytes, _ := encodeConfigure(msg) return s.tryWrite(msgBytes) } func (s *Server) tryWrite(msgBytes []byte) error { if s.remoteAddr == nil { return NotConnectedError } _, err := s.conn.WriteTo(msgBytes, s.remoteAddr) return err }