jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Pi as a datalogger

Fri Sep 27, 2013 10:25 am

I have built an earth resistivity meter using two digital multimeters. I would now like to use my Pi as a data logger to record voltage and current data from the multimeters via their RS232 outputs. The plan would be to record data at the press of a button. As a total electronics novice where do I start?

User avatar
rurwin
Forum Moderator
Forum Moderator
Posts: 4257
Joined: Mon Jan 09, 2012 3:16 pm
Contact: Website

Re: Pi as a datalogger

Fri Sep 27, 2013 11:16 am

As you have two meters, you will have to get two RS232 interfaces for the RaspPi. At least one of those will have to be a USB one, so they both may as well be. That means you don't have to worry about hooking up the GPIO pins and stopping the existing process that uses it. Some RS232 USB interfaces may not work with the Pi, but searching this forum should give you an idea what to look for.

Then you need a program to fetch readings from the meters, decode it and save it to a file. You will need to choose a programming language and write the program. As the first part of that, you will have to learn the protocol that the meters use to communicate. That may possibly be in the meter's user manuals, but more likely you will have to get it from the manufacturers.

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Fri Sep 27, 2013 2:25 pm

I was thinking of replacing my multimeters with the Yocto-Amp and Yocto-Volt sensors but I have read on the following blog that there is a USB for raspi-yocto combination glitch.

http://www.yoctopuce.com/EN/article/tur ... multimeter
http://www.yoctopuce.com/EN/article/the ... al-mini-pc

Is it worth trying the Yocto sensors or should I just forget it and stick with my RS232 multimeters for now?

jdb
Raspberry Pi Engineer & Forum Moderator
Raspberry Pi Engineer & Forum Moderator
Posts: 2661
Joined: Thu Jul 11, 2013 2:37 pm

Re: Pi as a datalogger

Fri Sep 27, 2013 3:38 pm

As far as I am aware (because I wrote the patches for it), the underlying issues talking to the sort of devices used in various Yoctopuce modules have all been squashed for some time. You should not need to use dwc_otg.speed=1.
Rockets are loud.
https://astro-pi.org

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Mon Oct 14, 2013 12:40 am

I now have three youctopuce units but I immediately encountered the packet loss problem when connecting them to my Raspberry Pi. Based on jdb’s post above I assumed this was because my Linux was not fully up to date so I ran the linux debian update. My system did need updating but it did not solve the problem.

At this, I thought I’d better test the yoctopuce units to make sure they were working correctly. I tried them on my PC they do exactly what I want.

To try and get them to work correctly on the Raspberry Pi I then modified the command line with the addition of dwc_otg.speed=1 but my combined USB keyboard and mouse now doesn’t work and I can’t interact with the Raspberry Pi at all.

HELP!

Can anyone recommend or suggest a combined USB keyboard and mouse that is certain to work with the usb ports set to dwc_otg.speed=1 ?

PS – In desperation I put the SD card in my PC and found I could modify the command line text there so I have at least managed to remove dwc_otg.speed=1, for the time being, but this obviously renders my youctopuce units useless :(

1pi2much
Posts: 99
Joined: Sun Feb 24, 2013 6:58 pm

Re: Pi as a datalogger

Mon Oct 14, 2013 12:53 am

jakegnone wrote: HELP!

Can anyone recommend or suggest a combined USB keyboard and mouse that is certain to work with the usb ports set to dwc_otg.speed=1 ?
Dont know much about dws_otg but if you have a network connection you could login to your pi
using ssh from a remote laptop/pc and not need the usb keyboard and mouse. If you need a
graphical user interface, you can run vnc on the pi and access it from another networked computer.

--

thradtke
Posts: 724
Joined: Wed May 16, 2012 5:16 am
Location: Germany / EL

Re: Pi as a datalogger

Mon Oct 14, 2013 5:52 am

A webserver might be used to present data and offer a download option.
Rocket Scientist.

User avatar
DeeJay
Posts: 2026
Joined: Tue Jan 01, 2013 9:33 pm
Location: East Midlands, UK

Re: Pi as a datalogger

Mon Oct 14, 2013 8:51 am

thradtke wrote:A webserver might be used to present data and offer a download option.
But the OP hasn't got the data from the sensors yet...
How To Ask Questions The Smart Way: http://www.catb.org/~esr/faqs/smart-questions.html
How to Report Bugs Effectively: http://www.chiark.greenend.org.uk/~sgtatham/bugs.html

User avatar
DeeJay
Posts: 2026
Joined: Tue Jan 01, 2013 9:33 pm
Location: East Midlands, UK

Re: Pi as a datalogger

Mon Oct 14, 2013 8:53 am

jakegnone wrote:I now have three youctopuce units but I immediately encountered the packet loss problem when connecting them to my Raspberry Pi.
This isn't my area of knowledge, but how do you know you encountered that problem? And is it possible that it is related to a usb hub, or software, rather than the RPi?
How To Ask Questions The Smart Way: http://www.catb.org/~esr/faqs/smart-questions.html
How to Report Bugs Effectively: http://www.chiark.greenend.org.uk/~sgtatham/bugs.html

thradtke
Posts: 724
Joined: Wed May 16, 2012 5:16 am
Location: Germany / EL

Re: Pi as a datalogger

Mon Oct 14, 2013 9:25 am

DeeJay wrote:But the OP hasn't got the data from the sensors yet...
My comment was related to 1pi2much's answer above. Besides, it's never too early to outline the whole project ;).
Rocket Scientist.

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Mon Oct 14, 2013 10:11 am

if you have a network connection you could login to your pi
using ssh from a remote laptop/pc and not need the usb keyboard and mouse.
Thanks for the idea 1pi2much but I'm trying to make a portable device for use in the field so a I don't have network access.

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Mon Oct 14, 2013 10:23 am

how do you know you encountered that problem? And is it possible that it is related to a usb hub, or software, rather than the RPi?
Deejay, I know this is the problem as the yoctopuce units come with a test controller called yoctohub. When I launch yoctohub it reports there being packet loss.

As for your second question re the usb hub, software and pi. I don't know for sure. I will try to connect the units directly to the pi (one by one). As for software, what software are you referring to?The units are driven by python code. The same python file drives the units perfectly on my pc.

User avatar
DeeJay
Posts: 2026
Joined: Tue Jan 01, 2013 9:33 pm
Location: East Midlands, UK

Re: Pi as a datalogger

Mon Oct 14, 2013 10:29 am

jakegnone wrote: As for software, what software are you referring to?
I wondered if you might be running this VirtualHub package which might have introduced a source for problems?
How To Ask Questions The Smart Way: http://www.catb.org/~esr/faqs/smart-questions.html
How to Report Bugs Effectively: http://www.chiark.greenend.org.uk/~sgtatham/bugs.html

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Mon Oct 14, 2013 10:39 am

