-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathradio.go
More file actions
953 lines (825 loc) · 24.1 KB
/
Copy pathradio.go
File metadata and controls
953 lines (825 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//go:build esp32c3 || esp32c3_qemu_target || esp32s3
package espradio
/*
#cgo CFLAGS: -Iblobs/include
#cgo CFLAGS: -Iblobs/include/local
#cgo CFLAGS: -Iblobs/headers
#cgo CFLAGS: -DCONFIG_SOC_WIFI_NAN_SUPPORT=0
#cgo CFLAGS: -DESPRADIO_PHY_PATCH_ROMFUNCS=0
#cgo CFLAGS: -fno-short-enums
#include "espradio.h"
*/
import "C"
import (
"bytes"
"runtime"
"runtime/interrupt"
"sync"
"sync/atomic"
"time"
"unsafe"
)
// ─── Types ───────────────────────────────────────────────────────────────────
type LogLevel uint8
const (
LogLevelNone = C.WIFI_LOG_NONE
LogLevelError = C.WIFI_LOG_ERROR
LogLevelWarning = C.WIFI_LOG_WARNING
LogLevelInfo = C.WIFI_LOG_INFO
LogLevelDebug = C.WIFI_LOG_DEBUG
LogLevelVerbose = C.WIFI_LOG_VERBOSE
)
func (l LogLevel) String() string {
switch l {
case LogLevelNone:
return "NONE"
case LogLevelError:
return "ERROR"
case LogLevelWarning:
return "WARN"
case LogLevelInfo:
return "INFO"
case LogLevelDebug:
return "DEBUG"
case LogLevelVerbose:
return "VERBOSE"
default:
return "?"
}
}
// Config configures the radio and its driver.
type Config struct {
Logging LogLevel
// ArenaPoolSize overrides the default per-target arena pool size (bytes).
// Zero means use the target default.
ArenaPoolSize int
}
// AccessPoint represents a Wi-Fi access point discovered during scanning.
type AccessPoint struct {
SSID string
RSSI int
}
// STAConfig configures station mode connection parameters.
type STAConfig struct {
SSID string
Password string
}
// ConnectResult represents the result of a connection attempt.
type ConnectResult struct {
Connected bool
SSID string
Channel uint8
Reason uint8
}
// APConfig configures soft-AP mode parameters.
type APConfig struct {
SSID string
Password string
Channel uint8
AuthOpen bool
}
// ─── Enable ──────────────────────────────────────────────────────────────────
const schedTickerMs = 5
var isrKick chan struct{}
func startSchedTicker() {
isrKick = make(chan struct{}, 1)
go func() {
ticker := time.NewTicker(schedTickerMs * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
case <-isrKick:
}
schedOnce()
runtime.Gosched()
}
}()
}
var wifiInitDone uint32
func schedOnce() {
// Snapshot INTENABLE before any blob code runs so that wifi_unmask can
// restore TinyGo-owned bits (e.g. GPIO at bit 10 on ESP32-S3) that the
// blob may clear via ROM calls (ets_isr_mask) bypassing the OS adapter.
C.espradio_snapshot_intenable()
// Mask WiFi CPU interrupt before the ISR softcall. On Xtensa (ESP32-S3)
// the WiFi interrupt is level-triggered at level 1. If the MAC asserts
// its interrupt while we're already iterating the ISR handlers below,
// the hardware ISR preempts us and re-entrantly calls the blob's ISR
// handler, corrupting its state and crashing. Masking first prevents
// this; espradio_wifi_unmask() at the end re-enables the interrupt.
C.espradio_ints_off(C.uint32_t(1 << wifiCPUInterrupt))
// Restore ROM pointers BEFORE any blob code runs. The blob reads
// pTxRx, pp_wdev_funcs etc. during ISR/queue/timer processing below.
C.espradio_restore_rom_ptrs()
// Poll WiFi ISR: work around missing hardware interrupt on ESP32-S3.
// Only poll after init is complete (blob ISR not registered until then).
if atomic.LoadUint32(&wifiInitDone) != 0 {
C.espradio_call_wifi_isr()
}
for C.espradio_isr_ring_tail() != C.espradio_isr_ring_head() {
idx := C.espradio_isr_ring_tail()
q := C.espradio_isr_ring_entry_queue(idx)
itemPtr := C.espradio_isr_ring_entry_item(idx)
C.espradio_queue_send(q, itemPtr, 0)
C.espradio_isr_ring_advance_tail()
}
for i := 0; i < 4; i++ {
C.espradio_event_loop_run_once()
}
for i := 0; i < 4; i++ {
if C.espradio_timer_poll_due(8) == 0 {
break
}
}
for i := 0; i < 4; i++ {
if C.espradio_esp_timer_poll_due(8) == 0 {
break
}
}
// Restore critical ROM pointer variables that WiFi DMA may have
// corrupted (pTxRx, our_tx_eb, our_wait_eb, lmacConfMib_ptr).
C.espradio_restore_rom_ptrs()
C.espradio_wifi_unmask()
}
func kickSched() {
select {
case isrKick <- struct{}{}:
default:
}
}
// arenaPool keeps the arena backing memory reachable from Go so the GC
// won't collect it. The WiFi blob stores pointers into this pool in ROM
// BSS (outside the GC's scan range), so individual malloc'd objects would
// be collected. One large pool kept alive by this global is safe.
var arenaPool []byte
// ArenaStats returns the current arena usage and capacity in bytes.
func ArenaStats() (used, capacity uint32) {
var u, c C.uint32_t
C.espradio_arena_stats(&u, &c)
return uint32(u), uint32(c)
}
// Enable and configure the radio for WiFi.
func Enable(config Config) error {
// Allocate arena pool from Go heap and hand it to C.
poolSize := arenaPoolSize
if config.ArenaPoolSize > 0 {
poolSize = config.ArenaPoolSize
}
arenaPool = make([]byte, poolSize)
C.espradio_arena_init((*C.uint8_t)(unsafe.Pointer(&arenaPool[0])), C.size_t(poolSize))
startSchedTicker()
time.Sleep(schedTickerMs * time.Millisecond)
initHardware()
C.espradio_ensure_osi_ptr()
wifiISR = interrupt.New(wifiCPUInterrupt, wifiISRHandler)
wifiISR.Enable()
C.espradio_wifi_int_raise_priority()
C.espradio_prewire_wifi_interrupts()
C.espradio_event_register_default_cb()
C.espradio_set_blob_log_level(C.uint32_t(config.Logging))
mask := interrupt.Disable()
C.espradio_hal_init_clocks_go()
interrupt.Restore(mask)
errCode := C.espradio_wifi_init()
if errCode != 0 {
return makeError(errCode)
}
C.espradio_wifi_init_completed()
C.espradio_wifi_int_to_level()
atomic.StoreUint32(&wifiInitDone, 1)
schedOnce()
C.espradio_netif_init_netstack_cb()
return nil
}
// Start starts the Wi-Fi driver and connects to the AP if in station mode.
// Blocks until the driver is ready. Start is separate from Enable to allow
// configuration (e.g. country code) before starting, and to allow scanning without
// starting the driver. Start calls schedOnce in a loop to let the blob process
// its internal startup sequence (posting events, etc.) before Start returns.
func Start() error {
var mode C.wifi_mode_t
if code := C.esp_wifi_get_mode(&mode); code != C.ESP_OK {
return makeError(code)
}
if mode != C.WIFI_MODE_STA {
if code := C.esp_wifi_set_mode(C.WIFI_MODE_STA); code != C.ESP_OK {
return makeError(code)
}
}
C.espradio_set_country_eu_manual()
if code := C.espradio_esp_wifi_start(); code != C.ESP_OK {
return makeError(code)
}
// Disable modem-sleep power management. The blob's default
// WIFI_PS_MIN_MODEM fires PM timer callbacks (pm_dream, pm_go_to_wake,
// etc.) that call ppCheckTxConnTrafficIdle. Under cooperative scheduling
// the TX frame queues may be in an inconsistent state when those PM
// callbacks run, causing NULL-pointer crashes in ppCheckIsConnTraffic.
C.esp_wifi_set_ps(C.WIFI_PS_NONE)
// The blob's esp_wifi_start posts a START command to ppTask's queue
// and returns. espradio_esp_wifi_start already called post_start_cb
// which relocates heap tables. Now pump the scheduler so ppTask
// processes START (calls pp_attach, ppInitTxq, etc.) and the critical
// ROM pointer variables (pTxRx, our_tx_eb, …) get initialised.
for i := 0; i < 40; i++ {
schedOnce()
runtime.Gosched()
}
// Snapshot the ROM pointers now that they are valid.
C.espradio_save_rom_ptrs()
return nil
}
// DebugISRCount returns the number of WiFi ISR invocations (for debugging).
func DebugISRCount() uint32 {
return uint32(C.espradio_get_wifi_isr_count())
}
// Scan performs a single Wi-Fi scan pass and returns the list of discovered access points.
func Scan() ([]AccessPoint, error) {
C.espradio_ensure_osi_ptr()
C.esp_wifi_set_ps(C.WIFI_PS_NONE)
C.espradio_set_country_eu_manual()
time.Sleep(250 * time.Millisecond)
var scanCfg C.wifi_scan_config_t
scanCfg.ssid = nil
scanCfg.bssid = nil
scanCfg.channel = 0
scanCfg.show_hidden = false
scanCfg.scan_type = C.WIFI_SCAN_TYPE_ACTIVE
scanCfg.scan_time.active.min = 0
scanCfg.scan_time.active.max = 300
scanCfg.scan_time.passive = 500
if code := C.esp_wifi_scan_start(&scanCfg, true); code != C.ESP_OK {
return nil, makeError(code)
}
var num C.uint16_t
if code := C.esp_wifi_scan_get_ap_num(&num); code != C.ESP_OK {
return nil, makeError(code)
}
if num == 0 {
return nil, nil
}
recs := make([]C.wifi_ap_record_t, int(num))
if code := C.esp_wifi_scan_get_ap_records(
&num,
(*C.wifi_ap_record_t)(unsafe.Pointer(&recs[0])),
); code != C.ESP_OK {
return nil, makeError(code)
}
aps := make([]AccessPoint, int(num))
for i := 0; i < int(num); i++ {
raw := C.GoBytes(unsafe.Pointer(&recs[i].ssid[0]), C.int(len(recs[i].ssid)))
if idx := bytes.IndexByte(raw, 0); idx >= 0 {
raw = raw[:idx]
}
aps[i] = AccessPoint{
SSID: string(raw),
RSSI: int(recs[i].rssi),
}
}
return aps, nil
}
// ─── Connect ─────────────────────────────────────────────────────────────────
var (
connectMu sync.Mutex
connectResult chan ConnectResult
)
// Connect configures STA credentials and initiates association.
// Blocks until CONNECTED, DISCONNECTED or timeout.
func Connect(cfg STAConfig) error {
connectMu.Lock()
connectResult = make(chan ConnectResult, 1)
connectMu.Unlock()
code := C.espradio_sta_set_config(
C.CString(cfg.SSID), C.int(len(cfg.SSID)),
C.CString(cfg.Password), C.int(len(cfg.Password)),
)
if code != C.ESP_OK {
return makeError(code)
}
if code := C.esp_wifi_connect_internal(); code != C.ESP_OK {
return makeError(code)
}
select {
case res := <-connectResult:
if res.Connected {
// The blob fires WIFI_EVENT_STA_CONNECTED before its internal
// TX path (ppCheckIsConnTraffic) is fully initialized. Pump the
// scheduler to let the blob finish setup before callers try to TX.
for i := 0; i < 20; i++ {
schedOnce()
time.Sleep(10 * time.Millisecond)
}
return nil
}
return makeError(C.esp_err_t(res.Reason))
case <-time.After(15 * time.Second):
return makeError(C.ESP_ERR_TIMEOUT)
}
}
//export espradio_on_wifi_event
func espradio_on_wifi_event(eventID int32, data unsafe.Pointer) {
switch eventID {
case C.WIFI_EVENT_STA_CONNECTED:
C.espradio_netif_set_connected(1)
ev := (*C.wifi_event_sta_connected_t)(data)
ssidLen := int(ev.ssid_len)
if ssidLen > 32 {
ssidLen = 32
}
ssid := C.GoBytes(unsafe.Pointer(&ev.ssid[0]), C.int(ssidLen))
connectMu.Lock()
ch := connectResult
connectMu.Unlock()
if ch != nil {
select {
case ch <- ConnectResult{Connected: true, SSID: string(ssid), Channel: uint8(ev.channel)}:
default:
}
}
case C.WIFI_EVENT_STA_DISCONNECTED:
C.espradio_netif_set_connected(0)
ev := (*C.wifi_event_sta_disconnected_t)(data)
connectMu.Lock()
ch := connectResult
connectMu.Unlock()
if ch != nil {
select {
case ch <- ConnectResult{Connected: false, Reason: uint8(ev.reason)}:
default:
}
}
case C.WIFI_EVENT_STA_START:
}
}
// ─── Soft-AP ─────────────────────────────────────────────────────────────────
// StartAP starts the radio in soft-AP mode with the given configuration.
func StartAP(cfg APConfig) error {
if code := C.esp_wifi_set_mode(C.WIFI_MODE_AP); code != C.ESP_OK {
return makeError(code)
}
ssid := cfg.SSID
if len(ssid) == 0 {
ssid = "espradio-ap"
}
code := C.espradio_ap_set_config(
C.CString(ssid), C.int(len(ssid)),
C.CString(cfg.Password), C.int(len(cfg.Password)),
C.uint8_t(cfg.Channel), C.int(boolToInt(cfg.AuthOpen)),
)
if code != C.ESP_OK {
return makeError(code)
}
if code := C.espradio_esp_wifi_start(); code != C.ESP_OK {
return makeError(code)
}
// Same post-start sequence as Start(): disable modem-sleep, pump the
// scheduler so ppTask processes the START command (pp_attach, ppInitTxq,
// etc.) and the critical ROM pointer variables get initialised, then
// snapshot them so espradio_restore_rom_ptrs can protect every TX.
C.esp_wifi_set_ps(C.WIFI_PS_NONE)
for i := 0; i < 40; i++ {
schedOnce()
runtime.Gosched()
}
C.espradio_save_rom_ptrs()
return nil
}
// ─── RF diagnostics ─────────────────────────────────────────────────────────
func SniffCountOnChannel(channel uint8, duration time.Duration) (uint32, error) {
if duration <= 0 {
duration = 1500 * time.Millisecond
}
if code := C.espradio_sniff_begin(C.uint8_t(channel)); code != C.ESP_OK {
return 0, makeError(code)
}
time.Sleep(duration)
packets := uint32(C.espradio_sniff_count())
if code := C.espradio_sniff_end(); code != C.ESP_OK {
return packets, makeError(code)
}
return packets, nil
}
// ─── Tasks / timers / ISR ────────────────────────────────────────────────────
func millisecondsToTicks(ms uint32) uint32 {
return ms * (ticksPerSecond / 1000)
}
func ticksToMilliseconds(ticks uint32) uint32 {
return ticks / (ticksPerSecond / 1000)
}
//export espradio_panic
func espradio_panic(msg *C.char) {
panic("espradio: " + C.GoString(msg))
}
//export espradio_log_timestamp
func espradio_log_timestamp() uint32 {
return uint32(time.Now().UnixMilli())
}
//export espradio_run_task
func espradio_run_task(task_func, param unsafe.Pointer)
const taskStackSize = 8192
//export espradio_task_create_pinned_to_core
func espradio_task_create_pinned_to_core(task_func unsafe.Pointer, name *C.char, stack_depth uint32, param unsafe.Pointer, prio uint32, task_handle *unsafe.Pointer, core_id uint32) int32 {
ch := make(chan struct{}, 1)
go func() {
*task_handle = tinygo_task_current()
close(ch)
espradio_run_task(task_func, param)
}()
<-ch
return 1
}
//export espradio_task_delete
func espradio_task_delete(task_handle unsafe.Pointer) {
}
//export tinygo_task_current
func tinygo_task_current() unsafe.Pointer
//export espradio_task_get_current_task
func espradio_task_get_current_task() unsafe.Pointer {
return tinygo_task_current()
}
func safeGosched() {
if wifiIntsOff > 0 {
return
}
runtime.Gosched()
}
//export espradio_task_yield_go
func espradio_task_yield_go() {
// Don't fire timers inline here — the blob calls task_yield from
// deep call stacks and the extra depth risks overflowing the
// goroutine stack. Timer polling is handled by schedOnce() in
// the ticker goroutine on its own stack.
kickSched()
runtime.Gosched()
}
//export espradio_time_us_now
func espradio_time_us_now() uint64 {
return uint64(time.Now().UnixMicro())
}
var (
timerGenMu sync.Mutex
timerGen map[uintptr]uint32
)
func timerArmGeneration(timer unsafe.Pointer) uint32 {
key := uintptr(timer)
timerGenMu.Lock()
defer timerGenMu.Unlock()
if timerGen == nil {
timerGen = make(map[uintptr]uint32)
}
g := timerGen[key] + 1
timerGen[key] = g
return g
}
func timerGenerationAlive(timer unsafe.Pointer, gen uint32) bool {
key := uintptr(timer)
timerGenMu.Lock()
defer timerGenMu.Unlock()
if timerGen == nil {
return false
}
return timerGen[key] == gen
}
//export espradio_timer_cancel_go
func espradio_timer_cancel_go(timer unsafe.Pointer) {
key := uintptr(timer)
timerGenMu.Lock()
if timerGen == nil {
timerGen = make(map[uintptr]uint32)
}
timerGen[key] = timerGen[key] + 1
timerGenMu.Unlock()
}
//export espradio_timer_arm_go
func espradio_timer_arm_go(timer unsafe.Pointer, tmout_ticks uint32, repeat int32) {
ms := ticksToMilliseconds(tmout_ticks)
if ms == 0 {
ms = 1
}
gen := timerArmGeneration(timer)
go func(gen uint32) {
d := time.Duration(ms) * time.Millisecond
if repeat != 0 {
for {
time.Sleep(d)
if !timerGenerationAlive(timer, gen) {
return
}
C.espradio_timer_fire(timer)
}
}
time.Sleep(d)
if !timerGenerationAlive(timer, gen) {
return
}
C.espradio_timer_fire(timer)
}(gen)
}
//export espradio_timer_arm_go_us
func espradio_timer_arm_go_us(timer unsafe.Pointer, us uint32, repeat int32) {
if us == 0 {
us = 1
}
gen := timerArmGeneration(timer)
go func(gen uint32) {
d := time.Duration(us) * time.Microsecond
if repeat != 0 {
for {
time.Sleep(d)
if !timerGenerationAlive(timer, gen) {
return
}
C.espradio_timer_fire(timer)
}
}
time.Sleep(d)
if !timerGenerationAlive(timer, gen) {
return
}
C.espradio_timer_fire(timer)
}(gen)
}
//export espradio_task_delay
func espradio_task_delay(ticks uint32) {
const ticksPerMillisecond = ticksPerSecond / 1000
ms := (ticks + ticksPerMillisecond - 1) / ticksPerMillisecond
time.Sleep(time.Duration(ms) * time.Millisecond)
}
//export espradio_task_ms_to_tick
func espradio_task_ms_to_tick(ms uint32) int32 {
return int32(millisecondsToTicks(ms))
}
var wifiIntsOff uint32
//export espradio_wifi_int_disable
func espradio_wifi_int_disable(wifi_int_mux unsafe.Pointer) uint32 {
s := uint32(interrupt.Disable())
wifiIntsOff++
return s
}
//export espradio_wifi_int_restore
func espradio_wifi_int_restore(wifi_int_mux unsafe.Pointer, tmp uint32) {
if wifiIntsOff > 0 {
wifiIntsOff--
}
interrupt.Restore(interrupt.State(tmp))
}
var wifiISR interrupt.Interrupt
// ─── OSI sync primitives ───────────────────────────────────────────────────────
const debugOSI = false
var fakeSpinLock uint8
//export espradio_spin_lock_create
func espradio_spin_lock_create() unsafe.Pointer {
return unsafe.Pointer(&fakeSpinLock)
}
//export espradio_spin_lock_delete
func espradio_spin_lock_delete(lock unsafe.Pointer) {
}
type recursiveMutex struct {
state sync.Mutex
owner unsafe.Pointer
count uint32
}
var mutexes [8]recursiveMutex
var mutexInUse [8]uint32
//export espradio_recursive_mutex_create
func espradio_recursive_mutex_create() unsafe.Pointer {
for i := range mutexes {
if atomic.CompareAndSwapUint32(&mutexInUse[i], 0, 1) {
return unsafe.Pointer(&mutexes[i])
}
}
panic("espradio: too many mutexes")
}
//export espradio_mutex_delete
func espradio_mutex_delete(cmut unsafe.Pointer) {
mut := (*recursiveMutex)(cmut)
mut.state.Lock()
mut.owner = nil
mut.count = 0
mut.state.Unlock()
for i := range mutexes {
if mut == &mutexes[i] {
atomic.StoreUint32(&mutexInUse[i], 0)
return
}
}
}
//export espradio_mutex_lock
func espradio_mutex_lock(cmut unsafe.Pointer) int32 {
mut := (*recursiveMutex)(cmut)
me := tinygo_task_current()
for {
mut.state.Lock()
if mut.count == 0 || mut.owner == me {
mut.owner = me
mut.count++
mut.state.Unlock()
return 1
}
mut.state.Unlock()
safeGosched()
}
}
//export espradio_mutex_unlock
func espradio_mutex_unlock(cmut unsafe.Pointer) int32 {
mut := (*recursiveMutex)(cmut)
me := tinygo_task_current()
mut.state.Lock()
if mut.count > 0 && mut.owner == me {
mut.count--
if mut.count == 0 {
mut.owner = nil
}
mut.state.Unlock()
return 1
}
mut.state.Unlock()
return 0
}
// ─── Event groups ─────────────────────────────────────────────────────────────
type eventGroup struct {
mu sync.Mutex
bits uint32
}
var eventGroups [8]eventGroup
var eventGroupInUse [8]uint32
//export espradio_event_group_create
func espradio_event_group_create() unsafe.Pointer {
for i := range eventGroups {
if atomic.CompareAndSwapUint32(&eventGroupInUse[i], 0, 1) {
eventGroups[i].bits = 0
return unsafe.Pointer(&eventGroups[i])
}
}
panic("espradio: too many event groups")
}
//export espradio_event_group_delete
func espradio_event_group_delete(ptr unsafe.Pointer) {
eg := (*eventGroup)(ptr)
eg.mu.Lock()
eg.bits = 0
eg.mu.Unlock()
for i := range eventGroups {
if eg == &eventGroups[i] {
atomic.StoreUint32(&eventGroupInUse[i], 0)
return
}
}
}
//export espradio_event_group_set_bits
func espradio_event_group_set_bits(ptr unsafe.Pointer, bits uint32) uint32 {
eg := (*eventGroup)(ptr)
eg.mu.Lock()
eg.bits |= bits
cur := eg.bits
eg.mu.Unlock()
return cur
}
//export espradio_event_group_clear_bits
func espradio_event_group_clear_bits(ptr unsafe.Pointer, bits uint32) uint32 {
eg := (*eventGroup)(ptr)
eg.mu.Lock()
eg.bits &^= bits
cur := eg.bits
eg.mu.Unlock()
return cur
}
//export espradio_event_group_wait_bits
func espradio_event_group_wait_bits(ptr unsafe.Pointer, bitsToWaitFor uint32, clearOnExit int32, waitForAllBits int32, blockTimeTick uint32) uint32 {
eg := (*eventGroup)(ptr)
want := bitsToWaitFor
matches := func(bits uint32) bool {
if waitForAllBits != 0 {
return bits&want == want
}
return bits&want != 0
}
forever := blockTimeTick == C.OSI_FUNCS_TIME_BLOCKING
start := time.Now()
var timeout time.Duration
if !forever {
timeout = time.Duration(blockTimeTick) * time.Millisecond
}
var snapshot uint32
for {
eg.mu.Lock()
snapshot = eg.bits
ok := matches(snapshot)
if ok {
if clearOnExit != 0 {
eg.bits &^= want
}
eg.mu.Unlock()
return snapshot
}
eg.mu.Unlock()
if blockTimeTick == 0 || (!forever && time.Since(start) >= timeout) {
return snapshot
}
safeGosched()
}
}
// ─── Semaphores ────────────────────────────────────────────────────────────────
type semaphore struct {
count uint32
}
var (
semaphores [4]semaphore
semaphoreIndex uint32
wifiThreadSemMu sync.Mutex
wifiThreadSemByTH = map[unsafe.Pointer]*semaphore{}
wifiThreadSemNil semaphore
)
func wifiThreadSemOwner(semphr unsafe.Pointer) unsafe.Pointer {
wifiThreadSemMu.Lock()
defer wifiThreadSemMu.Unlock()
for th, sem := range wifiThreadSemByTH {
if unsafe.Pointer(sem) == semphr {
return th
}
}
return nil
}
func semTryTake(sem *semaphore) bool {
for {
cur := atomic.LoadUint32(&sem.count)
if cur == 0 {
return false
}
if atomic.CompareAndSwapUint32(&sem.count, cur, cur-1) {
return true
}
}
}
//export espradio_semphr_create
func espradio_semphr_create(max, init uint32) unsafe.Pointer {
i := atomic.AddUint32(&semaphoreIndex, 1) - 1
if i >= uint32(len(semaphores)) {
panic("espradio: too many semaphores")
}
semaphores[i] = semaphore{count: init}
return unsafe.Pointer(&semaphores[i])
}
//export espradio_semphr_take
func espradio_semphr_take(semphr unsafe.Pointer, block_time_tick uint32) int32 {
sem := (*semaphore)(semphr)
owner := wifiThreadSemOwner(semphr)
_ = owner
if block_time_tick == 0 {
if semTryTake(sem) {
return 1
}
return 0
}
forever := block_time_tick == C.OSI_FUNCS_TIME_BLOCKING
start := time.Now()
var timeout time.Duration
if !forever {
timeout = time.Duration(block_time_tick) * time.Millisecond
}
iters := 0
for {
if semTryTake(sem) {
return 1
}
if !forever && time.Since(start) >= timeout {
return 0
}
iters++
safeGosched()
}
}
//export espradio_semphr_give
func espradio_semphr_give(semphr unsafe.Pointer) int32 {
sem := (*semaphore)(semphr)
atomic.AddUint32(&sem.count, 1)
return 1
}
//export espradio_semphr_delete
func espradio_semphr_delete(semphr unsafe.Pointer) {
sem := (*semaphore)(semphr)
atomic.StoreUint32(&sem.count, 0)
}
//export espradio_wifi_thread_semphr_get
func espradio_wifi_thread_semphr_get() unsafe.Pointer {
task := tinygo_task_current()
wifiThreadSemMu.Lock()
defer wifiThreadSemMu.Unlock()
if task == nil {
return unsafe.Pointer(&wifiThreadSemNil)
}
sem := wifiThreadSemByTH[task]
if sem == nil {
sem = &semaphore{}
wifiThreadSemByTH[task] = sem
}
return unsafe.Pointer(sem)
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
func boolToInt(b bool) int {
if b {
return 1
}
return 0
}