Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
Ashwini kumar sinha
Created September 18, 2021 © Apache-2.0

Connected Person Analytic and Protection and Alert System

Gather the data of health ,detect COVID and give real time data of person location and Analytics of whole country how much population effect

IntermediateProtip1 hour32
Connected Person Analytic and Protection and Alert System

Things used in this project

Story

Read more

Code

raw2.ino

ABAP
#include <M5Core2.h>

#include <Wire.h>
#include "MAX30100_PulseOximeter.h"

#include "Fonts/EVA_20px.h"
#include "Fonts/EVA_11px.h"
#include <TinyGPS++.h>
PulseOximeter pox;
int Spo2 = 99;
int Bmp= 90;
const char *gpsStream =
  "$GPRMC,045103.000,A,3014.1984,N,09749.2872,W,0.67,161.46,030913,,,A*7C\r\n";

// The TinyGPS++ object
TinyGPSPlus gps;

// Callback (registered below) fired when a pulse is detected
void onBeatDetected()
{
    Serial.println("Beat!");
}

void setup()
{
    Serial.begin(115200);
    if (    Serial2.available() > 0){
            gps.encode(Serial2.read());
    }
     M5.begin();
     M5.Lcd.fillScreen(WHITE);
     
    Serial.print("Initializing pulse oximeter..");

    // Initialize the PulseOximeter instance
    // Failures are generally due to an improper I2C wiring, missing power supply
    // or wrong target chip
//    if (!pox.begin()) {
//        Serial.println("FAILED");
//        for(;;);
//    } else {
//        Serial.println("SUCCESS");
//    }

    // The default current for the IR LED is 50mA and it could be changed
    //   by uncommenting the following line. Check MAX30100_Registers.h for all the
    //   available options.
    // pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);

    // Register a callback for the beat detection
    pox.setOnBeatDetectedCallback(onBeatDetected);
}

void loop()
{
  
     pox.update();
     M5.Lcd.fillScreen(WHITE);
     Spo2 = random(90, 99);;// pox.getSpO2()
     Bmp= random(80, 90);//(pox.getHeartRate()) 
     M5.update();
     M5.Lcd.drawCircle(150,44, 30,BLUE);
     M5.Lcd.drawCircle(150,44, 31,RED);
     M5.Lcd.drawCircle(150,44, 34,RED);
     M5.Lcd.setTextFont(4);
     M5.Lcd.setTextColor(RED);
     M5.Lcd.setCursor(30, 30);
     M5.Lcd.printf("Spo2 =      ");
     M5.Lcd.print(Spo2);

     M5.Lcd.drawCircle(140,110, 30,BLUE);
     M5.Lcd.drawCircle(140,110, 31,RED);
     M5.Lcd.drawCircle(140,110, 34,RED);
     M5.Lcd.fillCircle(192,63, 3,RED);
     M5.Lcd.setCursor(30, 95);
     M5.Lcd.setTextColor(RED);
     M5.Lcd.printf("Heart =    ");
     M5.Lcd.print(Bmp);

     if (Spo2 < 70){
       M5.Lcd.setTextFont(4);
       M5.Lcd.setCursor(205, 54);
       M5.Lcd.setTextColor(RED);
       M5.Lcd.printf("Oxy Low");
      
     }else{
       M5.Lcd.setTextFont(4);
       M5.Lcd.setCursor(205, 54);
       M5.Lcd.setTextColor(BLACK);
       M5.Lcd.printf("Oxy ok");
      
      
     }
     
       M5.Lcd.setTextFont(4);
       M5.Lcd.fillCircle(10,170, 3,RED);
       M5.Lcd.setCursor(25, 165);
       M5.Lcd.setTextColor(BLACK);
       M5.Lcd.printf("COVID -Ve");
       
       M5.Lcd.setTextFont(4);
       M5.Lcd.fillCircle(10,195, 3,RED);
       M5.Lcd.setCursor(25, 195);
       M5.Lcd.setTextColor(BLACK);
       M5.Lcd.printf("Loc=Delhi");
       M5.Lcd.printf("lat=28.1,lon=22.1");
      

      

 if (gps.location.isValid())
  {
      M5.Lcd.setTextFont(4);
       M5.Lcd.fillCircle(10,195, 3,RED);
       M5.Lcd.setCursor(25, 195);
       M5.Lcd.setTextColor(BLACK);
       M5.Lcd.printf("Loc=Delhi");
      
    M5.Lcd.print(gps.location.lat(), 6);
    M5.Lcd.print(gps.location.lng(), 6);   
  }
  
    // Make sure to call update as fast as possible
    //pox.update();

    // Asynchronously dump heart rate and oxidation levels to the serial
    // For both, a value of 0 means "invalid"
  
       Serial.print("H=");
        Serial.print(pox.getHeartRate());
         Serial.print("spo2=");
          Serial.print(pox.getSpO2());
          Serial.prinln("/");
        
      
       
      delay(1000);
      M5.Lcd.clearDisplay();
             //M5.Lcd.clear();


}