I wondered if you might be running this VirtualHub package which might have introduced a source for problems?
Yes, my mistake. It was the VirtualHub package I used and it's this that is reporting the packet errors.

However, I'm not using this in my python code and, as I mentioned in an earlier post, the same file works perfectly on my pc where as on the pi I just get a reading of 0.0 every time.

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Mon Oct 14, 2013 10:40 am

it's never too early to outline the whole project
thradtke, happy to oblige. Is there a guide to making a project outline? I'm not sure what you want to know.

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Mon Oct 14, 2013 11:28 am

Thanks you all. With your help I have narrowed the problem down to the usb hub. I connected the yoctopuce units directly to the pi (one-by-one) and they all worked perfectly - horray!

Can anyone suggest a usb hub that won't disrupt their communication with the pi?

thradtke
Posts: 724
Joined: Wed May 16, 2012 5:16 am
Location: Germany / EL

Re: Pi as a datalogger

Mon Oct 14, 2013 1:20 pm

jakegnone wrote:thradtke, happy to oblige. Is there a guide to making a project outline? I'm not sure what you want to know.
I suspect there's a misunderstanding due to myself not beeing a native english speaker. Sorry for interfering in your thread.
Rocket Scientist.

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Mon Oct 14, 2013 4:10 pm

the Pi has trouble to handle the encapsulation of USB 1.1 packets in USB 2.0 traffic. When you connect a USB 1.1 device to the Pi, traffic
is chunk into pieces and encapsulated in USB 2.0 packets. It is up to the root hub (the Pi) to rebuild the original USB 1.1 packets. Originally this did work very bad, and after some fixes it works significantly better. But whatever type of Hub you put behind the Pi, it will put this part of code from the Pi under stress. I am not sure changing the hub will make a difference, it can well be that the Pi just cannot cope with the load of encapsulated traffic.
Thanks to Yoctopuce support for the above quote. Based on this I have reconfigured the yotopuce sensors so one goes straight into the pi and the other goes through the hub and I have removed my wifi dongle. The result... success! My sensors work. So just to confirm it seems not to be a hub problem but rather an overload of encapsulated traffic.

User avatar
jbeale
Posts: 3893
Joined: Tue Nov 22, 2011 11:51 pm
Contact: Website

Re: Pi as a datalogger

Mon Oct 14, 2013 4:30 pm

Just FWIW: not all USB hubs are created equal. Almost without exception, the cheapest tier of USB hubs have only one "TT" module for the entire hub. (TT = Transaction Translator, the thing that makes USB2 and USB1.1 devices work together). That can cause trouble with the R-Pi, depending what you have plugged in. Some better hubs, such as this one: http://www.theregister.co.uk/Print/2013 ... i_usb_hub/
have a "multi-TT" or "TT-per-port" design, which is known to work better on the Pi.

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Mon Oct 14, 2013 7:14 pm

jbeale wrote:Just FWIW: not all USB hubs are created equal. Almost without exception, the cheapest tier of USB hubs have only one "TT" module for the entire hub. (TT = Transaction Translator, the thing that makes USB2 and USB1.1 devices work together). That can cause trouble with the R-Pi, depending what you have plugged in. Some better hubs, such as this one: http://www.theregister.co.uk/Print/2013 ... i_usb_hub/
have a "multi-TT" or "TT-per-port" design, which is known to work better on the Pi.


jbeale, thanks. I will get one next month and report back on what difference it makes.

thradtke
Posts: 724
Joined: Wed May 16, 2012 5:16 am
Location: Germany / EL

Re: Pi as a datalogger

Tue Dec 10, 2013 11:59 am

jakegnone wrote:jbeale, thanks. I will get one next month and report back on what difference it makes.
Any insights?
Rocket Scientist.

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Sat Mar 08, 2014 7:22 pm

I have finally built my Pi controlled Archaeological Resistivity Meter. I had to give up with the Yoctopuce voltmeter, ammeter and display as I was unable to resolve the USB problems they had when connected to the Pi. Instead, I replaced them with two USB Digitek DT-4000ZC multimeters (£22 each) and a 3.5 inch TFT LCD digital car rear view monitor ( £14) connected to the Pi using the RCA cable. I use the Pi to collect a sequence of different readings using an 8 way serial relay controlled by a BV4111 microcontroller (£20) connected via the GPIO pins. All the components are powered by a EasyAcc 10000mAh dual USB battery (£22). To get the 6v monitor to work I boosted the 5v provided via the USB with a 1.5v battery.

The working resistivity meter can be seen at:

http://youtu.be/QiSPwnuRJ3Q

Blender1985
Posts: 2
Joined: Mon May 26, 2014 3:31 pm

Re: Pi as a datalogger

Mon May 26, 2014 3:58 pm

Hi. How can I install the software for this DMM? I'm trying to set up a similar system and am a complete noob to raspberry Pi/Linux etc

Thanks

tjfinan
Posts: 2
Joined: Fri Jan 02, 2015 8:47 pm

Re: Pi as a datalogger

Fri Jan 02, 2015 8:49 pm

I was hoping that we might be able see more details on this project. I am particularly interested in the code and the method by which you put together the DMM to achieve your results.

Ive also pondered whether using arduinos as multimeters would get the job done equally well, with a RPi in between to read the data.

Thanks very much. This is very exciting.

jakegnone
Posts: 18
Joined: Fri Sep 27, 2013 10:12 am

Re: Pi as a datalogger

Sun Feb 01, 2015 9:07 pm

Dear all,

Here is the code for my Raspberry Pi controlled Resistivity Meter.

You can see the blueprints and the working meter on Youtube here:

https://www.youtube.com/channel/UC7-Kyy ... GYmacrHMqg

I am self-taught so I'm sure the code is very crude and can be much improved. I am keen to hear from anyone who can help make it better.

Please note that the code imports the drivers for the serial relay (BV4111) and the millimetres (tp4000zc). These are available from their manufacturers and can be downloaded online.

Thanks

Mike

Code: Select all

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

#file opening code is as follows:
#sudo python arez.py "/dev/ttyAMA0"

##modules

import os,sys,time
import math

from time import gmtime, strftime, sleep

import pygame, pygame.font, pygame.event, pygame.draw, string
from pygame.locals import *

import random
from collections import defaultdict

import PIL
from PIL import Image, ImageDraw, ImageFont

import BV4111

import tp4000zc

####
##VERSION
version_no = "2.3"

####
###Draw variables
x = 1
WIDTH, HEIGHT = 656,416
#WIDTH, HEIGHT = 572,312
width, height = WIDTH, HEIGHT

