暂无描述

modem.go 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package main
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "io"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/gordonklaus/portaudio"
  12. "github.com/naleek/gortty"
  13. )
  14. type Modem struct {
  15. ttyReader io.Reader
  16. ttyWriter io.Writer
  17. modulator *gortty.Modulator
  18. demodulator *gortty.Demodulator
  19. encoder *gortty.Encoder
  20. decoder *gortty.Decoder
  21. stream *portaudio.Stream
  22. registers map[int]configRegister
  23. autoAnswer bool
  24. escapeRune rune
  25. modulatorOn bool
  26. turnaroundDelay int
  27. usos bool
  28. localEcho bool
  29. }
  30. func (m *Modem) Close() {
  31. m.stream.Close()
  32. portaudio.Terminate()
  33. }
  34. func (m *Modem) SetLocalEcho(e bool) {
  35. m.localEcho = e
  36. }
  37. func (m *Modem) GetRegister(index int) (string, bool) {
  38. if r, ok := m.registers[index]; ok {
  39. return r.f(registerGet, ""), true
  40. }
  41. return "", false
  42. }
  43. func (m *Modem) SetRegister(index int, value string) bool {
  44. if r, ok := m.registers[index]; ok {
  45. r.f(registerSet, value)
  46. return true
  47. } else {
  48. return false
  49. }
  50. }
  51. func NewModem(ctx context.Context, rttySettings *gortty.ModemSettings, charset *gortty.CodeSet) (*Modem, error) {
  52. m := &Modem{}
  53. m.registers = map[int]configRegister{
  54. 0: {
  55. help: "auto-answer enable",
  56. f: func(action int, value string) string {
  57. switch action {
  58. case registerGet:
  59. if m.autoAnswer {
  60. return "1"
  61. } else {
  62. return "0"
  63. }
  64. case registerSet:
  65. m.autoAnswer = (value == "1")
  66. return "OK"
  67. }
  68. return ""
  69. },
  70. },
  71. 2: {
  72. help: "escape character",
  73. f: func(action int, value string) string {
  74. switch action {
  75. case registerGet:
  76. return string(m.escapeRune)
  77. case registerSet:
  78. runes := []rune(value)
  79. m.escapeRune = runes[0]
  80. return "OK"
  81. }
  82. return ""
  83. },
  84. },
  85. 101: {
  86. help: "modulator enable",
  87. f: func(action int, value string) string {
  88. switch action {
  89. case registerGet:
  90. if m.modulatorOn {
  91. return "1"
  92. } else {
  93. return "0"
  94. }
  95. case registerSet:
  96. m.modulatorOn = (value == "1")
  97. if m.modulator != nil {
  98. if m.modulatorOn {
  99. m.modulator.SetAmplitude(16384)
  100. } else {
  101. m.modulator.SetAmplitude(0)
  102. }
  103. }
  104. return "OK"
  105. }
  106. return ""
  107. },
  108. },
  109. 102: {
  110. help: "turnaround delay",
  111. f: func(action int, value string) string {
  112. switch action {
  113. case registerGet:
  114. return fmt.Sprintln(m.turnaroundDelay)
  115. case registerSet:
  116. if d, err := strconv.Atoi(value); err == nil {
  117. m.turnaroundDelay = d
  118. return "OK"
  119. } else {
  120. return "ERROR"
  121. }
  122. }
  123. return ""
  124. },
  125. },
  126. 103: {
  127. help: "unshift on space",
  128. f: func(action int, value string) string {
  129. switch action {
  130. case registerGet:
  131. if m.usos {
  132. return "1"
  133. } else {
  134. return "0"
  135. }
  136. case registerSet:
  137. m.usos = (value == "1")
  138. m.decoder.UnshiftOnSpace(m.usos)
  139. return "OK"
  140. }
  141. return ""
  142. },
  143. },
  144. }
  145. m.autoAnswer = false
  146. m.escapeRune = '?'
  147. m.modulatorOn = true
  148. m.turnaroundDelay = 0
  149. m.usos = false
  150. in := make([]int16, 64)
  151. out := make([]int16, 64)
  152. // Set up audio with system default input and output
  153. portaudio.Initialize()
  154. var err error
  155. m.stream, err = portaudio.OpenDefaultStream(1, 1, float64(rttySettings.SampleRate), len(in), in, out)
  156. if err != nil {
  157. panic(err)
  158. }
  159. modulatorToAudio := make(chan int16)
  160. audioToDemodulator := make(chan int16)
  161. // Set up modulator pipeline
  162. encoderToModulator := make(chan byte)
  163. m.encoder = gortty.NewEncoder(ctx, nil, encoderToModulator, charset)
  164. m.modulator = gortty.NewModulator(ctx, rttySettings, encoderToModulator, modulatorToAudio)
  165. m.modulator.SetIdleDelay(1000)
  166. // Set up demodulator pipeline
  167. demodulatorToDecoder := make(chan byte)
  168. m.demodulator = gortty.NewDemodulator(ctx, rttySettings, audioToDemodulator, demodulatorToDecoder)
  169. m.decoder = gortty.NewDecoder(ctx, demodulatorToDecoder, nil, charset)
  170. // start audio
  171. m.stream.Start()
  172. // Audio output
  173. go func() {
  174. l := 0
  175. for v := range modulatorToAudio {
  176. out[l] = v
  177. l++
  178. if l == 64 {
  179. l = 0
  180. m.stream.Write()
  181. }
  182. }
  183. }()
  184. // Audio input
  185. go func() {
  186. for {
  187. m.stream.Read()
  188. for i := range in {
  189. audioToDemodulator <- in[i]
  190. }
  191. }
  192. }()
  193. return m, nil
  194. }
  195. func (m *Modem) modulatorCallback(event int, data interface{}) {
  196. switch event {
  197. case gortty.EventActive:
  198. fmt.Println("EventActive")
  199. m.demodulator.Inhibit(true)
  200. case gortty.EventIdle:
  201. fmt.Println("EventIdle")
  202. m.demodulator.Inhibit(false)
  203. }
  204. }
  205. type configFunction func(action int, value string) string
  206. type configRegister struct {
  207. help string
  208. f configFunction
  209. }
  210. const (
  211. registerGet = iota
  212. registerSet
  213. )
  214. func (m *Modem) run() {
  215. ttyBufferedReader := bufio.NewReader(m.decoder)
  216. var netConn *NetConn
  217. if m.modulator != nil {
  218. m.modulator.SetCallback(m.modulatorCallback)
  219. }
  220. for {
  221. s, _ := ttyBufferedReader.ReadString('\n')
  222. //fmt.Println(s)
  223. s = strings.ToUpper(s)
  224. regex, _ := regexp.Compile(`^AT([SHOED?])([0-9])?(\?)?(?:[=|\:]([\S]*))?(?: (.*))?`)
  225. params := regex.FindStringSubmatch(s)
  226. if params == nil {
  227. continue
  228. }
  229. command := params[1]
  230. var register string
  231. if len(params) > 2 {
  232. register = params[2]
  233. }
  234. var registerQuery string
  235. if len(params) > 3 {
  236. registerQuery = params[3]
  237. }
  238. var value string
  239. if len(params) > 4 {
  240. value = params[4]
  241. }
  242. var parameter string
  243. if len(params) > 5 {
  244. parameter = params[5]
  245. }
  246. //fmt.Fprintf(m.encoder, "command: '%s' register: '%s' query: '%s' value: '%s' parameter: '%s'\n", command, register, registerQuery, value, parameter)
  247. switch command {
  248. case "?":
  249. fmt.Fprintf(m.encoder, "Setting Registers\n")
  250. for s, conf := range m.registers {
  251. fmt.Fprintf(m.encoder, "%s: %s (current value: %s)\n", s, conf.help, conf.f(registerGet, ""))
  252. }
  253. case "O": // online
  254. if !netConn.Connected() {
  255. fmt.Fprintln(m.encoder, "ERROR No active session")
  256. break
  257. }
  258. fmt.Fprintln(m.encoder, "OK")
  259. dataMode(netConn, ttyBufferedReader, m.encoder, m.escapeRune)
  260. case "D": // dial
  261. if netConn.Connected() {
  262. fmt.Fprintln(m.encoder, "ERROR Session in progress")
  263. break
  264. }
  265. addr := strings.TrimSpace(parameter)
  266. var err error
  267. netConn, err = NewNetConn(addr)
  268. if err != nil {
  269. fmt.Fprintln(m.encoder, "ERROR", err)
  270. break
  271. } else {
  272. fmt.Fprintln(m.encoder, "CONNECTED")
  273. dataMode(netConn, ttyBufferedReader, m.encoder, m.escapeRune)
  274. }
  275. case "H": // hangup
  276. if !netConn.Connected() {
  277. fmt.Fprintln(m.encoder, "ERROR No active session")
  278. break
  279. }
  280. netConn.Hangup()
  281. fmt.Fprintln(m.encoder, "OK")
  282. case "E": // local echo
  283. m.localEcho = (register == "1")
  284. fmt.Fprintln(m.encoder, "local echo", m.localEcho)
  285. case "S": // register
  286. r, _ := strconv.Atoi(register)
  287. if registerQuery == "?" { // get
  288. if v, ok := m.GetRegister(r); ok {
  289. fmt.Fprintln(m.encoder, v)
  290. } else {
  291. fmt.Fprintln(m.encoder, "ERROR")
  292. }
  293. } else if value != "" { //set
  294. if m.SetRegister(r, value) {
  295. fmt.Fprintln(m.encoder, "OK")
  296. } else {
  297. fmt.Fprintln(m.encoder, "ERROR")
  298. }
  299. } else {
  300. fmt.Fprintln(m.encoder, "ERROR")
  301. }
  302. }
  303. }
  304. }
  305. func dataMode(netConn *NetConn, ttyBufferedReader *bufio.Reader, ttyWriter io.Writer, escapeRune rune) {
  306. ttyCancelReader := make(chan struct{})
  307. ttyReadChan := make(chan rune)
  308. ttyReadPending := make(chan struct{})
  309. var t *time.Timer
  310. escapeRunes := 0
  311. go func() {
  312. for {
  313. r, l, err := ttyBufferedReader.ReadRune()
  314. if err != nil && err != io.EOF {
  315. return
  316. }
  317. if l > 0 {
  318. select {
  319. case <-ttyCancelReader:
  320. ttyBufferedReader.UnreadRune() // oops this wasn't ours. let's put it back.
  321. close(ttyReadPending)
  322. return
  323. default:
  324. ttyReadChan <- r
  325. }
  326. }
  327. }
  328. }()
  329. netReadChan := netConn.OutputChannel()
  330. netConn.Resume()
  331. pipeLoop:
  332. for {
  333. var r rune
  334. if t == nil {
  335. select {
  336. case r = <-ttyReadChan:
  337. case q := <-netReadChan:
  338. ttyWriter.Write([]byte(string(q)))
  339. continue pipeLoop
  340. }
  341. } else {
  342. select {
  343. case r = <-ttyReadChan:
  344. case q := <-netReadChan:
  345. ttyWriter.Write([]byte(string(q)))
  346. continue pipeLoop
  347. case <-t.C:
  348. fmt.Fprintln(ttyWriter, "\nOK")
  349. close(ttyCancelReader)
  350. netConn.Pause()
  351. break pipeLoop
  352. }
  353. }
  354. if r == escapeRune && escapeRunes < 3 {
  355. escapeRunes++
  356. } else {
  357. if t != nil {
  358. t.Stop()
  359. }
  360. escapeRunes = 0
  361. }
  362. if escapeRunes == 3 {
  363. t = time.NewTimer(1 * time.Second)
  364. }
  365. err := netConn.Write(r)
  366. if err != nil {
  367. fmt.Fprintln(ttyWriter, "NO CARRIER")
  368. close(ttyCancelReader)
  369. break pipeLoop
  370. }
  371. }
  372. <-ttyReadPending
  373. }