# An Air Quality Sensor - Main script
#
# The devices determines the PM2.5 and PM10 concentrations in the air
# and transmits the collected data via LoRaWAN.
#
# Version 0.5
#
# Authors: J. Barthelemy and N. Verstaevel
# License: MIT
#
# Copyright 2020 Johan Barthelemy and Nicolas Verstaevel
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import config
from SDS011 import SDS011

from EasyLoraConnect import EasyLoraConnect
import gc
import time
import struct
import machine

gc.enable()

try:
    lora = EasyLoraConnect()
    #Init the SEN0177 Sensor
    sds011 = SDS011(PTX='P11',PRX='P10')

    n_transmit = 0

    while True:
            #Read sensor data
            (pm2_5,pm10) = sds011._read_PM()
            if not sds011._isError():
                print('===============================')
                print('pm2.5 =' + str(pm2_5) + ' ug/m3')
                print('pm10  =' + str(pm10) + ' ug/m3')
            else:
                print('Oups...something went wrong in the reading')
                machine.reset()

            ttn_data = bytes()
            ttn_data = ttn_data + struct.pack('!l', pm2_5)
            ttn_data = ttn_data + struct.pack('!l', pm10)
            checksum = pm2_5+pm10
            ttn_data = ttn_data + struct.pack('!l', checksum)
            print("Sending : "+str(ttn_data))
            lora.send(ttn_data)

            gc.collect()
            pycom.rgbled(0x4B0082)


            n_transmit = n_transmit + 1
            if n_transmit == config.REJOIN_AFTER:
                machine.reset()

            time.sleep(config.INT_SAMPLING)
except:
    machine.reset()