white = (255,255,255)
black = (0,0,0)
orange = (247, 125, 17)
crimson =(220,20,60)
blush =(139,131,134)
purple = (205,105,201)
blue = (0,0,238)
royal_blue = (67,110,238)
sea_blue = (99,110,238)
hookers_green = (0,100,0)
forest_green = (34,139,34)
field_green = (154,205,50)
roughgrazing = (202,255,47)
beach =(255,246,143)
dark_beach = (189,183,107)
gold = (205,173,0)
orange = (255,165,0)
brown_orange = (205,133,0)
red = (255,0,0)
sienna = (255,130,71)
yellow_green = (154,205,50)
dark_green = (107,142,35)
green_yellow = (173,255,47)

colour = orange

dimensions = (WIDTH,HEIGHT)

img = Image.new("RGB", dimensions)
d = ImageDraw.Draw(img)
f_font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf",18)

####
def debugging(text, prefix = "a"):
    """To create a debug file: bug = True"""
    
    bug = True
    debug_file = "arez_debug"

    if bug:
        text_file = open(debug_file, prefix)
        text_file.writelines(text)
        text_file.close()
    else:
        pass

########
debugging("Dairsie D"+version_no+" Archaeological Resistivity Meter\n"\
          "Mike Middleton\n"\
          "www.dairsieonline.co.uk\n"\
          "Debugging\nTEST\n\n", "w")

#variables and settings
probe_seperation = 0.75
pause = 0
display_time = 1
repeat = 2
# 100 = 282.4s or 4m42.4s, 25 = 75s
# 10 = 34.7s, 9 = 31.6s, 8 = 29.3s, 7 = 26.8s, 6 = 24.2s
# 5 = 21.1s, 4 = 18.9s, 3 = 16.2s, 2 = 12.9s, 1 = 10.0s
####
TEST_LENGTH = 100

"""plot variables"""
colours = 5

####
debugging("AA: Modules and global values loaded - Done\n")

##initiate pygame
pygame.init()
screen=pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN)
#screen=pygame.display.set_mode((WIDTH, HEIGHT))
pygame.mouse.set_visible(0)
pygame.display.set_caption("Dairsie D"+version_no+" Resistivity Meter")
font = pygame.font.SysFont("Arial",50)

def clear_screen(screen, width, height):
    rectangle = ((0,0),(width, height))

    screen.fill((sea_blue))
    
    pygame.display.update()

    return

def voltage():
    ##VOLTAGE

    time.sleep(pause)

    volt = "missing packet"
    volt_list = []

    i = 0
    port = '/dev/ttyUSB1'
    dmm = tp4000zc.Dmm(port)

    while i < repeat:

        volt_reading = dmm.read()
        
        volt = round(volt_reading.numericVal,5)
        message = str(volt*1000)+" mV DC"

        volt_list.append(volt)

        i+=1

    dmm.close()

    try:
        plot_message2(message, font, screen)
    except:
        pass

    ####
    if volt == "missing packet":
        debugging("AC: Voltage NOT recorded - FAIL\n")
    else:
        debugging("AC: Voltage recorded - Done\n")

    return volt, volt_list

def current():
    ##AMMETER

    time.sleep(pause)

    current = "missing packet"
    amp_list = []

    i = 0
    port = '/dev/ttyUSB0'
    dmm = tp4000zc.Dmm(port)

    while i < repeat:
        
        amps_reading = dmm.read()

        current = round(amps_reading.numericVal,5)
        message = str(current*1000)+" mA DC"

        amp_list.append(current)

        i+=1

    dmm.close()
    try:
        plot_message2(message, font, screen)
    except:
        pass

    if current == "missing packet":
        debugging("AD: Current NOT recorded - FAIL\n")
    else:
        debugging("AD: Current recorded - Done\n")

    return current, amp_list

def probe():

    probe_seperation = None
    
    while probe_seperation == None:
        message = "Enter probe seperation (m)"
        plot_message(message, font, screen)
        probe_seperation = ask(screen, "probe_sep")

    ok = ""

    while ok.upper() not in ("Y","N"):
        message = str(probe_seperation) + "m ok? (y)(n)"
        plot_message(message, font, screen)
        ok = enter_key()

    if ok.upper() in ("Y"):
        debugging("AG: Probe seperation - Done\n")
        return probe_seperation
    else:
        debugging("AG: Probe seperation - FAIL\n")
        probe()

def set_date(font, screen):

    day, month, year = "##","##","####"
    date_in = None
    again = "n"
    
    message= "Enter date: DDMMYYYY"
    while date_in == None:
        plot_message(message, font, screen)

        date_in = ask(screen, "Date")

        if len(date_in) < 8 or len(date_in) > 8:
            date_in = None

        if date_in == None:
            pass
        else:
            for val in date_in:
                if val not in ("0","1","2","3","4","5","6","7","8","9"):
                    date_in = None
                else:
                    pass
                
            if date_in == None:
                pass
            else:
                day = date_in[:2]
                month = date_in[2:4]
                year = date_in[4:]

                day_list = []
                i = 1
                while i < 32:
                    day_list.append(i)
                    i+=1

                if int(day) not in day_list:
                    date_in = None
                else:
                    pass

                month_list = []
                i = 1
                while i < 13:
                    month_list.append(i)
                    i+=1

                if int(month) not in month_list:
                    date_in = None
                else:
                    pass

                if int(year) < 2013:
                    date_in = None
                else:
                    pass

                if date_in == None:
                    pass
                else:
                    month = get_month(month)

                    ok = ""

                    while ok.upper() not in ("Y","N"):
                        message= str(day)+" "+month+" "+str(year)+" ok? (y/n)"
                        plot_message(message, font, screen)
                        ok = enter_key()

                    if ok.upper() in ("Y"):
                        pass
                    else:
                        date_in = None

        if date_in == None:
            message = "input error..."
            plot_message(message, font, screen)
            time.sleep(2)
            message = "Enter date: DDMMYYYY"
        else:
            pass

    debugging("AH: Date set - Done\n")

    return day, month, year, date_in

def set_time(font, screen):
    """get time from user"""

    message= "Enter time: HHMM  (24H)"
    plot_message(message, font, screen)
    time_in = None
    while time_in == None:
        time_in = ask(screen, "Time")

        if len(time_in) < 4 or len(time_in) > 4:
            time_in = None
        else:
            pass

        if time_in == None:
            pass
        else:
            for val in time_in:
                if val not in ("0","1","2","3","4","5","6","7","8","9"):
                    time_in = None
                else:
                    pass
                
            if time_in == None:
                pass
            else:
                time_h = time_in[:2]
                time_m = time_in[2:]


            if time_in == None:
                pass
            else:
                if int(time_h) >23:
                    time_in = None
                else:
                    pass

            if time_in == None:
                pass
            else:
                if int(time_m) >59:
                    time_in = None
                else:
                    pass

        if time_in == None:
            pass
        else:

            ok = ""

            while ok.upper() not in ("Y","N"):
                message= str(time_h)+":"+str(time_m)+" ok? (y/n)"
                plot_message(message, font, screen)
                ok = enter_key()

            if ok.upper() in ("Y"):
                pi_h = time.strftime("%H", gmtime())
                pi_m = time.strftime("%M", gmtime())

                h_factor = int(time_h) - int(pi_h)
                m_factor = int(time_m) - int(pi_m)
    
            else:
                time_in = None

        if time_in == None:
            message = "input error..."
            plot_message(message, font, screen)
            time.sleep(2)
            message = "Enter time: HHMM  (24H)"
        else:
            pass

    debugging("AI: Time set - Done\n")

    return h_factor, m_factor, time_in