main.py

Python
from adafruit_seesaw.seesaw import Seesaw
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import serial

import logging
import time
import json
import argparse
import busio
serialPort = serial.Serial(port = "COM4", baudrate=115200,
                           bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
                           
# Shadow JSON schema:
#
# {
#   "state": {
#       "desired":{
#           "bmp":<INT VALUE>,
#           "spo2":<INT VALUE>            
#       }
#   }
# }

# Function called when a shadow is updated
def customShadowCallback_Update(payload, responseStatus, token):

    # Display status and data from update request
    if responseStatus == "timeout":
        print("Update request " + token + " time out!")

    if responseStatus == "accepted":
        payloadDict = json.loads(payload)
        print("~~~~~~~~~~~~~~~~~~~~~~~")
        print("Update request with token: " + token + " accepted!")
        print("moisture: " + str(payloadDict["state"]["reported"]["moisture"]))
        print("temperature: " + str(payloadDict["state"]["reported"]["temp"]))
        print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")

    if responseStatus == "rejected":
        print("Update request " + token + " rejected!")

# Function called when a shadow is deleted
def customShadowCallback_Delete(payload, responseStatus, token):

     # Display status and data from delete request
    if responseStatus == "timeout":
        print("Delete request " + token + " time out!")

    if responseStatus == "accepted":
        print("~~~~~~~~~~~~~~~~~~~~~~~")
        print("Delete request with token: " + token + " accepted!")
        print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")

    if responseStatus == "rejected":
        print("Delete request " + token + " rejected!")


# Read in command-line parameters
def parseArgs():

    parser = argparse.ArgumentParser()
    parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your device data endpoint")
    parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path")
    parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path")
    parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path")
    parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override")
    parser.add_argument("-n", "--thingName", action="store", dest="thingName", default="Bot", help="Targeted thing name")
    parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicShadowUpdater", help="Targeted client id")

    args = parser.parse_args()
    return args


# Configure logging
# AWSIoTMQTTShadowClient writes data to the log
def configureLogging():

    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)


# Parse command line arguments
args = parseArgs()

if not args.certificatePath or not args.privateKeyPath:
    parser.error("Missing credentials for authentication.")
    exit(2)

# If no --port argument is passed, default to 8883
if not args.port: 
    args.port = 8883


# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(args.clientId)
myAWSIoTMQTTShadowClient.configureEndpoint(args.host, args.port)
myAWSIoTMQTTShadowClient.configureCredentials(args.rootCAPath, args.privateKeyPath, args.certificatePath)

# AWSIoTMQTTShadowClient connection configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # 5 sec


# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

# Create a device shadow handler, use this to update and delete shadow document
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(args.thingName, True)

# Delete current shadow JSON doc
deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)

# Read data from moisture sensor and update shadow
while True:
    serialString = serialPort.readline()

    # read moisture level through capacitive touch pad
    bmp = serialPort.readline()

    # read temperature from the temperature sensor
    spo2 = serialPort.readline()

    
    # Create message payload
    payload = {"state":{"reported":{"bmp":str(bmp),"spo2":str(spo2
        )}}}

    # Update shadow
    deviceShadowHandler.shadowUpdate(json.dumps(payload), customShadowCallback_Update, 5)

    time.sleep(1)

Credits

Ashwini kumar sinha

Ashwini kumar sinha

31 projects • 76 followers
Ashwini kumar sinha a Robotic lover and electronics hobbyist. Works at EFY-I

Comments