import paho.mqtt.client as mqtt
from pymongo import *
import datetime
import numpy as np
import serial

client = MongoClient()

db = client.patients
db1 = client.box

ser = serial.Serial('/dev/ttyACM0', 115200)

def on_connect(client, userdata, rc):
  print("Connected with result code " + str(rc))
  
  '''Send from the tablet'''
  # Clinical data from the AI Assistant
  client.subscribe("/tab/send/server/patient")
  client.subscribe("/tab/send/server/vitals")
  client.subscribe("/tab/send/server/GI")
  client.subscribe("/tab/send/server/RI")
  client.subscribe("/tab/send/server/AP")
  client.subscribe("/tab/send/server/CONFIRM")
  # Send commands to move the microscope
  client.subscribe("/tab/send/microscope/serial")
  client.subscribe("/tab/send/microscope/startdiagnostic")
  # Send commands to move the box
  client.subscribe("/tab/send/box/openclose")

  ''' Receive from the box'''
  # Box data
  client.subscribe("/box/send/server/temp")
  client.subscribe("/box/send/server/hum")
  client.subscribe("/box/send/server/slides") 

  '''Receive from microscope'''
  # Result of diagnostics
  client.subscribe("/microscope/send/server/diagnostic_result")
  
def on_message(client, userdata, msg):
  global ser
  '''Send from the tablet'''
  # Clinical data from the AI Assistant
  if msg.topic == "/tab/send/server/patient":
    line = (msg.payload).split(';')
    year, month, day, hour, minute, second = get_now()
    db.patients.insert_one({
            'general information': {
            'id': line[0],
            'status': line[1],
            'TB':{
              'n_baci': '0',
              'n_clus': '0',
              'infection': '0'
            },
            'name info':{
                'first name': line[2],
                'last name': line[3]
            },
            'gender': line[4],
            'age': line[5],
            'number': line[6],
            'birthdate info': {
              'day': line[7],
              'month': line[8],
              'year': line[9]
            },
            'address info': {
                'address': line[10],
                'cityvillage': line[11],
                'stateprovince': line[12],
                'country': line[13],
                'postalcode': line[14]
            }
          }
        })
  
  if msg.topic == "/tab/send/server/vitals":
    year, month, day, hour, minute, second = get_now()
    line = (msg.payload).split(';')
    db.patients.update({'general information.id': line[0]},
                {'$push': 
                    {
                        'vitals information': {
                            'date':{
                            'day': str(now.day),
                            'month': str(now.month),
                            'year': str(now.year),
                            'hour': str(now.hour),
                            'minute': str(now.minute)
                          },
                          'height': line[0],
                          'weight': line[1],
                          'bmi': line[2],
                          'temperature': line[3],
                          'pulse': line[4],
                          'respiratory rate': line[5],
                          'blood pressure': line[6],
                          'blood oxygen saturation': line[7] 
                        }
                    }
                }
            )
  
  if msg.topic == "/tab/send/server/GI":
    line = (msg.payload).split(';')
    year, month, day, hour, minute, second = get_now()
    db.patients.update({'general information.id': line[0]},
                {'$push': 
                        {
                            'general inspection': {
                                'date':{
                                    'day': str(now.day),
                                    'month': str(now.month),
                                    'year': str(now.year),
                                    'hour': str(now.hour),
                                    'minute': str(now.minute)
                                  },

                                  'conformation':{
                                    'constitution': line[1], 
                                    'volume': line[2],
                                    'general deformation': line[3],
                                    'partial deformation': line[4],
                                    'regional alterations': line[5]
                                    }, 

                                  'skin':{
                                   'coloration': line[6],
                                   'pigmentation': line[7],
                                   'aspect': {
                                      'normal_smooth': line[8],
                                      'ulcers_scars': line[9],
                                      'traumatic_trophic': line[10],
                                      'eruptions': line[11],
                                      },
                                      'others': line[12]
                                    }, 

                                  'positions': {
                                    'decubitus':line[13],
                                    'clinostatism_orthotatism': line[14],
                                      'pain': {
                                        'pain_yes_no': line[15],
                                        'location': line[16],
                                        'intensity': line[17]
                                      },
                                      'disease manifestation': {
                                      'disease': line[18],
                                      'specify disease manifestation': line[19] 
                                       }
                                    }, 

                                  'movements': {
                                    'normal_increased_decrease': line[20],
                                    'alterations': line[21],
                                  }
                            }
                        }
                    }
            )
  
  if msg.topic == "/tab/send/server/RI":
    line = (msg.payload).split('')
    year, month, day, hour, minute, second = get_now()
    db.patients.update(
            {'general information.id': line[0]},
            {'$push': 
                {   
                        'respiratory inspection':{
                            'date':{
                                'day': str(now.day), 
                                'month': str(now.month),
                                'year': str(now.year),
                                'hour': str(now.hour),
                                'minute': str(now.minute)
                            },
                            'anatomic':{
                                'assymetry': line[1],
                                'assymetry observations': line[2],
                                'spinal cord observations': line[3],
                                'breastbone observations': line[4],
                                'ribs observations': line[5],
                                'rib cage expansion observations': line[6],
                                'respiratory pattern': line[7],
                                'respiration characteristic': line[8]
                              },

                              'percussion':{
                                'normal_increased_decreased': line[9]
                              },

                              'palpation':{
                                'transmission voice': line[10],
                                'rib cages observations': line[11],
                                'assymetry': line[12],
                                'edema': line[13]
                              },

                              'auscultation':{
                                'transmission voice': line[14],
                                'respiration amplitude': line[15],
                                'cough': line[16],
                                'voice': line[17]
                              }
                        }
                    }
                })

  if msg.topic == "/tab/send/server/AP":
    line = (msg.payload).split('')
    year, month, day, hour, minute, second = get_now()
    db.patients.update(
                {'general information.id': line[0]}, 
                {'$push':
                    {
                        'appointment information':{
                            'date':{
                                'day': line[1],
                                'month': line[2],
                                'year': '2016',
                                'hour': line[3], 
                                'minute': line[4]
                            },
                            'location': line[5],
                            'service': line[6],
                            'status': line[7],
                            'duration': line[8],
                            'description': line[9]
                        }
                    }
                }
                )
    
  if msg.topic == "/tab/send/server/CONFIRM":
    ser.write('1')
    time.sleep(0.1)
    line = ser.readline()
    if line[0] == 'D':
      line = (msg.payload).split(',')
      c = db.patients.find({'general information.id': line[0]})
      send = c['general information.id'] + ',' + c['general information.status'] + ',' + c['general information.TB.n_baci'] + ',' + c['general information.TB.n_clus'] + ',' + c['general information.TB.infection'] + ',' + c['general information.name info.first name'] + ',' + c['general information.name info.last name'] + ',' + c['general information.gender'] + ',' + c['general information.age'] + ',' + c['general information.address info.address'] + ',' + c['general information.address info.cityvillage']
      ser.write(send)
      time.sleep(0.1)
      if ser.readline()[0] == 'D':
        print 'SMS sent! Hopefully'

  # Send commands to move the microscope
  if msg.topic == "/tab/send/microscope/serial":
    print str(msg.payload)
    client.publish('/server/send/microscope/serial', msg.payload)
  if msg.topic == "/tab/send/microscope/startdiagnostic":
    print str(msg.payload)
    client.publish('/server/send/microscope/startdiagnostic', msg.payload)
  
  # Send commands to move the box
  if msg.topic == "/tab/send/box/openclose":
    client.publish('/server/send/box/openclose', msg.payload)

  if msg.topic == "/box/send/server/temp":
    db1.box.update({'id':'box'},{'$push':{'temp':str(msg.payload)}})
  if msg.topic == "/box/send/server/hum":
    db1.box.update({'id':'box'},{'$push':{'temp':str(msg.payload)}})
  if msg.topic == "/box/send/server/slides":
    db1.box.update({'id':'box'},{'$push':{'temp':str(msg.payload)}})

  '''Receive from microscope'''
  # Result of diagnostics
  if msg.topic == "/microscope/send/server/diagnostic_result":
    line = (msg.payload).split(';')
    db.patients.update({'id':line[0]}, {'$set':{ 
            'general information.TB':{
              'n_baci': line[1],
              'n_clus': line[2],
              'infection': line[3]
        }
      }
    })

  if msg.topic=="/tab/send/server/patient":
    print str(msg.payload)
  if msg.topic=="/tab/send/server/vitals":
    print str(msg.payload)
  if msg.topic=="/tab/send/server/GI":
    print str(msg.payload)
  if msg.topic=="/tab/send/server/RI":
    print str(msg.payload)
  if msg.topic=="/tab/send/server/AP":
    print str(msg.payload)
  if msg.topic == "/box/send/server/temp":
    print str(msg.payload)
  if msg.topic == "/box/send/server/hum":
    db1.box.update({'id':'box'},{'$push':{'temp':str(msg.payload)}})
  if msg.topic == "/box/send/server/slides":
    db1.box.update({'id':'box'},{'$push':{'temp':str(msg.payload)}})

def get_now():
  now = datetime.datetime.now()
  return now.year, now.month, now.day, now.hour, now.minute, now.second 

if __name__ == '__main__':
  #db.box.insert_one({'id':'box','temp':[],'hum':[],'slides':[]}) 
  client = mqtt.Client()
  #client.connect('mosquitto.org', 1883, 60)
  client.connect('192.168.42.1', 1883, 60)
  client.on_connect = on_connect
  client.on_message = on_message
  client.loop_forever()