def add_zero(number):
    if len(number) == 1:
        number = "0"+str(number)
    else:
        pass

    debugging("AJ: Add zero - Done\n")

    return number

def get_time(h_factor, m_factor):

    hour = str(int(time.strftime("%H", gmtime()))+h_factor)
    hour = add_zero(hour)
    minute = str(int(time.strftime("%M", gmtime()))+m_factor)
    minute = add_zero(minute)
    second = time.strftime("%S", gmtime())
    second = add_zero(second)

    debugging("AK: Get time - Done\n")
    
    return hour, minute, second

def new_setup(font, screen, key):
    """set up a new survey"""
  
    ## Start at point 1
    point = 1

    if key == "N":

        ## Date
        date_in = None
        while date_in == None:
            day, month, year, date_in = set_date(font, screen)

        ## time
        time_in = None
        while time_in == None:
            h_factor, m_factor, time_in = set_time(font, screen)

        hour, minute, second = get_time(h_factor, m_factor)
    else:
        day, month, year, date_in = "01","Jan","2014","01012014"
        h_factor, m_factor, time_in = 0,0,"0000"

    ## set filename
    filename = None
    while filename == None:
        filename = set_filename(filename,font, screen)

        if filename == None:
            pass
        else:
            try:
                text_file = open(filename, "r")
                text_file.close()
                try:
                    message = "File already exists"
                    plot_message(message, font, screen)
                    time.sleep(2)
                except:
                    pass
                filename = None
            except:
                pass
                
    
    template = "point,line,position,resistivity," \
                 "difference,volt1,volt2," \
                 "volt3,volt4,current,time,date," \
                 "volt_list,current_list\n"

    write_data(filename, template)

    debugging("AL: Set up new survey - Done\n")

    return year, month, day, h_factor, m_factor, filename, point

def load_data(choice):

    if choice == "R":
        day, month, year, date_in = "01","Jan","2014","01012014"
        h_factor, m_factor, time_in = 0,0,"0000"
    else:
        ## Date
        date_in = None
        while date_in == None:
            day, month, year, date_in = set_date(font, screen)

        ## time
        time_in = None

        while time_in == None:
            h_factor, m_factor, time_in = set_time(font, screen)

    ## get filename
    filename = None
    while filename == None:
        filename = set_filename(filename,font, screen)

        if filename == None:
            pass
        else:
            try:
                text_file = open(filename, "r")
                lines = text_file.readlines()
                text_file.close()
                last_line = lines[-1]
                last_line_list = last_line.split(",")
                point = int(last_line_list[0])+1
            except:
                try:
                    message = "File not found"
                    plot_message(message, font, screen)
                    time.sleep(2)
                except:
                    pass

                filename = None
                
    debugging("AL: Load data - Done\n")

    return year, month, day, h_factor, m_factor, filename, point

def set_filename(filename,font, screen):

    while filename == None:
        message = "Enter file name"
        plot_message(message, font, screen)
        filename = ask(screen, "Filename")

        if filename == None:
            pass
        else:
            ok = ""
            
            while ok.upper() not in ("Y","N"):
                message = str(filename)+" (y/n)"
                plot_message(message, font, screen)
                ok = enter_key()

            if ok in ("Y","y"):
                pass
            else:
                filename = None

    if filename.upper() == "E":
        filename = "E"
    else:
        if filename[-4:] == ".txt":
            pass
        else:
            filename+=".txt"

    debugging("AM: Set filename - Done\n")

    return filename

def find_line_pos(point):

    i = 0
    while point>20:
        point-=20
        i+=1

    line = i
    position = point-1

    debugging("AR: Line position found - Done\n")

    return line, position

def get_month(month):

    if int(month)==1:
        month = "Jan"
    elif int(month)==2:
        month = "Feb"
    elif int(month)==3:
        month = "Mar"
    elif int(month)==4:
        month = "Apr"
    elif int(month)==5:
        month = "May"
    elif int(month)==6:
        month = "Jun"
    elif int(month)==7:
        month = "Jul"
    elif int(month)==8:
        month = "Aug"
    elif int(month)==9:
        month = "Sep"
    elif int(month)==10:
        month = "Oct"
    elif int(month)==11:
        month = "Nov"
    elif int(month)==12:
        month = "Dec"
    else:
        pass

    debugging("AN: Month set - Done\n")

    return month

def write_result(year, month, day, filename, point, h_factor, m_factor, result, assessment):
    
    line, position = find_line_pos(point)
    
    current = round(result[4],5)
    volt1, volt2, volt3, volt4 = round(result[0],5), round(result[1],5), round(result[2],5), round(result[3],5)
    resistivity = result[7]
    volt_list = result[5]
    current_list = result[6]

    hour, minute, second = get_time(h_factor, m_factor)
    time = hour+":"+minute+":"+second
    date = day+":"+month+":"+year

    data = str(point)+","+str(line)+","+str(position)+","+\
            str(resistivity)+","+str(assessment)+","+ \
            str(volt1)+","+str(volt2)+","+ \
            str(volt3)+","+str(volt4)+","+str(current)+","+time+","+date+","+\
            str(volt_list)+","+str(current_list)+"\n"
  
    debugging("AO: Results prepared to be written - Done\n")

    write_data(filename, data)

def write_data(filename, data):

    text_file = open(filename, "a")
    text_file.writelines(str(data))

    text_file.close()

    debugging("AP: Results written - Done\n")

def switch_all_off(Devd):
    #all lights off
    Devd.Rly(1,1,0)
    Devd.Rly(2,1,0)
    Devd.Rly(3,1,0)
    Devd.Rly(4,1,0)
    Devd.Rly(5,1,0)
    Devd.Rly(6,1,0)
    Devd.Rly(7,1,0)
    Devd.Rly(8,1,0)

    debugging("AQ: Relays all off - Done\n")

def switch_all_on(Devd):
    #all lights off
    Devd.Rly(1,0,0)
    Devd.Rly(2,0,0)
    Devd.Rly(3,0,0)
    Devd.Rly(4,0,0)
    Devd.Rly(5,0,0)
    Devd.Rly(6,0,0)
    Devd.Rly(7,0,0)
    Devd.Rly(8,0,0)

    debugging("AS: Relays all on - Done\n")

