Guest User

Untitled

a guest
Mar 28th, 2022
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 2.10 KB | None | 0 0
  1. import posix
  2. import locks
  3. import nesper/general, nesper/uarts, nesper/tasks
  4. import ./example
  5. import ./modem
  6. import ./esp_pthread
  7. import ./shared
  8.  
  9. var t {.rtcNoInit.}: int
  10.  
  11. const TAG* = "main"
  12.  
  13. type Guarded[T] = object
  14.   lock: Lock
  15.   data {.guard: lock.}: T
  16.  
  17. proc newGuarded[T](data: T): ref Guarded[T] =
  18.   new(result)
  19.   initLock(result.lock)
  20.   withLock(result.lock):
  21.     result.data = data
  22.  
  23. proc sendAT(params: pointer): pointer {.rtosThread.} =
  24.   var res = cast[ptr ref Guarded[string]](params)
  25.  
  26.   var mdm = newModem(
  27.     port = UART_NUM_1,
  28.     tx_pin = GPIO_NUM_17,
  29.     rx_pin = GPIO_NUM_16)
  30.  
  31.   if not mdm.init():
  32.     loge(TAG, "Error initialising modem")
  33.     return
  34.  
  35.   while true:
  36.     withLock(res.lock):
  37.       echo "Modem thread: " & res.data
  38.  
  39.     let (success, _) = mdm.sendAT("")
  40.     if success:
  41.       echo "Yep, ends with OK"
  42.     else:
  43.       echo "No it doesn't"
  44.     vTaskDelay(pdMS_TO_TICKS(300))
  45.  
  46. proc myMain(params: pointer): pointer {.rtosThread.} =
  47.   var res = cast[ptr ref Guarded[string]](params) # Sort of gross, but
  48.   echo "We're in the main thread"
  49.  
  50.   while true:
  51.     withLock(res.lock):
  52.       echo "Main thread: " & res.data
  53.     vTaskDelay(pdMS_TO_TICKS(150))
  54.  
  55. app_main():
  56.   if t != 42:
  57.     echo "Nope, its not 42"
  58.     t = 42
  59.   else:
  60.     echo "Yes, it is!"
  61.   vTaskDelay(pdMS_TO_TICKS(500))
  62.   esp_restart()
  63.  
  64.   ## All of this is dead code
  65.   var guardedString = newGuarded("Hello, world")
  66.  
  67.   check: esp_pthread_init()
  68.  
  69.   var cfg = esp_pthread_get_default_config()
  70.   cfg.stack_size = csize_t(1024 * 8)
  71.  
  72.   check: esp_pthread_set_cfg(addr cfg)
  73.  
  74.   echo "Hello, Nim!"
  75.   example.run()
  76.  
  77.   var mainThread: Pthread
  78.   var mainRes = pthread_create(addr mainThread, nil, myMain, addr guardedString)
  79.  
  80.   if mainRes != 0:
  81.     echo "Error creating main thread!"
  82.  
  83.   var modemThread: Pthread
  84.   var modemRes = pthread_create(addr modemThread, nil, sendAT, addr guardedString)
  85.  
  86.   if modemRes != 0:
  87.     echo "Error creating modem thread!"
  88.  
  89.   discard pthread_join(mainThread, nil)
  90.   discard pthread_join(modemThread, nil)
  91.  
  92.   assert false, "Should never get here"
  93.  
Advertisement
Add Comment
Please, Sign In to add comment