<repo_name>itsJustAbe/BerrySensor<file_sep>/BluetoothClient.py
import bluetooth
import sensor
import datetime
import sys
import time


def bluetooth_msg():
    # Kruno's Bluetooth
    bd_addr = "B8:27:EB:94:1F:03"

    port = 1
    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    sock.connect((bd_addr, port))

    while True:
        try:
             # assembling data received from the sensor
             log_line = sensor.temp()
             # sending data
             sock.send(log_line)
             # sleep time
             time.sleep(5)
       
        except:
            print("connection error")
            
bluetooth_msg()
<file_sep>/testClient.py
import paho.mqtt.client as mqtt
import time

# This is the Publisher

# Add client Ip address on the same network
CLIENT_IP = "" 
client = mqtt.Client()

client.connect(CLIENT_IP, 1883, 60)
i = 0
word = '<PASSWORD>!'

while i < 10:
    word = word + " " + str(i)
    print "sending data"
    client.publish("topic/test", word)
    i = i + 1
    time.sleep(2)
    
print "disconnecting..."    
client.disconnect()
<file_sep>/server.py
#!/usr/bin/python

import time
import os
import select
from datetime import datetime
import bluetooth
import paho.mqtt.client as mqtt
from logentries import LogentriesHandler
import logging
import pyowm

# sensor utils
import sensor

# Add log entries API key here
LOG_ENTRIES_API_KEY = '' 

# Getting external weather data to compare with internal temperature and humididty 
def get_weather():

    user_id = os.uname()[1]
    protocol="EXTERNAL"

    owm = pyowm.OWM('1d11da8b7fd7895acd7d78bf97be9839')
    observation = owm.weather_at_place('Dublin,IE')
    weather = observation.get_weather()
    humidity = weather.get_humidity()
    temperature = weather.get_temperature('celsius')["temp"]
    
    format_string = '{}  Protocol={} SensorID={}, temperature={}, humidity={} \n'.format(str(datetime.now()), protocol,
                                                                                             user_id,temperature, humidity)
    log.info(format_string)

# Format string to be sent to log entries
def get_reading(protocol):
    humidity, temperature, user_id = sensor.temp()

    format_string = '{}  Protocol={} SensorID={}, temperature={}, humidity={} \n'.format(str(datetime.now()), protocol,
                                                                                             user_id,temperature, humidity)
    return format_string 

# Connect to the mqtt publisher
def mqtt_connect():
    # create mqtt connection
    client = mqtt.Client()
    client.connect("127.0.0.1",1883,60)
    client.loop_start()
    return client

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("topic/test")


def on_message(client, userdata, msg):
    # get mqtt message and send to logentries
    mqtt_msg = msg.payload.decode()
    if mqtt_msg:
        print "Mqtt message:", mqtt_msg
        log.info(mqtt_msg)

def send_mqtt_data(client):
    client.on_connect = on_connect
    client.on_message = on_message

# Creating bluetooth server
def bluetooth_connect():
    # set bluetooth
    server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
    port = 1
    server_sock.bind(("",port))
    server_sock.listen(1)
    client_sock,address = server_sock.accept()
    print "Accepted connection from ",address
    return client_sock

# Recieve data coming from bluetooth and send to log entries
def send_bluetooth_data(client_sock):
    try:
        print "checking for bluetooth message!"
        client_sock.setblocking(0)
        
        ready = select.select([client_sock], [], [], 1)
        if ready[0]:
            remote_data = client_sock.recv(4096)
        #remote_data = client_sock.recv(1024)
        if remote_data:
            print "Remote data:", remote_data
            log.info(remote_data)
    except:
        pass

# send data from local gateway server
def send_local_log():
    log_line = get_reading("LOCAL")
    log.info(log_line)


# Set lognetires
log = logging.getLogger('logentries')
log.setLevel(logging.INFO)
log.addHandler(LogentriesHandler(LOG_ENTRIES_API_KEY))

client_sock = bluetooth_connect()
client = mqtt_connect()
send_mqtt_data(client)

while True:
    get_weather()
    send_local_log()
    print "Receive data from MQTT\n"
    send_mqtt_data(client)
    print "Receive data from Bluetooth\n"
    send_bluetooth_data(client_sock)
    time.sleep(2)


client_sock.close()
server_sock.close()

<file_sep>/servermqtt.py
#!/usr/bin/env python

import paho.mqtt.client as mqtt

# This is the Subscriber

def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("topic/test")

def on_message(client, userdata, msg):
  #if msg.payload.decode() == "Hello world!":
  print(msg.payload.decode())


client = mqtt.Client()
#client.connect("172.16.31.10",1883,60)
client.connect("127.0.0.1",1883,60)

client.on_connect = on_connect
#client.on_message = on_message

while True:
    client.on_message = on_message
    print "sleep for 1 sec"
    time.sleep(1)

#client.loop_forever()

#client.disconnect()<file_sep>/README.md
# IoT_sensor_monitor
Raspberry Pi sensor monitor
<file_sep>/SensorScript.py
# assembler for all the script data
def assembler(dt, my_list, user_id):

    # converting received values to float
    humidity = float(my_list[0])
    humidity_decimal = float(my_list[1])/10

    temperature = float(my_list[2])
    temperature_decimal = float(my_list[3])/10

    # adding the decimal bits
    humidity = humidity + humidity_decimal
    temperature = temperature + temperature_decimal

    # formatting data to be sent to the bluetooth device
    format_string = '{} SensorID={}, temperature={}, humidity={} \n'.format(dt.now, user_id, temperature, humidity)


    return format_string