def probe_bc(Devd):
    #one and three lights on
    #Volt -
    Devd.Rly(1,0,0)
    Devd.Rly(3,0,0)
    
    debugging("AT: probes bc active - Done\n")

def probe_cb(Devd):
    #two and four lights on
    #Volt +
    Devd.Rly(2,0,0)
    Devd.Rly(4,0,0)
    
    debugging("AU: Probes cb active - Done\n")
    
def probe_ad(Devd):
    #five and seven lights on
    #Amp -
    Devd.Rly(5,0,0)
    Devd.Rly(7,0,0)
    
    debugging("AV: Probes ad active - Done\n")

def probe_da(Devd):
    #six and eight lights on
    #Amp +
    Devd.Rly(6,0,0)
    Devd.Rly(8,0,0)
    
    debugging("AW: Probes da active - Done\n")

def process():
    ##Initiate relay switches
    sp = BV4111.sv3clV2_2.Connect(sys.argv[1],115200)

    # class instance for sv3 device, assume address 'a' and
    # default ack
    Devd = BV4111.bv4111(sp,'d')
    d = Devd.Discover()
    
    #### Data gathering
    result = []
    
    amp_list = []

    master_volt_list = []
    master_current_list = []

    ##short: prepare sensors
    probe_cb(Devd)
    probe_da(Devd)
    try:
        amp_test, current_list = current()
        master_current_list += current_list
    except:
        amp_test = "fail"
        
    amp_list.append(amp_test)
    switch_all_off(Devd)

    ##take reading
    #V+
    probe_cb(Devd)
    try:
        volt1, volt_list = voltage()
        master_volt_list += volt_list
    except:
        volt1 = "fail"
        
    result.append(volt1)
    
    #A+
    probe_ad(Devd)
    try:
        volt2, volt_list = voltage()
        master_volt_list += volt_list
    except:
        volt1 = "fail"
        
    result.append(volt2)
    
    try:
        amp1, current_list = current()
        master_current_list += current_list
    except:
        amp1 = "fail"

    amp_list.append(amp1)
    
    switch_all_off(Devd)
    #V-
    probe_bc(Devd)
    try:
        volt3, volt_list = voltage()
        master_volt_list += volt_list
    except:
        volt3 = "fail"

    result.append(volt3)
    
    probe_da(Devd)
    
    #A-
    try:
        volt4, volt_list = voltage()
        master_volt_list += volt_list
    except:
        volt3 = "fail"

    result.append(volt4)
    
    try:
        amp2, current_list = current()
        master_current_list += current_list
    except:
        amp2 = "fail"

    amp_list.append(amp2)
    
    amp = 0
    fail = False
    for reading in amp_list:
        if reading == "fail":
            fail = True
        else:
            amp+=reading

    if fail:
        amp = "fail"
    else:
        amp = amp_list[-1]
        
    result.append(amp)
    switch_all_off(Devd)

    result.append(master_volt_list)
    result.append(master_current_list)

    debugging("AX: Point recorded - Done\n")

    return result

def review(result):
    """Examinbe results and assess worth"""

    assessment = ""
    good_data = True

    for reading in result:
        if reading == "fail":
            good_data = False
        else:
            pass

    if good_data:

        ### sort results
        current = result[4]
        v1, v2, v3, v4 = result[0], result[1], result[2], result[3]

        ## analise results
        v_pos = v2-v1
        v_minus = v4-v3
        difference = v_pos-v_minus
        average = (v_pos+v_minus)/2

        if current == 0:
            assessment = "FAIL: Current"
            message = assessment
            try:
                plot_message2(message, font, screen)
                time.sleep(4)
            except:
                pass
        else:
            resistance = average/current
            resistivity = 2*math.pi*probe_seperation*resistance
            assessment = round(difference*1000,3)

            if int(resistivity) < 0:
                resistivity *=-1
            else:
                pass
            
            result.append(int(resistivity))

    else:
        assessment = "FAIL: Missing Data"
        #print(assessment)
        message = assessment
        try:
            plot_message2(message, font, screen)
            time.sleep(4)
        except:
            pass

    debugging("AY: Assessment - Done\n")

    return assessment

def last(filename):

    text_file = open(filename, "r")
    lines = text_file.readlines()
    text_file.close()
    last_line = lines[-1]
    last_line_list = last_line.split(",")
    line = last_line_list[1]
    pos = last_line_list[2]
    last_resistivity = last_line_list[3]
    message = "last: "+str(line)+":"+str(pos)+" : "+str(last_resistivity)+" ohm-m"
    try:
        plot_message(message, font, screen)
        time.sleep(4)
    except:
        pass

    debugging("AZ: Last line of file identifed - Done\n")

def last_rez(filename):

    text_file = open(filename, "r")
    lines = text_file.readlines()
    text_file.close()
    last_line = lines[-1]
    last_line_list = last_line.split(",")
    line = last_line_list[1]
    pos = last_line_list[2]
    last_resistivity = last_line_list[3]

    return last_resistivity


def delete(filename, point):

    message = "Delete? (y/n)"
    plot_message(message, font, screen)
    choice = ""
    while choice.upper() not in ("Y", "N"):
        choice = enter_key()

    if choice in ("Y","y"):
        text_file = open(filename, "r")
        lines = text_file.readlines()
        text_file.close()
        new_lines = lines[:-1]
        text_file = open(filename, "w")
        text_file.close()
        for line in new_lines:
            write_data(filename, line)

        text_file = open(filename, "r")
        lines = text_file.readlines()
        text_file.close()
        last_line = lines[-1]
        last_line_list = last_line.split(",")
        point = int(last_line_list[0])+1
    else:
        pass

    debugging("BA: Point deleted from file - Done\n")

    return point
    
def close():
    choice_exit = ""

    while choice_exit.upper() not in ("O","S"):
        message = "(O)ffice : (S)hut down"
        plot_message(message, font, screen)

        choice_exit = enter_key()

    if choice_exit.upper() == "O":
        message = "Good bye"
        plot_message(message, font, screen)
        time.sleep(4)
        message = ""
        plot_message(message, font, screen)
        time.sleep(1)

        debugging("BB: Exit to office - Done\n")

        sys.exit()

    if choice_exit.upper() == "S":
        message = "Shut down"
        plot_message(message, font, screen)
        time.sleep(3)
        message = "Good bye"
        plot_message(message, font, screen)
        time.sleep(3)
        message = ""
        plot_message(message, font, screen)
        time.sleep(1)
        
        debugging("BC: Shutdown - Done\n")
        
        os.system("sudo shutdown now -h")

