def thermostat_refresh_status(payloadstr, topic, message): # imports the status script for use import status # publishes the current status to the ballomare/thermostat/status topic status.publishMQTT(status.getStatus(), "ballomare/thermostat/status") print('Status published.')
def do_GET(self): if not self.checkAuth(): return cmd = False fileName = '/home/pi/api/html' + self.path if self.path == '/': fileName = fileName + '/index.html' if os.path.isfile(fileName): return self.sendFile(fileName) if self.path.startswith('/lights/'): if self.path.startswith('status', 8): return self.json(200, getStatus()) elif self.path.startswith('on', 8): cmd = '/home/pi/bin/lights_on' elif self.path.startswith('off', 8): cmd = '/home/pi/bin/lights_off' if self.path.startswith('/controller/'): if self.path.startswith('cylon', 12): cmd = '/home/pi/bin/pattern cylon' elif self.path.startswith('dance', 12): cmd = '/home/pi/bin/pattern dance' elif self.path.startswith('flash', 12): cmd = '/home/pi/bin/pattern flash' elif self.path.startswith('random_pattern', 12): cmd = '/home/pi/bin/pattern random_pattern' if self.path.startswith('/show/'): if self.path.startswith('start', 6): cmd = '/home/pi/bin/start_lights' elif self.path.startswith('stop', 6): cmd = '/home/pi/bin/stop_lights' elif self.path.startswith('enable', 6): cmd = '/home/pi/bin/enable_show' elif self.path.startswith('disable', 6): cmd = '/home/pi/bin/disable_show' if cmd: writeLog(self.client_address[0], cmd) if re.search('/home/pi/bin/', cmd): os.system('/home/pi/bin/stop_controller background') os.system(cmd) data = { 'ip': self.client_address[0], 'when': format(strftime("%Y-%m-%d %H:%M:%S", gmtime())), 'command': cmd } return self.json(200, data) self.send_response(404) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write('404 Not Found') return
import checknet import status import socket import subprocess import time from firebase import db import os.path import json scriptpath = os.path.dirname(__file__) filename = os.path.join(scriptpath, 'config') with open (filename,"r") as file: uid=file.read() while True : if checknet.is_connected()and uid is not '': print("==========Online===========") tempStatus=status.getStatus() myMac=list(tempStatus.keys())[0] print(myMac) try: command=db.child("users").child(uid).child("status").child(myMac).child("command").get().val() shutdown=db.child("users").child(uid).child("status").child(myMac).child("shutdown").get().val() print(command," ",shutdown) if command is not None and command!="-": subprocess.getoutput(command) #print(subprocess.getoutput(command)) result=subprocess.getoutput(command) db.child("users").child(uid).child("status").child(myMac).child("result_command").set(result) print("command : ", command) if shutdown is not None and shutdown==1: db.child("users").child(uid).child("status").child(myMac).child("shutdown").set(0) subprocess.getoutput('sudo shutdown -h now')
from subprocess import call import uuid #from status import Status import status as stat import shutil import glob #Expect normal folder structure! # -sat # -backend # -bin # Detect SAT HOME DIR SAT_HOME = os.environ.get('SAT_HOME') BIN_PATH = os.path.realpath(SAT_HOME + '/bin/') status = stat.getStatus() # 1.st step to process file is to unpack file def process_trace(trace_id): trace_file = status.get_file_by_id(trace_id) status.update_status(trace_id, status.UNZIP) devnull = open('/dev/null', 'w') upload_traces_path = os.path.dirname(os.path.abspath(trace_file)) tmp_process_path = upload_traces_path + "/" + str(uuid.uuid4()) os.makedirs(tmp_process_path) ret_val = call("cd " + tmp_process_path + "; tar xvzf " + trace_file, shell=True, stdout=devnull) devnull.close() if not ret_val == 0:
from dronekit import connect from status import getStatus from readfile import readFileParameters print '<<<<< UAV-S2DK >>>>' print '====Read File Parameters====' parameters = readFileParameters() param = parameters.split(' ') HOST_MAVPROXY = param[0] HOST_HTTP = param[1] PORT_MAVPROXY = param[2] PORT_HTTP = param[3] print 'host_mavp: %s port_mavp: %s host_http: %s port_http: %s' % ( HOST_MAVPROXY, PORT_MAVPROXY, HOST_HTTP, PORT_HTTP) conn = '%s:%s' % (HOST_MAVPROXY, PORT_MAVPROXY) print '========Connect Drone=======' vehicle = connect(conn, wait_ready=True) print '=========Get Status=========' getStatus(vehicle) print '=========Run Server=========' runServer(vehicle, HOST_HTTP, int(PORT_HTTP)) print '======Close Connection======' vehicle.close()
columns = "all" if columns not in ("all", "branches"): usage() branches = (columns == "branches") for i in range(4,len(sys.argv)): if (sys.argv[i] == "calls"): perf_db_export_calls = True elif (sys.argv[i] == "callchains"): perf_db_export_callchains = True else: usage() conf = status.getStatus() dbname = conf.getDbConfig('dbname') dbuser = conf.getDbConfig('user') dbpass = conf.getDbConfig('password') dbgivenname = sys.argv[1] def do_query(q, s): if (q.exec_(s)): return raise Exception("Query failed: " + q.lastError().text()) print datetime.datetime.today(), "Creating database schema..." db = QSqlDatabase.addDatabase('QPSQL') query = QSqlQuery(db) db.setDatabaseName(dbname)
def hello(websocket, path): yield from websocket.send(json.dumps(status.getStatus())) name = yield from websocket.recv() print("< {}".format(name))
def configform(troop, scout, pin): # Prepare scout object for Pinoccio API query account = pynoccio.Account() account.token = app.config['SECURITY_TOKEN'] account.load_troops() account.troop(int(troop)).load_scouts() report_scout = account.troop(int(troop)).scout(int(scout)) # If Submit button was clicked if request.method == 'POST' and request.form.get('formbtn') == 'save': # Check DB for pin's previous device, if any current_device = models.Device.query.filter_by(troop=troop, scout=scout, pin=pin).first() current_motor = models.Motor.query.filter_by(troop=troop, scout=scout, pin=pin).first() # If the user chose to add an input device if request.form.get('deviceClass') == 'inputs': # Get current state of new device if pin in ANALOG_PINS: pinATemp = pynoccio.PinCmd(report_scout).report.analog.reply while isinstance(pinATemp, str): pinATemp = pynoccio.PinCmd(report_scout).report.analog.reply pinAStates = pinATemp.state digital = False elif pin in DIGITAL_PINS: pinDTemp = pynoccio.PinCmd(report_scout).report.digital.reply while isinstance(pinDTemp, str): pinDTemp = pynoccio.PinCmd(report_scout).report.digital.reply pinDStates = pinDTemp.state digital = True else: print "ERROR: Invalid pin designation" output_settings = request.form.get('triggerDevice') threshold_values = request.form.get('threshold').split("-") if threshold_values != ['']: threshold_values = [int(element) for element in threshold_values] else: threshold_values = [250, 750] ref_motor = [] if (output_settings != 'text' and output_settings != 'email' and output_settings != 'tweet'): ref_motor = [models.Motor.query.get(int(output_settings))] pynoccio.PinCmd(report_scout).makeinput(pin) new_device = models.Device( name = request.form.get('deviceName') or 'Unnamed Sensor', troop = troop, scout = scout, type = request.form.get('subset'), mode = 2, pin = pin, digital = digital, dtrigger = request.form.get('dtrigger') or 'HIGH', atriggerupper = threshold_values[1] or 1023, atriggerlower = threshold_values[0] or 0, pollinginterval = request.form.get('pollingInterval') or 15, text = True if output_settings == 'text' else False, email = True if output_settings == 'email' else False, tweet = True if output_settings == 'tweet' else False, motor = ref_motor ) print new_device.name print new_device.scout print new_device.troop print new_device.type print new_device.mode print new_device.pin print new_device.digital print new_device.dtrigger print new_device.atriggerupper print new_device.atriggerlower print new_device.pollinginterval print new_device.text print new_device.email print new_device.tweet print new_device.motor db.session.add(new_device) # If the user chose to add an output motor elif request.form.get('deviceClass') == 'outputs': # Get current state of new motor pinDTemp = pynoccio.PinCmd(report_scout).report.digital.reply while isinstance(pinDTemp, str): pinDTemp = pynoccio.PinCmd(report_scout).report.digital.reply pinDStates = pinDTemp.state pynoccio.PinCmd(report_scout).makeoutput(pin) new_motor = models.Motor( name = request.form.get('deviceName') or 'Unnamed Motor', scout = scout, troop = troop, type = request.form.get('subset'), mode = 1, pin = pin, trig_time = request.form.get('trigTime') or 0, untrig_time = request.form.get('untrigTime') or 0, delay = request.form.get('delay') or 0, state = 0, device_id = None ) print new_motor.name print new_motor.scout print new_motor.troop print new_motor.type print new_motor.mode print new_motor.pin print new_motor.trig_time print new_motor.untrig_time print new_motor.delay print new_motor.state print new_motor.device_id db.session.add(new_motor) else: print "ERROR: Device not set to input or output" if current_device: db.session.delete(current_device) if current_motor: db.session.delete(current_motor) db.session.commit() return redirect(url_for('config')) # If Delete button was clicked elif request.method == 'POST' and request.form.get('formbtn') == 'delete': current_device = models.Device.query.filter_by(troop=troop, scout=scout, pin=pin).first() current_motor = models.Motor.query.filter_by(troop=troop, scout=scout, pin=pin).first() pynoccio.PinCmd(report_scout).disable(pin) if current_device: db.session.delete(current_device) if current_motor: db.session.delete(current_motor) db.session.commit() return redirect(url_for('config')) else: # Get all motors to populate dropdown motorSet = models.Motor.query.all(); motors = [] for motor in motorSet: motors.append( {motor.name : motor.id} ) motors = sorted(motors) currentConfig = status.getStatus(troop, scout, pin) pinloc = { 'troop':account.troop(int(troop)).name, 'scout':report_scout.name, 'pin':pin } pindes = list(pin)[0] return render_template('configform.html', title = 'Device Configuration' , motors = motors, currentConfig = currentConfig, pinloc = pinloc, pindes = pindes)
def main_loop(): #cam.mode=cam.mode.automatic #----------------dict to hold vesseldata from streams vInfo = {} #----------------streams body = vessel.orbit.body refFrame = body.reference_frame flight = vessel.flight(refFrame) flightS = vessel.flight(vessel.surface_reference_frame) ap = vessel.auto_pilot dPitch = conn.add_stream(getattr, ap, 'pitch_error') dHead = conn.add_stream(getattr, ap, 'heading_error') angVelVec = conn.add_stream(vessel.angular_velocity, vessel.orbital_reference_frame) hSpeed = conn.add_stream(getattr, flight, 'horizontal_speed') pitch = conn.add_stream(getattr, flightS, 'pitch') alt = conn.add_stream(getattr, flight, 'surface_altitude') v_vert = conn.add_stream(getattr, flight, 'vertical_speed') mass = conn.add_stream(getattr, vessel, 'mass') maxThrust = conn.add_stream(getattr, vessel, 'available_thrust') sigContact = conn.add_stream(getattr, vessel.comms, 'can_communicate') sigStr = conn.add_stream(getattr, vessel.comms, 'signal_strength') g = conn.add_stream(getattr, body, 'surface_gravity') sit = conn.add_stream(getattr, vessel, 'situation') #----------------Vars ctrl = [0,0,1] oldCtrl = [0,0,1] connected = False mainParts = listMainParts(vessel) #some actions only in parts not connected by docking ports updateTime = time.perf_counter() sendDataTime = updateTime initTime = time.perf_counter() engineCheckTime = time.perf_counter() flameOut = False autoDescentStage = 0 overflow = 1 # Serial overflow from arduino abortPressed = False time.sleep(2) #cam = conn.space_center.camera try: while vessel == conn.space_center.active_vessel: now = time.perf_counter() try: vInfo['dPitch'] = dPitch() except: vInfo['dPitch'] = 0 try: vInfo['dHead'] = dHead() except: vInfo['dHead'] = 0 vInfo['angVelVec'] =angVelVec() vInfo['hSpeed'] = hSpeed() vInfo['pitch'] = pitch() vInfo['alt'] = alt() vInfo['v_vert'] = v_vert() vInfo['mass'] = mass() vInfo['mxThr'] = maxThrust() vInfo['sig'] = sigContact() vInfo['sigStr'] = sigStr() vInfo['g'] = g() vInfo['sit'] = sit() if vInfo['mass'] != 0: vInfo['a'] = vInfo['mxThr']/vInfo['mass'] else: vInfo['a'] = 0 if (now - engineCheckTime > 1): #check for flameout every second.engines engineCheckTime = now engineList = vessel.parts.engines flameOut = False for Engine in engineList: if not (Engine.has_fuel): flameOut = True print('Flameout') #for i in range(3): # oldCtrl[i] = ctrl[i] if arduino.in_waiting > 0: if (now - updateTime) > 0.01 or overflow == 1: tmpCtrl = serialReceive(arduino, conn) updateTime = time.perf_counter() if (tmpCtrl[3]& 0b00000111) == 0: # we have success, run commands for i in range(2): oldCtrl[i] = ctrl[i] ctrl[i] = tmpCtrl[i] if ((ctrl[0] != oldCtrl[0]) or (ctrl[1] != oldCtrl[1]) and now-initTime > 1 ): #now - inittime: delay after connection to ensure KSP ready actions(ctrl,oldCtrl,vessel, mainParts,conn) #camera = (ctrl[0]&0b11100000)>>5 #camcontrol(camera, cam) if ((ctrl[1] & 0b00010000) == 0b10000): # Execute autoDescent routine if autoDescentStage == 0: autoDescentStage = 1 if ((ctrl[1] & 0b00100000) != (oldCtrl[1] & 0b00100000) and (ctrl[1] & 0b00100000) == 0b00100000): # Abort if autoDescentStage != 0 and ((ctrl[1] & 0b00100000) == 0b00100000): autoDescentStage = 0 print('fire') ap.disengage() vessel.control.throttle = 0 else: vessel.control.abort = bool((ctrl[1] & 0b00100000)) if bool((ctrl[1] & 0b00100000)): print('abort') else: for i in range(3): # reset ctrl #ctrl[i] = oldCtrl[i] print('fire') if (now - updateTime) > 1: #more than one second since last received comms from arduino updateTime = time.perf_counter() conn.ui.message("Arduino timeout", position = conn.ui.MessagePosition.top_left) #arduino.write(0b01010101) if autoDescentStage > 0: ap.engage() autoDescentStage = autoDescent(vessel, vInfo, ap, autoDescentStage) else: ap.disengage() if (now - sendDataTime) > 0.4: #send data to arduino status= getStatus(vInfo) # Compute status bytes from streams status[2]=getSOIbodynum(vessel) sendDataTime = time.perf_counter() status[1]=(status[1] | int(flameOut)) status[1]=(status[1] | int(overflow) << 1 ) buff = struct.pack('<BhBBB',85,status[0],status[1],status[2],170) arduino.write(buff) except krpc.error.RPCError: print("Error") else: print("Change of vessel")
def statusOption(): status.getStatus()