import logging.handlers import serial import json import sys import datetime import time import logging import os import persistqueue from tendo import singleton import logHandler logHandler.run("switch_sensors_qm") def run_cmd(cmd): try_cmd = True try_cnt = 0 while try_cmd and try_cnt < 2: port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=3.0) try: ser = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=3.0) rcv = ser.read(300) port.close() port.open() port.write(str.encode(cmd["qreq"])) except Exception as e: logging.error( "Unable to open serial port to read command status: " + str(e)) logging.info("Request: " + str(cmd["qreq"])) count = 0
from crate import client import sys sys.path.insert(1, '/home/pi/Lab3AgritechCron/') import dbHandler import logging import logHandler logHandler.run("access") def get_key(id): query = "select key from config where id ='{}';".format(id) logging.info(query) try: result = dbHandler.dbFetchOne(query) return result[0] except Exception as e: logging.info("Error: " + e) def get_name(id): query = "select name from config where id ='{}';".format(id) logging.info(query) try: result = dbHandler.dbFetchOne(query) return result[0] except Exception as e: logging.info("Error: " + e)
import logging import sys import json import time import datetime ts = datetime.datetime.now().isoformat() import history import os sys.path.insert(1, '/home/pi/Lab3AgritechCron/') import logHandler logHandler.run("cron_db_irr_update_set") if __name__ == '__main__': logging.info("Hello") try: f = open(os.path.join('/home/pi/Lab3AgritechCron/Lab4/migr/', "irrSet.json"), "r") json_dict = json.load(f) logging.info(json_dict) field_id = 101 max_sprinkle_dur = json_dict['max_sprinkle_dur'] offset_bef_sprinkle = json_dict['offset_bef_sprinkle'] max_wind_speed = json_dict['max_wind_speed'] humid = json_dict['humid'] skip_sprinkle_from = json_dict['skip_sprinkle_from'] skip_sprinkle_to = json_dict['skip_sprinkle_to'] last_updated = ts setting_id = json_dict['setting_id'] history.update_irr_set(max_sprinkle_dur, offset_bef_sprinkle, max_wind_speed, humid,skip_sprinkle_from,skip_sprinkle_to,last_updated, setting_id)
import os import json from datetime import datetime from azure.cosmosdb.table.tableservice import TableService import access import logging import sys sys.path.insert(1, '/home/pi/Lab3AgritechCron/') import logHandler logHandler.run("azure_ml_sensors") account_name = access.get_name('1') account_key = access.get_key('1') table_service = TableService(account_name, account_key) table_name = 'Sensors' def run(): for file in os.listdir("/home/pi/crate-4.0.6/data/az"): if file.startswith("sensors"): filename = os.path.join("/home/pi/crate-4.0.6/data/az", file) with open(filename, 'r') as f: for line in f: se = json.loads(line) exist_flag = 0 se['PartitionKey'] = table_name se['RowKey'] = str(se["macadd"]) try: entities = table_service.query_entities( table_name, filter="PartitionKey eq 'Sensors'",
import dbHandler import logging import logHandler import datetime logHandler.run("raise_alert") def GetAlertMsg(container_name, avetemp, avehumid, warning_value, critical_value, alert_type, warning_sent, critical_sent): try: if alert_type == 'lowHumidity': if avehumid <= critical_value and not critical_sent: alarm_type, direction, measure_type, val, critical_sent, warning_sent = 'critical', 'below', 'Humidity', critical_value, True, warning_sent elif avehumid <= warning_value and not warning_sent: alarm_type, direction, measure_type, val, critical_sent, warning_sent = 'warning', 'below', 'Humidity', warning_value, critical_sent, True elif alert_type == 'lowTemperature' and critical_sent: if avetemp <= critical_value and not warning_sent: alarm_type, direction, measure_type, val, critical_sent, warning_sent = 'critical', 'below', 'Temperature', critical_value, True, warning_sent elif avetemp <= warning_value and not warning_sent: alarm_type, direction, measure_type, val, critical_sent, warning_sent = 'warning', 'below', 'Temperature', warning_value, critical_sent, True elif alert_type == 'highTemperature': if avetemp >= critical_value and not critical_sent: alarm_type, direction, measure_type, val, critical_sent, warning_sent = 'critical', 'above', 'Temperature', critical_value, True, warning_sent elif avetemp >= warning_value and not warning_sent: alarm_type, direction, measure_type, val, critical_sent, warning_sent = 'warning', 'above', 'Temperature', warning_value, critical_sent, True elif alert_type == 'highHumidity': if avehumid >= critical_value and not critical_sent: alarm_type, direction, measure_type, val, critical_sent, warning_sent = 'critical', 'above', 'Humidity', critical_value, True, warning_sent elif avehumid >= warning_value and not warning_sent: alarm_type, direction, measure_type, val, critical_sent, warning_sent = 'warning', 'above', 'Humidity', warning_value, critical_sent, True return alarm_type, direction, measure_type, val, critical_sent, warning_sent except Exception as e:
import os import json from datetime import datetime from azure.cosmosdb.table.tableservice import TableService import access import logging import sys sys.path.insert(1, '/home/pi/Lab3AgritechCron/') import logHandler logHandler.run("azure_ml_faucets") account_name = access.get_name('1') account_key = access.get_key('1') table_service = TableService(account_name, account_key) table_name = 'Faucets' def run(): for file in os.listdir("/home/pi/crate-4.0.6/data/az"): if file.startswith("faucets"): filename = os.path.join("/home/pi/crate-4.0.6/data/az", file) with open(filename, 'r') as f: for line in f: fc = json.loads(line) exist_flag = 0 fc['PartitionKey'] = table_name fc['RowKey'] = str(fc["mac_id"]) fc['time'] = datetime.fromtimestamp(fc["time"] // 1000) try: entities = table_service.query_entities( table_name,
import os import json from datetime import datetime from azure.cosmosdb.table.tableservice import TableService import access import logging import sys sys.path.insert(1, '/home/pi/Lab3AgritechCron/') import logHandler logHandler.run("azure_ml_settings") account_name = access.get_name('1') account_key = access.get_key('1') table_service = TableService(account_name, account_key) table_name = 'CurrentConstraints' def run(): for file in os.listdir("/home/pi/crate-4.0.6/data/az"): if file.startswith("irr_set_cust"): filename = os.path.join("/home/pi/crate-4.0.6/data/az", file) with open(filename, 'r') as f: for line in f: cc = json.loads(line) exist_flag = 0 cc['PartitionKey'] = "CC" cc['RowKey'] = str(cc["field_id"]) cc['last_updated'] = datetime.fromtimestamp( cc["last_updated"] // 1000) try: entities = table_service.query_entities(
import logging import json import time import sys import history sys.path.insert(1, '/home/pi/Lab3AgritechCron/') import logHandler logHandler.run("cron_db_irr_update_history") if __name__ == '__main__': abc = history.get_max_ts_irr_hist() xyz = history.get_max_ts_irr(1) logging.info("Inside Update History" + " abc: " + str(abc) + " xyz: " + str(xyz)) if xyz > abc: logging.info("condition met !!!") history.record()
import os import json from datetime import datetime from azure.cosmosdb.table.tableservice import TableService import access import logging import sys sys.path.insert(1, '/home/pi/Lab3AgritechCron/') import logHandler logHandler.run("azure_ml_soil_data") account_name = access.get_name('1') account_key = access.get_key('1') table_service = TableService(account_name, account_key) table_name = 'SoilData' def run(): for file in os.listdir("/home/pi/crate-4.0.6/data/az"): if file.startswith("soil"): filename = os.path.join("/home/pi/crate-4.0.6/data/az", file) with open(filename, 'r') as f: for line in f: sd = json.loads(line) exist_flag = 0 sd['PartitionKey'] = table_name sd['RowKey'] = sd["mac_add"] + str(sd["time"]) sd['time'] = datetime.fromtimestamp(sd["time"] // 1000) try: entities = table_service.query_entities( table_name,
import logging import json import time import datetime import os import sys ts = datetime.datetime.now().isoformat() sys.path.insert(1, '/home/pi/Lab3AgritechCron/') import logHandler logHandler.run("db_irr_set_hist") import dbHandler def get_irr_set_comn(): query = "select setting_id, max_sprinkle_dur, offset_bef_sprinkle, max_wind_speed, humid,skip_sprinkle_from,skip_sprinkle_to,last_updated from irr_set_comn;" logging.info(query) try: result = dbHandler.dbFetchOne(query) return result[0], result[1], result[2], result[3], result[4], result[ 5], result[6], result[7] except Exception as e: logging.info("Error: " + e) def get_irr_set_cust(field_id): query = "select setting_id, max_sprinkle_dur, offset_bef_sprinkle, max_wind_speed, humid,skip_sprinkle_from,skip_sprinkle_to,last_updated from irr_set_cust where field_id ='{}';".format( field_id) logging.info(query) try: result = dbHandler.dbFetchOne(query) return result[0], result[1], result[2], result[3], result[4], result[
from crate import client import logging import logHandler logHandler.run("db_handler") def dbFetchOne(query): connection = client.connect("http://localhost:4200", username="******") cursor = connection.cursor() cursor.execute(query) result = cursor.fetchone() cursor.close() connection.close() return(result) def dbFetchAll(query): connection = client.connect("http://localhost:4200", username="******") cursor = connection.cursor() cursor.execute(query) result = cursor.fetchall() cursor.close() connection.close() return(result) def dbAlter(query): connection = client.connect("http://localhost:4200", username="******") cursor = connection.cursor() cursor.execute(query) cursor.close() connection.close()
#!/usr/bin/env python3 # disp.py - read from Fine Offset RS495 weather station. # Take RS485 via USB message from a Fine Offset WH2950 and interpret. import serial import binascii from wdata import RawWeatherData, wdata import logging import datetime import sys sys.path.insert(1, '/home/pi/Lab3AgritechCron/') import logHandler logHandler.run("read_lws") import dbHandler # For testing we can either use an actual raw format message embedded here in the code, or read from the USB input. def insert_lws(id, time, rawdata, temperature, humidity, wind_direction, wind_speed, gust_speed, rainfall, uv, light): query = "INSERT INTO lws(id,time,rawdata,temperature,humidity,wind_direction,wind_speed,gust_speed,rainfall,uv,light) VALUES ('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}')".format( id, time, rawdata, temperature, humidity, wind_direction, wind_speed, gust_speed, rainfall, uv, light) logging.info(query) try: dbHandler.dbAlter(query) except Exception as e: logging.info("Error: " + e) def main():
import datetime import dbHandler import json import time import logging import logHandler logHandler.run("fake_data") sensorList = ['000000001', '000000002', '000000003'] sensorTemp = 29 sensorHumid = 70 def insertdb(data): try: value = json.loads(data) dbHandler.InsertDB('TH_DATA', **value) except Exception as e: logging.info("Database Insertion is Fail:" + str(e)) ListOfContainer = dbHandler.GetListContainer() for i in range(5): CURRENTDT = str(datetime.datetime.now()) data = { "mac_add": "outdoor", "time": CURRENTDT, "temperature": "28", "humidity": "60"
import os import sys import dbHandler import time import json import requests import datetime from datetime import timedelta from multiprocessing import Process import logging import logHandler import switchSensors logHandler.run("brain") switch_server1_ip = "192.168.1.103" switch_server2_ip = "192.168.1.104" wechat_url = "54.255.187.114" user_id = ["ok99-wWEUEanEXFDBjxsd1vH7Rvo", "ok99-wev6t-aZRaAHffRZS1tAP0g"] def sendhttp_request(sensor_id, status, system): try: switchSensors.action(system, "2", status) time.sleep(10) switchSensors.action(system, "2", status) logging.info("{} system has been switched {}".format(system, status)) except Exception as e: logging.error("Switch is not Working. ERROR: " + str(e)) def sendhttp_request2(sensor_id, status, system):
import datetime import dbHandler import time import timeConvert import logging import logHandler import fmtLocal logHandler.run("sensor_status") def check(): timestamp_n = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') logging.info(timestamp_n) mac_list = dbHandler.GetMacAll() logging.info(mac_list) delta = 0 for mac in mac_list: mac = fmtLocal.remSqBQ(str(mac)) logging.info("MAC Address: " + str(mac)) latest_ts = dbHandler.GetSensorTsLatest(mac) delta = timeConvert.getDelta(ts_1=latest_ts, ts_2=timestamp_n, dt="min") delta = round(delta, 1) logging.info(str(delta) + " Min") if delta > 30: dbHandler.UpdateSensor(mac, "deactivate") elif delta < 30: dbHandler.UpdateSensor(mac, "activate") logging.info("Last updated sensor ts: " + str(latest_ts))