Changeset - da6947ec7d99
[Not reviewed]
default
0 2 1
matthewreed - 9 years ago 2016-08-07 18:19:07

Added cron task check to set correct state when starting up. Also added untested PID control for outputs.
3 files changed with 129 insertions and 7 deletions:
0 comments (0 inline, 0 general)
PID.py
Show inline comments
 
new file 100644
 
import time
 

	
 
class PID:
 

	
 
    def __init__(self, setpoint = 0):
 
        
 
        self.setpoint = float(setpoint)
 
        
 
        self.Kp = 0
 
        self.Ki = 0
 
        self.Kd = 0
 
        
 
        self.min_out = 0
 
        self.max_out = 1000
 
        
 
        self.Reset()
 
        
 
    def SetMin(self, min_out):
 
        self.min_out = min_out
 
        
 
    def SetMax(self, max_out):
 
        self.max_out = max_out
 
    
 
    def SetSetpoint(self, setpoint):
 
        self.setpoint = float(setpoint)
 

	
 
    def SetKp(self, Kp):
 
        self.Kp = float(Kp)
 

	
 
    def SetKi(self, Ki):
 
        self.Ki = float(Ki)
 

	
 
    def SetKd(self, Kd):
 
        self.Kd = float(Kd)
 

	
 
    def Reset(self):
 
        
 
        self.current_time = time.time()
 
        self.last_time = self.current_time
 

	
 
        self.last_error = 0
 
        
 
        self.Cp = 0
 
        self.Ci = 0
 
        self.Cd = 0
 

	
 
    def Update(self, value):
 
        
 
        print("PID input: " + str(value))
 
        
 
        error = self.setpoint - value
 
        self.current_time = time.time()
 
        dt = self.current_time - self.last_time
 
        de = error - self.last_error
 
        
 
        self.Cp = self.Kp * error
 
        self.Ci += error * dt
 
        
 
        self.Cd = 0
 
        if dt > 0:
 
            self.Cd = de/dt
 
        
 
        self.last_time = self.current_time
 
        self.last_error = error
 
        
 
        output = self.Cp + (self.Ki * self.Ci) + (self.Kd * self.Cd)
 
        if output > self.max_out:
 
            output = self.max_out
 
        if output < self.min_out:
 
            output = self.min_out
 
        
 
        print("PID output: " + str(output))
 
        return output
hydrobot.py
Show inline comments
 
import sys
 
import time
 
import _thread
 
import ast
 
import configparser
 
import datetime
 
from canard import can, messaging
 
from canard.hw import socketcan
 
from canard.hw import cantact
 
from canard.file import jsondb
 
from influxdb import InfluxDBClient
 
from influxdb import SeriesHelper
 
from apscheduler.schedulers.background import BackgroundScheduler
 
import PID
 

	
 
#TODO
 
#fix temperature offsets
 
#database time interval logging
 
#set initial state for cron timers
 

	
 
config = configparser.ConfigParser(allow_no_value = True)
 
config.read("hydrobot.conf")
 
DEBUG_CAN = config.getboolean("debug", "can")
 
DEBUG_CAN_DETAIL = config.getboolean("debug", "can_detail")
 
DEBUG_TIMER = config.getboolean("debug", "timer")
 

	
 
    
 
class MySeriesHelper(SeriesHelper):
 
    
 
    # Meta class stores time series helper configuration.
 
    class Meta:
 
        # The client should be an instance of InfluxDBClient.
 
        #client = myclient
 
        # The series name must be a string. Add dependent fields/tags in curly brackets.
 
        series_name = '{measurement}'
 
        # Defines all the fields in this time series.
 
        fields = ['value']
 
        # Defines all the tags for the series.
 
        tags = ['measurement']
 
        # Defines the number of data points to store prior to writing on the wire.
 
        bulk_size = 5
 
        # autocommit must be set to True when using bulk_size
 
        autocommit = True
 

	
 

	
 
