#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import subprocess
import datetime

def sensor_read(params):
    '''Read sensor parameters from sashaws using the getINDI command through ssh'''

    user = "observer"
    host = "sashaws.shark-nir.lbto.org"
    cmd = "/opt/local/sharknir/bin/getINDI"
    
    try:
        res = subprocess.Popen("ssh {}@{} {} {}".format(user, host, cmd, params), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = res.communicate()
        getindi_array = stdout.split("\n")#[:-1]
        getindi_values = [g for g in getindi_array if ".value" in g ]
        #print(getindi_values)
        temp = [float(l.split("=")[1]) for l in getindi_values]
        
        print(datetime.datetime.now().isoformat(), str(temp))

        return temp

    except Exception as e:

        print(datetime.datetime.now().isoformat(), e)

        if "temp" in params:
            return ["NaN","NaN","NaN","NaN"]
        else:
            return ["NaN"]    


def sensor_send(channels, values):
    '''Send sensor values to EPICS channels using the caput command'''

    sh = "/bin/sh -l -c"
    cmd = "/opt/epics/bin/linux-x86_64/caput"
    
    try:
        for channel,value in zip(channels,values):

            # Sending temperature or pressure
            res = subprocess.Popen("{} '{} {} {}'".format(sh, cmd, channel, value), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdout, stderr = res.communicate()            
            print(datetime.datetime.now().isoformat(), stdout, stderr)
 
            # Sending gradient of temperature1:
            temp = "temperature1"
            if stdout and temp in channel:
                
                channel = "shark:nir:cv:gradientTemp1"
                old_and_new = stdout.replace(temp, "\n").split("\n") # isolate values in string
                
                try:
                    value = float(old_and_new[3]) - float(old_and_new[1])
                    res = subprocess.Popen("{} '{} {} {}'".format(sh, cmd, channel, value), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                except Exception as e:
                    value = "NaN"
                    res = subprocess.Popen("{} '{} {} {}'".format(sh, cmd, channel, value), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    
                stdout, stderr = res.communicate()            
                print(datetime.datetime.now().isoformat(), stdout, stderr)

            
    except Exception as e:

        print(e)

    
def run():
    '''Get values and then send them, looping forever'''
        
    # Send temperatures. Also calculates and send gradientTemp1
    channels = ["shark:nir:cv:temperature1",
                "shark:nir:cv:temperature2",
                "shark:nir:cv:temperature3",
                "shark:nir:cv:temperature4"]
    temperatures = sensor_read("sharknir_temp.sensor")
    sensor_send(channels, temperatures)

    # Send pressure
    channels = ["shark:nir:cv:pressure"]
    pressure = sensor_read("sharknir_pres1.sensor.value")
    sensor_send(channels, pressure)


if __name__ == "__main__":
    '''If running from command line'''
        
    run()
