main-lora-868.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import os
  2. import machine
  3. uart = machine.UART(0, 115200)
  4. os.dupterm(uart)
  5. known_nets = {
  6. 'UpUpUp': {'pwd': 't4k4tuk4l4nd2', 'wlan_config': ('192.168.2.115', '255.255.255.0', '192.168.2.1', '192.168.2.1')},
  7. 'Vidit-Fabrik': {'pwd': '%m1n!5NK=$', 'wlan_config': ('192.168.0.115', '255.255.255.0', '192.168.0.1', '192.168.0.1')}, # (ip, subnet_mask, gateway, DNS_server)
  8. }
  9. if machine.reset_cause() != machine.SOFT_RESET:
  10. from network import WLAN
  11. wl = WLAN()
  12. wl.mode(WLAN.STA)
  13. original_ssid = wl.ssid()
  14. original_auth = wl.auth()
  15. print("Scanning for known wifi nets")
  16. available_nets = wl.scan()
  17. nets = frozenset([e.ssid for e in available_nets])
  18. known_nets_names = frozenset([key for key in known_nets])
  19. net_to_use = list(nets & known_nets_names)
  20. try:
  21. net_to_use = net_to_use[0]
  22. net_properties = known_nets[net_to_use]
  23. pwd = net_properties['pwd']
  24. sec = [e.sec for e in available_nets if e.ssid == net_to_use][0]
  25. if 'wlan_config' in net_properties:
  26. wl.ifconfig(config=net_properties['wlan_config'])
  27. wl.connect(net_to_use, (sec, pwd), timeout=10000)
  28. while not wl.isconnected():
  29. machine.idle() # save power while waiting
  30. print("Connected to "+net_to_use+" with IP address:" + wl.ifconfig()[0])
  31. except Exception as e:
  32. print("Failed to connect to any known network, going into AP mode")
  33. wl.init(mode=WLAN.AP, ssid=original_ssid, auth=original_auth, channel=6, antenna=WLAN.INT_ANT)
  34. from network import LoRa
  35. import socket
  36. import machine
  37. import time
  38. # initialize LoRa in LORA mode
  39. # more params can also be given, like frequency, tx power and spreading factor
  40. lora = LoRa(mode=LoRa.LORA, frequency=868000000)
  41. # create a raw LoRa socket
  42. s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
  43. while True:
  44. # send some data
  45. s.setblocking(True)
  46. s.send('Hello')
  47. # get any data received...
  48. s.setblocking(False)
  49. data = s.recv(64)
  50. print(data)
  51. # wait a random amount of time
  52. time.sleep(machine.rng() & 0x0F)