class Database:
 
    
 
    def __init__(self):
 
        host = config.get("database", "host")
 
        port = config.get("database", "port")
 
        username = config.get("database", "username")
 
        password = config.get("database", "password")
 
        database = config.get("database", "database")
 
        self.name = config.get("system", "name")
 
        self.client = InfluxDBClient(host, port, username, password, database)
 
        MySeriesHelper.Meta.client = self.client
 
        MySeriesHelper.Meta.series_name = self.name + '.{measurement}'
 
        
 
        # To manually submit data points which are not yet written, call commit:
 
        #MySeriesHelper.commit()
 

	
 
    def log_data(self, msgdb, message):
 
        if message == msgdb.AirSense:
 
            MySeriesHelper(measurement='air_temp', value=(float)(message.Temperature.value))
 
            MySeriesHelper(measurement='air_humidity', value=(float)(message.Humidity.value))
 
            MySeriesHelper(measurement='air_pressure', value=(float)(message.Pressure.value))
 
        if message == msgdb.RelayDriveIn:
 
            MySeriesHelper(measurement='water_flow_rate', value=(float)(message.FlowRate.value))
 
            MySeriesHelper(measurement='input_1', value=(float)(message.Input1.value))
 
            MySeriesHelper(measurement='input_2', value=(float)(message.Input2.value))
 
            MySeriesHelper(measurement='input_3', value=(float)(message.Input3.value))
 
            MySeriesHelper(measurement='input_4', value=(float)(message.Input4.value))
 
        if message == msgdb.WaterSense:
 
            MySeriesHelper(measurement='water_level', value=(float)(message.PercentFull.value))
 
            MySeriesHelper(measurement='water_temp', value=(float)(message.Temperature.value))
 

	
 

	
 
class CanBus:
 
    
 
    def __init__(self, database):
 
        
 
        self.database = database
 

	
 
        self.dev = socketcan.SocketCanDev("can0")
 
        #self.dev = cantact.CantactDev("/dev/ttyACM8")
 
        #self.dev.set_bitrate(500000)
 
        
 
        parser = jsondb.JsonDbParser()
 
        self.msgdb = parser.parse('hydrobot_can.json')
 
        
 
        self.temp_msg = self.msgdb.AirSense
 
        self.relay_msg = self.msgdb.RelayDriveIn
 
        self.relay_send_msg = self.msgdb.RelayDriveOut
 
        
 
    def start(self):
 
        self.dev.start()
 
        
 
    def start_receive(self):
 
        _thread.start_new_thread(self.process_can, ())
 

	
 
    def process_can(self):
 
        while True:
 
            frame = self.dev.recv()
 
            message = self.msgdb.decode(frame)
 
            if message:
 
                if DEBUG_CAN:
 
                    print("Received CAN message! ID: " + hex(message.id))
 
                for s in message._signals.values():
 
                    if DEBUG_CAN_DETAIL:
 
                        print(s)
 
                        print(s.value)
 
                self.database.log_data(self.msgdb, message)
 
                
 
    def send_can(self):
 
        self.relay_send_msg.Nothing.value = 0
 
        if self.relay_send_msg.Output1.value == 0:
 
            self.relay_send_msg.Output1.value = 1
 
        else:
 
            self.relay_send_msg.Output1.value = 0
 
        self.relay_send_msg.Output2.value = 1
 
        self.relay_send_msg.Output3.value = 1
 
        self.relay_send_msg.Output4.value = 1
 
        if DEBUG_CAN:
 
            print("Send CAN message! ID: " + hex(self.relay_send_msg.id))
 
        if DEBUG_CAN_DETAIL:
 
            print(self.relay_send_msg)
 
        self.dev.send(self.relay_send_msg.encode())
 
        
 
    def set_output(self, module, output, state):
 
        print("Output! " + module + " " + output + " " + str(state))
 
        msg = self.msgdb.lookup_message(module)
 
        msg.lookup_signal(output).value = state
 
        self.dev.send(msg.encode())
 
        
 
        if msg.lookup_signal(output) == msg.Output1:
 
            MySeriesHelper(measurement='output_1', value=state)
 
        if msg.lookup_signal(output) == msg.Output2:
 
            MySeriesHelper(measurement='output_2', value=state)
 
        if msg.lookup_signal(output) == msg.Output3:
 
            MySeriesHelper(measurement='output_3', value=state)
 
        if msg.lookup_signal(output) == msg.Output4:
 
            MySeriesHelper(measurement='output_4', value=state)
 
        
 
        
 
