Guest User

Untitled

a guest
Aug 23rd, 2017
73
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import sys
  2. sys.path.append("./lib")
  3.  
  4. import binascii
  5. import struct
  6. import pycom
  7. import socket
  8. import time
  9. import _thread
  10. import ujson as json
  11. from machine import Pin
  12. from machine import Timer
  13. from network import LoRa
  14. from network import WLAN
  15.  
  16. from pysense import Pysense
  17. from LIS2HH12 import LIS2HH12
  18. from LTR329ALS01 import LTR329ALS01
  19. from SI7006A20 import SI7006A20
  20. from MPL3115A2 import MPL3115A2
  21. from mqtt import MQTTClient
  22.  
  23. # Colors
  24. off = 0x000000
  25. red = 0xff0000
  26. green = 0x00ff00
  27. blue = 0x0000ff
  28. yellow = 0xFFFF00
  29. white = 0xFFFFFF
  30.  
  31. mode = 'wifi'
  32. threadstate = 0
  33.  
  34. pycom.heartbeat(False)
  35. print('Hello!')
  36. pycom.rgbled(red)
  37. time.sleep(3)
  38.  
  39. # Set network keys
  40. app_eui = binascii.unhexlify('AABBCCDDEEFF1122')
  41. app_key = binascii.unhexlify('AABBCCDDEEFF11223344556677889900')
  42.  
  43. # Init pysense board
  44. py = Pysense()
  45. mp = MPL3115A2(py, mode=MPL3115A2.PRESSURE)
  46. si = SI7006A20(py)
  47. lt = LTR329ALS01(py)
  48. li = LIS2HH12(py)
  49. # Initialize LoRaWAN radio and Wifi
  50. lora = LoRa(mode=LoRa.LORAWAN)
  51.  
  52.  
  53. class SensorValues():
  54.     def __init__(self):
  55.         self.binary = None
  56.         self.JSON = None
  57.  
  58.     def get_JSON(self):
  59.         return self.JSON
  60.  
  61.     def get_binary(self):
  62.         return self.binary
  63.  
  64.     def set_JSON(self, json_string):
  65.         self.JSON = json_string
  66.  
  67.     def set_binary(self, bin):
  68.         self.binary = bin
  69.  
  70.  
  71. sensorValues = SensorValues()
  72.  
  73.  
  74. class StoppableThread:
  75.     def __init__(self):
  76.         self._running = True
  77.         self._stopped = False
  78.         self._started = False
  79.  
  80.     def stop(self):
  81.         print('Requested thread to stop')
  82.         self._running = False
  83.         self._started = False
  84.  
  85.     def is_started(self):
  86.         return self._started
  87.  
  88.     def is_stopped(self):
  89.         return self._stopped
  90.  
  91.     def run(self, *args, **kwargs):
  92.         self.setup(args, kwargs)
  93.         self._started = True
  94.         while self._running == True:
  95.             self.loop(args, kwargs)
  96.             time.sleep_ms(1)
  97.         self.teardown()
  98.         self._stopped = True
  99.         _thread.exit()
  100.  
  101.     def loop(self, *args, **kwargs):
  102.         raise NotImplementedError
  103.  
  104.     def teardown(self):
  105.         return 1
  106.  
  107.     def setup(self, *args, **kwargs):
  108.         return 1
  109.  
  110.  
  111. class WifiNetworkThread(StoppableThread):
  112.     def setup(self, *args, **kwargs):
  113.         self.wlan = WLAN(mode=WLAN.STA, antenna=WLAN.INT_ANT)
  114.         print("LoPy WiFi MAC: " + str(binascii.hexlify(self.wlan.mac())))
  115.         print('Connecting WiFi lopy with pw lopyconnect')
  116.         self.wlan.connect('lopy', auth=(WLAN.WPA2, 'lopyconnect'))
  117.  
  118.     def teardown(self):
  119.         if self.wlan.isconnected():
  120.             self.wlan.disconnect()
  121.         self.wlan.deinit()
  122.  
  123.     def loop(self, *args, **kwargs):
  124.         if self.wlan.isconnected() == False:
  125.             print('.', end='')
  126.             pycom.rgbled(yellow)
  127.             time.sleep(1)
  128.         else:
  129.             pycom.rgbled(off)
  130.             try:
  131.                 client = MQTTClient("lopy", "m21.cloudmqtt.com",user="lopyconnect", password="lopyconnect", port=26883, ssl=True)
  132.                 client.connect()
  133.                 client.publish(topic="lopy", msg="ON")
  134.                 client.disconnect()
  135.             except:
  136.                 print("Unexpected error:", sys.exc_info()[0])
  137.            
  138.             time.sleep(5)
  139.  
  140.  
  141. class LoRaNetworkThread(StoppableThread):
  142.     def setup(self, *args, **kwargs):
  143.         self.socket = None
  144.         print('Joining LoRa Network')
  145.         lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
  146.         print('LoPy LoRa MAC (TTN Devive EUI): ', end='')
  147.         print(binascii.hexlify(lora.mac()))
  148.  
  149.     def teardown(self):
  150.         if self.socket != None:
  151.             self.socket.close()
  152.             self.socket = None
  153.  
  154.     def loop(self, *args, **kwargs):
  155.         if not lora.has_joined():
  156.             print('.', end='')
  157.             pycom.rgbled(yellow)
  158.             time.sleep(1)
  159.         elif self.socket == None:  # initially configure our socket
  160.             self.socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
  161.             self.socket.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
  162.             self.socket.setblocking(True)
  163.             lora.power_mode(LoRa.TX_ONLY)  # auto sleep if not transmitting
  164.         else:
  165.             c = self.socket.send(sensorValues.get_binary())
  166.             print('Sent ', str(c), ' bytes via LoRa')
  167.             time.sleep(15)
  168.  
  169.  
  170. current_network_thread = WifiNetworkThread()
  171. _thread.start_new_thread(current_network_thread.run, ())
  172.  
  173.  
  174. def switch_mode(arg):
  175.     global mode
  176.     global current_network_thread
  177.     print(' ')
  178.     print(' ')
  179.     if mode == 'wifi':
  180.         print('Switching to LoRa')
  181.     else:
  182.         print('Switch to WiFi')
  183.  
  184.     new_led_color = white if mode == 'wifi' else blue
  185.     led_color = blue if mode == 'wifi' else white
  186.  
  187.     pycom.rgbled(led_color)
  188.     current_network_thread.stop()
  189.     while current_network_thread.is_stopped() == False:
  190.         pycom.rgbled(off)
  191.         time.sleep(0.2)
  192.         pycom.rgbled(led_color)
  193.         time.sleep(0.2)
  194.  
  195.     current_network_thread = LoRaNetworkThread() if mode == 'wifi' else WifiNetworkThread()
  196.     mode = 'lora' if mode == 'wifi' else 'wifi'
  197.  
  198.     pycom.rgbled(new_led_color)
  199.     _thread.start_new_thread(current_network_thread.run, ())
  200.     while current_network_thread.is_started() == False:
  201.         pycom.rgbled(off)
  202.         time.sleep(0.2)
  203.         pycom.rgbled(new_led_color)
  204.         time.sleep(0.2)
  205.  
  206.     pycom.rgbled(off)
  207.  
  208.  
  209. def update_measures(*args, **kwargs):
  210.     # print('Updating sensor values...')
  211.     pys_voltage = py.read_battery_voltage()
  212.     pys_acceleration_all = li.acceleration()
  213.     pys_light_all = lt.light()
  214.     struct_params = [
  215.         int((mp.temperature() - 5) * 100),  # int, 2Byte - h/short
  216.         float(mp.pressure()),               # float, 4Byte - f/float
  217.         int(si.humidity() * 100),           # int, 2Byte - h/short
  218.         int(pys_light_all[0]),              # light[0]: 2Byte -H/unsigned short
  219.         int(pys_light_all[1]),              # light[1]: 2Byte -H/unsigned shor
  220.         int(pys_acceleration_all[0] * 100),  # float, 4Byte - i/int
  221.         int(pys_acceleration_all[1] * 100),  # float, 4Byte - i/int
  222.         int(pys_acceleration_all[2] * 100),  # float, 4Byte - i/int
  223.         # float (conv to int), 2Byte - h/short
  224.         int(li.roll() * 100),
  225.         # float (conv to int), 2Byte - h/short
  226.         int(li.pitch() * 100),
  227.         # float (conv to int), 2Byte - h/short
  228.         int(li.yaw() * 100),
  229.         # float (conv to int), 2Byte - h/short
  230.         int(py.read_battery_voltage() * 100)
  231.     ]
  232.     bVal = struct.pack('>hfhHHiiihhhh', *struct_params)
  233.     hVal = binascii.hexlify(bVal)
  234.     sensorValues.set_binary(bVal)
  235.     json_string = json.dumps({
  236.         'temperature': struct_params[0] / 100,
  237.         'pressure': struct_params[1],
  238.         'humidity': struct_params[2] / 100,
  239.         'light1': struct_params[3],
  240.         'light2': struct_params[4],
  241.         'acceleration': [struct_params[5] / 100, struct_params[6] / 100, struct_params[7] / 100],
  242.         'roll': struct_params[8] / 100,
  243.         'pitch': struct_params[9] / 100,
  244.         'yaw': struct_params[10] / 100,
  245.         'battery': struct_params[11] / 100
  246.     })
  247.     sensorValues.set_JSON(json_string)
  248.  
  249. # init mode switch button
  250. switch_mode_button = Pin('P14', mode=Pin.IN)
  251. switch_mode_button.callback(Pin.IRQ_FALLING, handler=switch_mode)
  252.  
  253.  
  254. Timer.Alarm(update_measures, 5, periodic=True)
RAW Paste Data