def plot_message(message, font, screen):

    clear_screen(screen, width, height)
    reading = font.render(message, 1, (0,0,0))
    a = font.size(message)
    x=int(a[0]/2)
    y=int(a[1]/2)
    screen.blit(reading, ((width/2)-x,(height/2)-y))
    pygame.display.update()

    #print(message)
    
    return

def plot_message2(message, font, screen):

    clear_screen(screen, width, height)
    fontobject = pygame.font.Font(None,100)
    reading = fontobject.render(message, 1, (0,0,0))
    a = fontobject.size(message)
    x=int(a[0]/2)
    y=int(a[1]/2)
    screen.blit(reading, ((width/2)-x,(height/2)-y))
    pygame.display.update()

    #print(message)
    
    return

def plot_message3(message, font, screen):

    fontobject = pygame.font.Font(None,40)
    reading = fontobject.render(message, 1, (0,0,0))
    a = fontobject.size(message)
    x=int(a[0]/2)
    y=int(a[1]/2)
    screen.blit(reading, ((width/2)-x,(height)-(3*y)))
    pygame.display.update()

    #print(message)
    
    return

def plot_message4(message, font, screen):

    fontobject = pygame.font.Font(None,100)
    reading = fontobject.render(message, 1, (0,0,0))
    a = fontobject.size(message)
    x=int(a[0]/2)
    y=int(a[1]/2)
    screen.blit(reading, ((width/2)-x,(height/2)-(3*y)))
    pygame.display.update()

    #print(message)
    
    return

def plot_message_up(message, font, screen):

    clear_screen(screen, width, height)
    reading = font.render(message, 1, (0,0,0))
    a = font.size(message)
    x=int(a[0]/2)
    y=int(a[1]/2)
    screen.blit(reading, ((width/2)-x,(height/2)-(3*y)))
    pygame.display.update()

    
    return

def plot_message_down(message, font, screen):

    reading = font.render(message, 1, (0,0,0))
    a = font.size(message)
    x=int(a[0]/2)
    y=int(a[1]/2)
    screen.blit(reading, ((width/2)-x,(height/2)+(y)))
    pygame.display.update()

    
    return

def get_key():
    while 1:
        event = pygame.event.poll()
        if event.type == KEYDOWN:
            return event.key
        else:
            pass

def display_box(screen, message):
    """print a message in a box in the middle of the screen"""
    h = 2
    v = 3
    fontobject = pygame.font.Font(None,38)
    pygame.draw.rect(screen, (0,0,0),
                     ((screen.get_width()/h)-100,
                      (screen.get_height()/v)-10,
                      200,40),0)
    pygame.draw.rect(screen, (255,255,255),
                     ((screen.get_width()/h)-102,
                      (screen.get_height()/v)-12,
                      204,44),1)
    if len(message) !=0:
        screen.blit(fontobject.render(message, 1, (255,255,255)),
                    ((screen.get_width()/h)-100,(screen.get_height()/v)-10))
    pygame.display.flip()

def ask(screen, question):
    """ask(screen, question -> answer"""
    pygame.font.init()
    current_string = []
    display_box(screen, question + ": " + string.join(current_string,""))
    while 1:
        inkey = get_key()
        if inkey == K_BACKSPACE:
            current_string = current_string[0:-1]
        elif inkey == K_RETURN:
            break
        elif inkey == K_MINUS:
            current_string.append("_")
        elif inkey <= 127:
            current_string.append(chr(inkey))
        display_box(screen, question + ": " + string.join(current_string,""))
    return string.join(current_string,"")

#######

def enter_key():
    in_key = None
    while not in_key:
        try:
            in_key = chr(get_key())
        except:
            in_key = None

    return in_key

#######
#######
"""AREZPLOT"""
def load_data2(filename):
    text_file = open(filename, "r")
    lines = text_file.readlines()
    text_file.close()

    data = []
    for line in lines:
        temp = line.split(",")
        if temp[3] == "resistivity":
            pass
        else:
            data.append(int(temp[3]))

    a= len(data)
    while a <400:
        data.append(0)
        a+=1
        

    return lines, data

def sorting(data):

    data2 = data[:]

    data2.sort()

    data_min = data2[0]
    data2.reverse()
    data_max = data2[0]

    return data_max, data_min 

def data_range(data, colours):
    ## identify max/min values

    data2 = data[:]

    data2.sort()

    data_min = data2[0]
    data2.reverse()
    data_max = data2[0]

    colour_ramp = []

    a = (data_max-data_min)/colours
    
    colour_ramp.append(data_min)

    b = data_min
    
    while b < data_max:
        b += a
        colour_ramp.append(b)
    
    return colour_ramp, data_max, data_min

def colour_choice(item, colour_ramp,colours):

    colour = (0,0,0)
    tone = 255/colours

    i = 0
    j = 0
    for ramp in colour_ramp:
        if item > ramp:
            i = tone * j
            if i>255:
                i = 255
            else:
                pass                
            colour = (i,i,i)

        else:
            pass
        j+=1

    return colour 

def point_data(lines, point):
                     
    line_data = lines[int(point)]
    i = 0
    for letter in line_data:
        if letter == "[":
            start = i+1
        if letter == "]":
            end = i
        i+=1

    current_list = line_data[start:end]

    line_data = line_data[:start-2]

    i = 0
    for letter in line_data:
        if letter == "[":
            start = i+1
        if letter == "]":
            end = i
        i+=1

    volt_list = line_data[start:end]
    volt_list = volt_list.split(",")
    
    line_data = line_data[:start-2]
    
    line_data = line_data.split(",")

    resistivity = line_data[3]
    difference = line_data[4]
    v1,v2,v3,v4 = line_data[5],line_data[6],line_data[7],line_data[8]
    current = line_data[9]
    time_is = line_data[10]
    date_is = line_data[11]

    return resistivity,difference,v1,v2,v3,v4,current,time_is,date_is,volt_list,current_list

def plot(screen,x,y,lastx,lasty,width, height):
    
    start = (lastx,lasty)
    end = (x,y)

    pygame.draw.line(screen, green_yellow, start, end,3)
    pygame.display.update()

    return x,y