class Scheduler:
 
    
 
    def __init__(self, canbus):
 
        self.canbus = canbus
 
        self.apscheduler = BackgroundScheduler()
 
        
 
    def start(self):
 
        self.apscheduler.start()
 
        
 
        for section in config.sections():
 
            if "timer" in section:
 
                items = config.items(section)
 
                for item in items:
 
                    if item[0] == 'trigger':
 
                        trigger = item[1]
 
                    if item[0] == 'module':
 
                        module = item[1]
 
                    if item[0] == 'output':
 
                        output = item[1]
 
                    if item[0] == 'on_time':
 
                        on_time = ast.literal_eval(item[1])
 
                    if item[0] == 'off_time':
 
                        off_time = ast.literal_eval(item[1])
 
                    if item[0] == 'on_duration':
 
                        on_duration = ast.literal_eval(item[1])
 
                    if item[0] == 'off_duration':
 
                        off_duration = ast.literal_eval(item[1])
 
                if trigger == 'cron':
 
                    self.apscheduler.add_job(self.canbus.set_output, trigger, [module, output, 1], day = on_time[0], day_of_week = on_time[1], hour = on_time[2], minute = on_time[3], second = on_time[4])
 
                    self.apscheduler.add_job(self.canbus.set_output, trigger, [module, output, 0], day = off_time[0], day_of_week = off_time[1], hour = off_time[2], minute = off_time[3], second = off_time[4])
 
                    on_job = self.apscheduler.add_job(self.canbus.set_output, trigger, [module, output, 1], day = on_time[0], day_of_week = on_time[1], hour = on_time[2], minute = on_time[3], second = on_time[4])
 
                    off_job = self.apscheduler.add_job(self.canbus.set_output, trigger, [module, output, 0], day = off_time[0], day_of_week = off_time[1], hour = off_time[2], minute = off_time[3], second = off_time[4])
 
                                        
 
                    #evalute the current state of the cron trigger and set output on if needed
 
                    if on_job.next_run_time > off_job.next_run_time:
 
                        self.canbus.set_output(module, output, 1)
 
                    
 
                if trigger == 'interval':
 
                    self.apscheduler.add_job(self.interval_off, trigger, [module, output, section + "_off", section + "_on", on_duration], id = section + "_off", weeks = off_duration[0], days = off_duration[1], hours = off_duration[2], minutes = off_duration[3], seconds = off_duration[4])
 
                    timer = self.apscheduler.add_job(self.interval_on, trigger, [module, output, section + "_off", section + "_on", off_duration], id = section + "_on", weeks = on_duration[0], days = on_duration[1], hours = on_duration[2], minutes = on_duration[3], seconds = on_duration[4])
 
                    timer.pause()
 
        
 
                    
 
            if "pid" in section:
 
                items = config.items(section)
 
                for item in items:
 
                    if item[0] == 'module_out':
 
                        module_out = item[1]
 
                    if item[0] == 'output':
 
                        signal_out = item[1]
 
                    if item[0] == 'module_in':
 
                        module_in = item[1]
 
                    if item[0] == 'input':
 
                        signal_in = item[1]
 
                    if item[0] == 'kp':
 
                        kp = item[1]
 
                    if item[0] == 'ki':
 
                        ki = item[1]
 
                    if item[0] == 'kd':
 
                        kd = item[1]
 
                    if item[0] == 'rate':
 
                        rate = item[1]
 
                    if item[0] == 'setpoint':
 
                        setpoint = item[1]
 
                
 
                pid = PID.PID(float(setpoint))
 
                pid.SetKp(kp)
 
                pid.SetKi(ki)
 
                pid.SetKd(kd)
 
                pid.Reset()
 
                self.apscheduler.add_job(self.process_PID, "interval", [pid, module_out, signal_out, module_in, signal_in], seconds = int(rate))
 
                
 
                    
 
    def interval_off(self, module, output, timer_off, timer_on, on_duration):
 
        self.canbus.set_output(module, output, 1)
 
        self.apscheduler.get_job(timer_on).reschedule("interval", weeks = on_duration[0], days = on_duration[1], hours = on_duration[2], minutes = on_duration[3], seconds = on_duration[4])
 
        self.apscheduler.get_job(timer_on).resume()
 
        self.apscheduler.get_job(timer_off).pause()
 
        if DEBUG_TIMER:
 
            print("Turning " + timer_on + "! " + str(datetime.datetime.now().time()))
 
        
 
    def interval_on(self, module, output, timer_off, timer_on, off_duration):
 
        self.canbus.set_output(module, output, 0)
 
        self.apscheduler.get_job(timer_off).reschedule("interval", weeks = off_duration[0], days = off_duration[1], hours = off_duration[2], minutes = off_duration[3], seconds = off_duration[4])
 
        self.apscheduler.get_job(timer_off).resume()
 
        self.apscheduler.get_job(timer_on).pause()
 
        if DEBUG_TIMER:
 
            print("Turning " + timer_off + "! " + str(datetime.datetime.now().time()))
 
    
 
            
 
    def process_PID(self, pid, module_out, signal_out, module_in, signal_in):
 
        msg = self.canbus.msgdb.lookup_message(module_in)
 
        input_reading = msg.lookup_signal(signal_in).value
 
        input_reading = 19
 
        pid_out = pid.Update(input_reading)
 
        if pid_out > 0:
 
            self.canbus.set_output(module_out, signal_out, 1)
 
            run_time = datetime.datetime.now() + datetime.timedelta(milliseconds=pid_out)
 
            self.apscheduler.add_job(self.canbus.set_output, "date", run_date=run_time, args=[module_out, signal_out, 0])
 
    
 
