
/*
 Author: Obrtac Tomas  
 Mail: obrtac.tomas@gmail.com
 2017
 */

#include <xc.h>           
#include "UART_commands.h"
#include "SPI_commands.h"
#include "Sensors_lib.h"
#include "I2Ccommands.h"
#include "Sleep_commands.h"
#include "RN_commands.h"
#include "SHT75.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
 
/* fuses */
#pragma config WDTEN = ON       // Watchdog Timer (Enabled)
#pragma config PLLDIV = 1       // PLL Prescaler Selection bits (No prescale (4 MHz oscillator input drives PLL directly))
#pragma config STVREN = ON      // Stack Overflow/Underflow Reset (Disabled) 
#pragma config XINST = OFF      // Extended Instruction Set (Enabled)

// CONFIG1H
#pragma config CPUDIV = OSC1    // CPU System Clock Postscaler (No CPU system clock divide)
#pragma config CP0 = OFF        // Code Protect (Program memory is not code-protected)

// CONFIG2L
#pragma config OSC = HS         // Oscillator (HS, USB-HS)
#pragma config T1DIG = ON       // T1OSCEN Enforcement (Secondary Oscillator clock source may be selected)
#pragma config LPT1OSC = OFF    // Low-Power Timer1 Oscillator (High-power operation)
#pragma config FCMEN = ON       // Fail-Safe Clock Monitor (Enabled)  
#pragma config IESO = ON        // Internal External Oscillator Switch Over Mode (Enabled)

// CONFIG2H
#pragma config WDTPS = 32768   // Watchdog Postscaler (1:32768)
// CONFIG3L
// Deep Sleep Watchdog Postscaler does not work
#pragma config DSWDTOSC = INTOSCREF // DSWDT Clock Select (DSWDT uses INTRC)
#pragma config RTCOSC = INTOSCREF   // RTCC Clock Select (RTCC uses INTRC)
#pragma config DSBOREN = ON         // Deep Sleep BOR (Enabled) //////
#pragma config DSWDTEN = ON         // Deep Sleep Watchdog Timer (Enabled) 
#pragma config DSWDTPS = 32768      // Deep Sleep Watchdog Postscaler (1:8,192 (8.5 seconds))

// CONFIG3H
#pragma config IOL1WAY = ON     // IOLOCK One-Way Set Enable bit (The IOLOCK bit (PPSCON<0>) can be set once)
#pragma config MSSP7B_EN = MSK7 // MSSP address masking (7 Bit address masking mode)

// CONFIG4L
#pragma config WPFP = PAGE_63   // Write/Erase Protect Page Start/End Location (Write Protect Program Flash Page 63)
#pragma config WPEND = PAGE_WPFP// Write/Erase Protect Region Select (valid when WPDIS = 0) (Page WPFP<5:0> through Configuration Words erase/write protected)
#pragma config WPCFG = OFF      // Write/Erase Protect Configuration Region (Configuration Words page not erase/write-protected)

// CONFIG4H
#pragma config WPDIS = ON     // Write Protect Disable bit (WPFP<5:0>/WPEND region ignored)

#define N_OF_REPEATS 2 // Calculate the length of one period of the transmission. Formula for this is approximately N_OF_REPEATS * 140s + 140

int main(void) {
    Basic_Settings();   // Basing settings like disable ADC ports etc
    Remap_UART_2();     // Remapping ports for UART conversation with RN module
    SPI_Remap();        // Remppaing ports for SPI communication
    Setting_I2C();      // Setting the I2C
    char message[96];
    char repeat = 1000; // Set the value higher than N_OF_REPEATS at startup
    float Temperature,Humidity,Light_intensity;
    uint16_t Humidityx,Temperaturex;
    uint32_t Light_intensityx,*Pressurex;
    uint16_t *C;
    C = Return_Constans_MS5607(); // Reading constants for pressure measurement
    RN_InitializationCommands(); // Initialization commands for RN module
    while(1){
        if (repeat > N_OF_REPEATS){ // Check if the data should be sent
            RN_WakeUpEvent(); // Wake the RN module from sleep
            Delay_ms10(5); // Wait few ms for wake up 
            Temperature = ADT7301_Converted_Value(); // Take value from ADT sensor
            Humidity = SHT_Humidity_With_Compensation(Temperature); // Take value from SHT sensor with compensation     
            Light_intensity = OPT3001_Converted_Value(0b10001010); // Read value from light sensor
            Light_intensity = OPT3001_Converted_Value(0b10001000); // Read value from light sensor
            Light_intensity /=2; // Divide the resulting value by two to get the average
            Pressurex = Return_Values_MS5607(C); // Read values from barometric sensor
            Temperaturex = round ((Temperature-50)*100);
            Humidityx = round (Humidity*100);
            Light_intensityx = round(Light_intensity);
            sprintf(message,"mac tx uncnf 2 %.4x%.4x%.6x%.6x",Temperaturex, 
                    Humidityx,Light_intensityx,
                    Pressurex[1]    
                    ); // Prepare message for send
            RN_SendCommand(message); // Send message
            Delay_ms10(200); // Wait until the message is sent
            RN_SendCommand("sys sleep 2000000"); // Put the RN module in the sleep mode
            Delay_ms10(2);
            repeat = 0; // Clear the repeat counter
        }
        Sleep_Funct(); // Put MCU in to sleep mode  
        repeat ++; // Increment the repeat counter
    }
}