def plot_rez(screen, data, colour_ramp,d, colours, filename):

    big = 400
    small = 200
    tiny = 120

    screen_size = big

    #plot_length = int(HEIGHT*0.95)
    plot_length = screen_size
    y_remains = HEIGHT-plot_length
    x_remains = WIDTH-plot_length
    lines =int(math.sqrt(len(data)))
    square_size = plot_length/lines
    #print(lines, square_size)

    rec_start = (0,0)
    rec_end = (WIDTH,HEIGHT)
    rect2 = (rec_start,rec_end)
    d.rectangle(rect2, green_yellow)

    i = 0
    point = 0
    while i<=lines-1:
        j = lines
        while j>0:  
            x = (x_remains/2)+(i*square_size)
            y = (y_remains/2)+(j*square_size)
            rect = (x,y,square_size,-square_size)
            rec_start = (x,y)
            rec_end = (x+square_size,y-square_size)
            rect2 = (rec_start,rec_end)
            try:
                item = data[point]
                colour = colour_choice(item, colour_ramp, colours)
            except:
                colour = black

            pygame.draw.rect(screen, colour, rect)

            d.rectangle(rect2, colour)

            j-=1
            point+=1

        i+=1

    """write filename on image"""
    loc = (10,20)
    d.text(loc,str(filename),black,font=f_font)

    date_is = get_date(filename)

    loc = (10,40)
    d.text(loc,str(date_is),black,font=f_font)

    loc = (10,80)
    message = "Dairsie: "+version_no
    d.text(loc,message,black,font=f_font)

    loc = (10,100)
    message = "Resistivity"
    d.text(loc,message,black,font=f_font)

    loc = (10,120)
    message = "Meter"
    d.text(loc,message,black,font=f_font)

    pygame.display.update()

def get_date(filename):
    lines, point = load_graph_data(filename)

    resistivity,difference,v1,v2,v3,v4,current,time_is,date_is,volt_list,current_list = point_data(lines, point)

    return date_is

def data_filter(data, data_max, data_min):

    new_data = []

    for reading in data:
        if reading > data_max:
            reading = data_max
        elif reading < data_min:
            reading = data_min
        else:
            pass
        
        new_data.append(reading)

    return new_data

def show(filename, letter):
    clear_screen(screen, width, height)
    
    lines, data = load_data2(filename)

    data_max, data_min = sorting(data)

    plot_data = data_filter(data, data_max, data_min)

    a= 0
    rez_list = []
    for val in data:
        if val == 0:
            pass
        else:
            rez_list.append(val)
            a+=val
    b = len(rez_list)
    av = a/b
    rez_list.sort()
    print(rez_list[0],rez_list[-1])
    print(av)
        

    start_max, start_min = data_max, data_min

    colour_ramp, data_max, data_min = data_range(plot_data,colours)

    plot_rez(screen, plot_data, colour_ramp, d,colours, filename)

    if letter == "J":
        pass
    else:
        enter_key()
    
#######
#######
"""graph data"""
def load_graph_data(filename):
    text_file = open(filename, "r")
    lines = text_file.readlines()
    text_file.close()
    for line in lines:
        line_list = line.split(",")
        point = line_list[0]

    return lines, point

def point_data(lines, point):
                     
    line_data = lines[int(point)]
    i = 0
    for letter in line_data:
        if letter == "[":
            start = i+1
        if letter == "]":
            end = i
        i+=1

    current_list = line_data[start:end]
    current_list = current_list.split(",")

    line_data = line_data[:start-2]

    i = 0
    for letter in line_data:
        if letter == "[":
            start = i+1
        if letter == "]":
            end = i
        i+=1

    volt_list = line_data[start:end]
    volt_list = volt_list.split(",")
    
    line_data = line_data[:start-2]
    
    line_data = line_data.split(",")

    resistivity = line_data[3]
    difference = line_data[4]
    v1,v2,v3,v4 = line_data[5],line_data[6],line_data[7],line_data[8]
    current = line_data[9]
    time_is = line_data[10]
    date_is = line_data[11]

    return resistivity,difference,v1,v2,v3,v4,current,time_is,date_is,volt_list,current_list

def point_coords(volt_list,current_list):

    no_volts = len(volt_list)-1
    no_current = len(current_list)-1

    volt_x_inc = (width-20)/no_volts
    current_x_inc = (width-20)/no_current

    volt_store = []
    for volt in volt_list:
        volt = float(volt)
        if volt<0:
            volt*=-1
        else:
            pass

        volt_store.append(volt)

    volt_store.sort()
    volt_max = volt_store[-1]

    y_max = ((height/2)-20)

    last_x = 0
    last_y = height/2
    x=0

    clear_screen(screen, width, height)

    start =(0,height/2)
    end = (width,height/2)
    
    pygame.draw.line(screen, black, start, end,3)
    pygame.display.update()

    for volt in volt_list:
        volt = float(volt)
        comp_volt = volt
        if comp_volt <0:
            comp_volt*=-1
            neg = True
        else:
            neg = False
        ratio = comp_volt/volt_max
        y_temp = ratio*y_max
        if neg:
            y_temp*=-1
        else:
            pass
        y=int((height/2)+y_temp)

        start = (last_x, last_y)
        end = (x,y)

        pygame.draw.line(screen, green_yellow, start, end,3)
        pygame.display.update()

        last_x = x
        last_y = y

        x+=volt_x_inc

    start = (last_x, last_y)
    end = (x-volt_x_inc,height/2)

    pygame.draw.line(screen, green_yellow, start, end,3)
    pygame.display.update()

    return volt_x_inc, current_x_inc, y_max, volt_max

def graph(filename, screen):
    lines, point = load_graph_data(filename)

    resistivity,difference,v1,v2,v3,v4,current,time_is,date_is,volt_list,current_list = point_data(lines, point)

    if volt_list == ['']:
        message = "last point was obscured"
        plot_message(message, font, screen)
        time.sleep(2)
        return
    else:
        volt_x_inc, current_x_inc, y_max, volt_max = point_coords(volt_list,current_list)

    enter_key()

#######
#######