def func():
 
    print(1)
 
    
 

	
 
def main():
 
    
 
    database = Database()
 
    
 
    canbus = CanBus(database)
 
    canbus.start()
 
    canbus.start_receive()
 
    
 
    scheduler = Scheduler(canbus)
 
    scheduler.start()
 

	
 
    while True:
 
        
 
        time.sleep(1)
 
        canbus.dev.send(can.Frame(0x7FF, 8, [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]))
 
        time.sleep(0.001)
 
        
 

	
 
if __name__ == "__main__":
 
    main()
hydrobot_can.json
Show inline comments
 

	
 
{
 
    "messages": [
 
        {
 
        "name": "AirSense",
 
        "id": "0x202",
 
        "signals": { "0": {"name": "Nothing", "bit_length": 16, "factor": 1, "offset": 0, "unit": ""},
 
                    "16": {"name": "Temperature", "bit_length": 16, "factor": 0.1, "offset": 40, "unit": "C"},
 
                    "32": {"name": "Humidity", "bit_length": 16, "factor": 0.1, "offset": 0, "unit": "%RH"},
 
                    "48": {"name": "Pressure", "bit_length": 16, "factor": 0.1, "offset": 0, "unit": "hPa"}
 
                   }
 
        },
 
        {
 
        "name": "RelayDriveOut",
 
        "id": "0x203",
 
        "signals": { "0": {"name": "Nothing", "bit_length": 32, "factor": 1, "offset": 0, "unit": ""},
 
                    "32": {"name": "Output1", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"},
 
                    "40": {"name": "Output2", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"},
 
                    "48": {"name": "Output3", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"},
 
                    "56": {"name": "Output4", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"}
 
                   }
 
        },
 
        {
 
        "name": "RelayDriveIn",
 
        "id": "0x204",
 
        "signals": { "0": {"name": "FlowRate", "bit_length": 16, "factor": 0.133, "offset": 0, "unit": "Hz"},
 
                    "16": {"name": "Nothing", "bit_length": 16, "factor": 1, "offset": 0, "unit": ""},
 
                    "32": {"name": "Input1", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"},
 
                    "40": {"name": "Input2", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"},
 
                    "48": {"name": "Input3", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"},
 
                    "56": {"name": "Input4", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"}
 
                   }
 
        },
 
        {
 
        "name": "Stuff",
 
        "id": "0x205",
 
        "signals": { "0": {"name": "Nothing", "bit_length": 32, "factor": 1, "offset": 0, "unit": ""},
 
                    "32": {"name": "Input1", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"},
 
                    "40": {"name": "Input2", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"},
 
                    "48": {"name": "Input3", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"},
 
                    "56": {"name": "Input4", "bit_length": 8, "factor": 1, "offset": 0, "unit": "bool"}
 
                   }
 
        },
 
        {
 
        "name": "WaterSense",
 
        "id": "0x206",
 
        "signals": { "0": {"name": "Temperature", "bit_length": 8, "factor": 0.5, "offset": 40, "unit": "C"},
 
                    "8": {"name": "Nothing", "bit_length": 16, "factor": 1, "offset": 0, "unit": ""},
 
                    "16": {"name": "PercentFull", "bit_length": 8, "factor": 1, "offset": 0, "unit": "%"}
 
                    "32": {"name": "PercentFull", "bit_length": 8, "factor": 1, "offset": 0, "unit": "%"}
 
                     
 
                   }
 
        }
 

	
 
    ]
 
}
0 comments (0 inline, 0 general)