<file_sep>/Testlog.py
from logentries import LogentriesHandler
import logging
import time
LOGENTRIES_TOKEN = "<PASSWORD>"


log = logging.getLogger('logentries')
log.setLevel(logging.INFO)
test = LogentriesHandler(LOGENTRIES_TOKEN)

log.addHandler(test)

log.warn("Warning message")
log.info("Info message")
sleep(10)
<file_sep>/main_client.py
import time
from datetime import datetime
import bluetooth
import sensor
import paho.mqtt.client as mqtt

CLIENT_IP = "" 

def mqtt_connect():
    # Connect to MQTT
    client = mqtt.Client()
    client.connect(CLIENT_IP, 1883, 60)
    return client
    

def bluetooth_connect(sock):
    # Kruno's Bluetooth
    bd_addr = "B8:27:EB:94:1F:03"
    port = 1
    # connecting to the said device
    sock.connect((bd_addr, port))
    

def get_reading(protocol):
    humidity, temperature, user_id = sensor.temp()
    # formatting data to be sent to the bluetooth device
    format_string = '{}  Protocol={} SensorID={}, temperature={}, humidity={} \n'.format(str(datetime.now()), protocol,
                                                                                             user_id,temperature, humidity)
    return format_string 

def bluetooth_msg(sock):
    try:
        # assembling data received from the sensor
        log_line = get_reading("RFCOMM")
        # sending data
        sock.send(log_line)
        # sleep time
        time.sleep(5)

    except:
        print("connection error")


def mqtt_msg(client):
    # The message
    log_line = get_reading("MQTT")
    print ("sending data")
    # Publishing message to be recived by the other pi
    client.publish("topic/test", log_line)
    # SLeep timer
    time.sleep(5)

# Connect to the bluetooth device
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
bluetooth_connect(sock)

while True:
    
    # The time constraint 1 hour =  10 seconds, runs for 2 minutes
    t_end = time.time() + 60 * 2
    client = mqtt_connect()

    #start sending with MQTT
    while time.time() < t_end:
            mqtt_msg(client) 
    # Console Output         
    print ("Handing off to RFCOMM")
    
    # Time constraint running for 2 minutes
    t_end = time.time() + 60 * 2
    
    # Start Bluetooth
    while time.time() < t_end:
        bluetooth_msg(sock)
    # Console output
    print ("Handing off to MQTT") 
   








<file_sep>/sensor.py
# client script

import RPi.GPIO as GPIO
import time
import os

gpio = 4
user_id = os.uname()[1]


def bin2dec(string_num):
    return str(int(string_num, 2))


def temp():
    data = []
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(gpio, GPIO.OUT)
    GPIO.output(gpio, GPIO.HIGH)
    time.sleep(0.025)
    GPIO.output(gpio, GPIO.LOW)
    time.sleep(0.02)
    GPIO.setup(gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    for i in range(0, 3500):
        data.append(GPIO.input(4))

    bit_count = 0
    tmp = 0
    count = 0
    HumidityBit = ""
    TemperatureBit = ""
    HumidityDecimalBit = ""
    TemperatureDecimalBit = ""
    crc = ""

    try:
        while data[count] == 1:
            tmp = 1
            count = count + 1

        for i in range(0, 32):
            bit_count = 0

            while data[count] == 0:
                tmp = 1
                count = count + 1

            while data[count] == 1:
                bit_count = bit_count + 1
                count = count + 1

            if bit_count > 16:
                # Humidity bit
                if 0 <= i < 8:
                    HumidityBit = HumidityBit + "1"
                # Humidity decimal
                if 8 <= i < 16:
                    HumidityDecimalBit = HumidityDecimalBit + "1"
                # Temperature
                if 16 <= i < 24:
                    TemperatureBit = TemperatureBit + "1"
                # Temperature decimal
                if 24 <= i < 32:
                    TemperatureDecimalBit = TemperatureDecimalBit + "1"

            else:
                # Humidity bit
                if 0 <= i < 8:
                    HumidityBit = HumidityBit + "0"
                # Humidity decimal
                if 8 <= i < 16:
                    HumidityDecimalBit = HumidityDecimalBit + "0"
                # Temperature
                if 16 <= i < 24:
                    TemperatureBit = TemperatureBit + "0"
                # Temperature decimal
                if 24 <= i < 32:
                    TemperatureDecimalBit = TemperatureDecimalBit + "0"

    except:
        #print("ERR_RANGE")
        return temp()

    try:
        for i in range(0, 8):
            bit_count = 0

            while data[count] == 0:
                tmp = 1
                count = count + 1

            while data[count] == 1:
                bit_count = bit_count + 1
                count = count + 1

            if bit_count > 16:
                crc = crc + "1"
            else:
                crc = crc + "0"
    except:
        #print("ERR_RANGE")
        return temp()

    # Display
    humidity = float(bin2dec(HumidityBit))
    humidity_decimal = float(bin2dec(HumidityDecimalBit)) / 10
    temperature_decimal = float(bin2dec(TemperatureDecimalBit)) / 10
    temperature = float(bin2dec(TemperatureBit))

    # adding the decimal bits
    humidity = humidity + humidity_decimal
    temperature = temperature + temperature_decimal

    # Returning the values parsed from the sensor
    return humidity, temperature, user_id