def main():
    ###
    """Main program starts here"""

    ###
    """Main variables"""
    photo = 1
    test_seq = "no"
    
    ##activate keyboard
    keysPressed = defaultdict(bool)

    def ScanKeyboard():
        while True:
            # Update the keysPressed state:
            evt = pygame.event.poll()
            if evt.type == pygame.MOUSEBUTTONUP:
                pos = pygame.mouse.get_pos()
            if evt.type == pygame.NOEVENT:
                break
            if evt.type == pygame.QUIT:
                pygame.quit(); sys.exit();
            elif evt.type in [pygame.KEYDOWN, pygame.KEYUP]:
                keysPressed[evt.key] = evt.type == pygame.KEYDOWN

    clear_screen(screen, width, height)

    debugging("A0: Main program start\n")

    ##Initiate relay switches
    sp = BV4111.sv3clV2_2.Connect(sys.argv[1],115200)

    # class instance for sv3 device, assume address 'a' and
    # default ack
    Devd = BV4111.bv4111(sp,'d')
    d = Devd.Discover()

    debugging("B0: Relays ready for test - Done\n")

    ##Test results setup
    test_results = []

        
    ###---###
    """Welcome screen"""

    message = "Welcome ..."
    plot_message(message, font, screen)
    time.sleep(2)

    message = "Dairsie "+version_no+": loading..."
    plot_message(message, font, screen)
    time.sleep(2)

    message = "Let's survey :-)"
    plot_message(message, font, screen)
    time.sleep(2)

    ###---###
    ###--ADD USER VARIABLE CHOICES--###

    ##"""Insriment set up"""
    ##probe_seperation = probe()


    #####
    """Enter survey name or load survey"""

    choice = ""

    while choice.upper() not in ("N","L","R","E","X","Z"):
        message = "(N)ew (L)oad (R)eview (E)xit"
        plot_message(message, font, screen)
        choice = enter_key()

        if choice.upper() in ("L"):
            message = "Load survey"
            plot_message(message, font, screen)
            time.sleep(2)
            year, month, day, h_factor, m_factor, filename, point = load_data(choice.upper())


        if choice.upper() in ("R"):
            message = "Load survey"
            plot_message(message, font, screen)
            time.sleep(2)
            year, month, day, h_factor, m_factor, filename, point = load_data(choice.upper())

            show(filename, "P")

            exp = ""
            while exp.upper() not in ("Y","N"):
                message = "export image? (y/n)"
                plot_message(message, font, screen)
                exp = enter_key()
                if exp.upper() == "Y":
                    img.save(str(filename[:-4])+"_"+str(photo)+".png")
                    message = str(filename[:-4])+"_"+str(photo)+".png"+ " saved"
                    plot_message(message, font, screen)
                    time.sleep(3)
                    photo+=1
                else:
                    pass

            choice = "q" 

        if choice.upper() in ("N"):
            message = "New survey"
            plot_message(message, font, screen)
            time.sleep(2)
            year, month, day, h_factor, m_factor, filename, point = new_setup(font, screen, "N")

        if choice.upper() in ("E","X"):
            message = "Exit"
            plot_message(message, font, screen)
            time.sleep(2)
            close()

        if choice.upper() in ("Z"):
            message = "multi test survey"
            plot_message(message, font, screen)
            time.sleep(2)
            year, month, day, h_factor, m_factor, filename, point = new_setup(font, screen, "Z")

            test_seq = "yes"
            test_length = TEST_LENGTH


    ## Take warm up readings
    choice = ""

    while choice.upper() != "Y":
        message = "probe test..."
        plot_message(message, font, screen)
        time.sleep(3)
        message = "Insert probes: Ready?(y)"

        plot_message(message, font, screen)

        choice = enter_key()
            

    message = "Warming up..."
    plot_message(message, font, screen)
                
    switch_all_off(Devd)
    time.sleep(1)
    switch_all_on(Devd)
    time.sleep(1)
    switch_all_off(Devd)

    result = process()
    assessment = review(result)

    debugging("D0: Survey set up and user input - Done\n")

    ###---TEST_DATA---###
    ##year, month, day = "2014", "Jan", "08"
    ##filename, point, h_factor, m_factor = "arez_write", 1, 0, 0

    ###---###
    survey = "active"

    while survey == "active":
        ScanKeyboard()
        
        if point >400:
            show(filename, "J")
            img.save(str(filename[:-4])+"_"+str(photo)+".png")
            time.sleep(3)
            message = str(filename[:-4])+"_"+str(photo)+".png"+ " saved"
            plot_message(message, font, screen)
            time.sleep(3)
            photo+=1
            survey = None
        else:
            pass

        if survey == None:
            pass
        else:
            if test_seq == "yes":
                if test_length > 0:
                    record = "test"
                    test_length -=1
                else:
                    record = ""
            else:
                record = ""
                
            line, position = find_line_pos(point)
            message = "Line: "+str(line)+"m Pos: "+str(position)+"m"
            plot_message(message, font, screen)
            help_message = "press 'x' for options"
            if line == 0:
                if position == 0:
                    plot_rez = False
                else:
                    plot_rez = True
            else:
                plot_rez = True

            if plot_rez:
                last_rez_val = last_rez(filename)
                message = "last: "+str(last_rez_val)+" ohm-m"
                plot_message4(message, font, screen)
            else:
                pass
                    
            plot_message3(help_message, font, screen)
            if record == "test":
                pass
            else:
                record = enter_key()

            if record.upper() == "X":
                choice = ""
                while choice.upper() not in ("L","O","R","D","J","S","X","E","P","G"):
                    message = "(O)bscured (D)elete (S)hort"
                    plot_message_up(message, font, screen)
                    message ="(P)lot (G)raph (J)pg (E)xit"
                    plot_message_down(message, font, screen)
                    help_message = "press 'R' to return"
                    plot_message3(help_message, font, screen)
                    choice = enter_key()

                    if choice.upper() == "L":
                        last(filename)

                    elif choice.upper() == "J":
                        show(filename, "J")
                        img.save(str(filename[:-4])+"_"+str(photo)+".png")
                        time.sleep(1)
                        message = str(filename[:-4])+"_"+str(photo)+".png"+ " saved"
                        plot_message(message, font, screen)
                        time.sleep(3)
                        photo+=1
                    elif choice.upper() == "R":
                        record = None

                    elif choice.upper() == "O":

                        result = [0,0,0,0,0,[],[],0]
                        assessment = 0
                        
                        write_result(year, month, day, filename, point, h_factor, m_factor, result, assessment)
                        point+=1
                        record = None

                    elif choice.upper() == "D":
                        last(filename)
                        point = delete(filename, point)

                    elif choice.upper() == "S":
                        switch_all_off(Devd)
                        time.sleep(1)
                        switch_all_on(Devd)
                        time.sleep(1)
                        switch_all_off(Devd)
                        switch_all_off(Devd)
                        time.sleep(1)
                        switch_all_on(Devd)
                        time.sleep(1)
                        switch_all_off(Devd)
                        record = None
                        break
                    elif choice.upper() in ("E","X"):
                        #:(
                        close()
                    elif choice.upper() == "P":
                        show(filename, "P")
                    elif choice.upper() == "G":
                        graph(filename, screen)

                    else:
                        pass
            else:
                try:
                    ##Main sequence
                    #print("\nTest: "+str(point))
                    result = process()
                    assessment = review(result)
                    if assessment == "" or assessment == "FAIL: Resistivity = 0" \
                       or assessment == "FAIL: Missing Data":
                        pass
                    else:
                        write_result(year, month, day, filename, point, h_factor, m_factor, result, assessment)
                        point+=1
                except:
                    message = "\nTest: "+str(point)+"FAIL: unknown error"
                    try:
                        plot_message(message, font, screen)
                        time.sleep(2)
                    except:
                        pass

    #print("end\nend")

    switch_all_off(Devd)
    sp.close()

    message = "Good bye"
    try:
        plot_message(message, font, screen)
    except:
        pass
    time.sleep(2)
    sys.exit()

if __name__ == "__main__":
    main()



Return to “Troubleshooting”