def doPost(self, request): """ handle POST request for Pi system resources request: the RequestContext data object must return a Flask.Response object """ bodyJson = request.json response = [] httpStatusCode = 200 for key, value in bodyJson.items(): try: timePrint('POST system command: %s=%s' %(key, value)) # use tempfile for output tempFile = tempfile.NamedTemporaryFile(prefix='pisys-') tempFileName = tempFile.name tempFile.close() command = '%s > %s 2>&1 \n' %(value, tempFileName) os.system(command) f = open(tempFileName, "r") text = f.read() f.close() os.remove(tempFileName) itemStatusCode = 200 itemResponse = { key: value, 'result': text } except: itemStatusCode = 400 itemResponse = { KeyResponse: 'InvalidCommand', KeyPropertyValue: value } if itemStatusCode != 200: httpStatusCode = itemStatusCode response.append(itemResponse) return makeJsonResponse(httpStatusCode, response)
def doPost(self, request): """ handle POST request for Pi GPIO request: the RequestContext data object must return a Flask.Response object """ bodyJson = request.json # todo: handle json with list of pin objects response = [] httpStatusCode = 200 component = request.paths[1] for key, value in bodyJson.items(): # case 1: url="/gpio" body="7/value": 0 // OK # case 2: url=/gpio/7 body="value": 0 // OK # case 3: url=/gpio/7 body="7/value": 0 // invalid for now # case 4: url=/gpio/7 body="8/value": 0 // invalid # prepend the component to form full path such as 7/value fullPath = component + '/' + key parts = splitAndTrim(fullPath, '/') try: pin = int(parts[0]) intValue = int(value) property = '' if len(parts) > 1: property = parts[1] pinResponse = piGpio.set(pin, property, intValue) pinStatusCode = pinResponse.pop(KeyStatusCode, 400) except: pinStatusCode = 400 pinResponse = { KeyResponse: 'InvalidPinOrValue', KeyGpioPropertyPin: pin, KeyPropertyValue: value } if pinStatusCode != 200: httpStatusCode = pinStatusCode response.append(pinResponse) return makeJsonResponse(httpStatusCode, response)
def processRequest(cls, request): """ process a request by finding the request handler """ method = request.method key = request.rootPath.lower() if key in BaseRequestHandler._handlers: handler = BaseRequestHandler._handlers[key] timePrint('%s %s client: %s handler: %s' % (method, request.url, request.remote_addr, handler.name)) try: if handler.checkAuth(request): if method == 'GET': response = handler.doGet(request) elif method == 'POST': response = handler.doPost(request) elif method == 'PUT': response = handler.doPut(request) elif method == 'DELETE': response = handler.doDelete(request) else: response = makeJsonResponse( 403, {'response': 'InvalidMethod'}) else: response = makeJsonResponse(401, {'response': 'UnAuthorized'}) except Exception as e: timePrint('Exception handling request: ' + str(e)) traceback.print_exc() response = makeJsonResponse( 500, {'response': 'Exception: ' + str(e)}) elif len(key) == 0: # send available discovery paths if rootPath is not specified result = [] for key in BaseRequestHandler._handlers: handler = BaseRequestHandler._handlers[key] #result.append({'name': handler.name, 'path': key, 'url': request.host_url + key}) for item in handler.endpoints(key, request.host_url): result.append(item) response = makeJsonResponse(200, result) else: timePrint('%s %s client: %s handler: N.A.' % (method, request.url, request.remote_addr)) response = makeJsonResponse(403, {'response': 'InvalidPath'}) timePrint( '%s %s client: %s status: %s' % (method, request.url, request.remote_addr, response.status_code)) return response
def doGet(self, request): """ handle GET request for smart plug devices . request: the RequestContext data object must return a Flask.Response object """ deviceId = request.paths[1] if len(deviceId) == 0: return makeJsonResponse( 200, self.endpoints(self.rootPaths[0], request.host_url)) httpStatusCode = 200 device = self.deviceList[deviceId] if device == None: return makeJsonResponse(400, {KeyResponse: 'InvalidSmartDeviceId'}) node = request.paths[2] dataId = request.paths[3] httpStatusCode, response = device.get(node, dataId, request.args) return makeJsonResponse(httpStatusCode, response)
def doPost(self, request): """ handle POST request for smart plug devices . request: the RequestContext data object must return a Flask.Response object """ deviceId = request.paths[1] if len(deviceId) == 0: return makeJsonResponse(400, {KeyResponse: 'MissingSmartDeviceId'}) device = self.deviceList[deviceId] if device == None: return makeJsonResponse(400, {KeyResponse: 'InvalidSmartDeviceId'}) bodyJson = request.json response = [] httpStatusCode = 200 node = request.paths[2] # node should be one of ['system', 'cmd'] dataId = request.paths[3] httpStatusCode, response = device.post(node, dataId, request.json) return makeJsonResponse(httpStatusCode, response)
def doGet(self, request): """ handle GET request for Pi GPIO request: the RequestContext data object must return a Flask.Response object """ component = request.paths[1] if len(component) == 0: httpStatusCode, response = piGpio.getAll() else: response = piGpio.get(int(component), request.paths[2]) httpStatusCode = response.pop(KeyStatusCode, 400) return makeJsonResponse(httpStatusCode, response)
def doGet(self, request): """ handle GET request for PiCar request: the RequestContext data object must return a Flask.Response object """ component = request.paths[1] httpStatusCode = 200 try: if 'ultra' in component: value = self.commandHandler.car.distance response = {KeyPropertyKey: 'ultra', KeyPropertyValue: value} elif 'motor' in component: value = self.commandHandler.drive.motor.speed response = {KeyPropertyKey: 'motor', KeyPropertyValue: value} elif 'servo' in component: value = self.commandHandler.drive.steering.angle response = {KeyPropertyKey: 'servo', KeyPropertyValue: value} elif 'servocamh' in component: value = self.commandHandler.head.servoH.angle response = { KeyPropertyKey: 'servocamh', KeyPropertyValue: value } elif 'servocamv' in component: value = self.commandHandler.head.servoV.angle response = { KeyPropertyKey: 'servocamv', KeyPropertyValue: value } elif 'ledright' in component: value = self.commandHandler.drive.rightLed.rgb.toRGBStr() response = { KeyPropertyKey: 'ledright', KeyPropertyValue: value } elif 'ledleft' in component: value = self.commandHandler.drive.leftLed.rgb.toRGBStr() response = {KeyPropertyKey: 'ledleft', KeyPropertyValue: value} elif 'settings' in component: response = self.commandHandler.car.config.settings elif 'ledstrip' in component: httpStatusCode = 400 response = {KeyPropertyValue: 'NotYetSupported'} else: httpStatusCode = 400 response = {KeyResponse: 'InvalidComponent'} except Exception as e: print('Exception handling request: ' + str(e)) traceback.print_exc() httpStatusCode = 500 response = {KeyResponse: 'Exception: ' + str(e)} return makeJsonResponse(httpStatusCode, response)
def doGet(self, request): """ handle GET request for temperature/humidity value request: the RequestContext data object must return a Flask.Response object """ component = request.paths[1] httpStatusCode = 200 temperature, humidity = self.sensor.read() if len(component) == 0: response = {TemperatureKey: temperature, HumidityKey: humidity} elif 'temp' in component: response = {TemperatureKey: temperature} elif 'hum' in component: response = {HumidityKey: humidity} else: httpStatusCode = 400 response = { KeyResponse: 'InvalidPath' } return makeJsonResponse(httpStatusCode, response)
def doPost(self, request): """ handle POST request for Pi system resources request: the RequestContext data object must return a Flask.Response object """ component = request.paths[1] bodyDict = request.json response = [] httpStatusCode = 200 try: timePrint('Post to picar: ' + str(bodyDict)) if 'scan' == component: # for scan, the bodyDict contains strt end and inc for the scan response = self.commandHandler.doScanCommand(bodyDict) httpStatusCode = response.pop(KeyStatusCode, 400) elif 'settings' in component: config = self.commandHandler.car.config oldAutoSave = config.autoSave config.autoSave = False for key, value in bodyDict.items(): config.set(key, value) config.save(forceSave=True) config.autoSave = oldAutoSave response = {KeyResponse: 'Settings saved '} else: # process all the values in the body httpStatusCode = 200 comma = '' for key, value in bodyDict.items(): fullPath = request.path + '/' + key itemResponse = self.commandHandler.doCommand( fullPath, value) #timePrint(response) statusCode = itemResponse.pop(KeyStatusCode, 400) if statusCode != 200: httpStatusCode = statusCode response.append(itemResponse) except Exception as e: print('Exception handling request: ' + str(e)) traceback.print_exc() httpStatusCode = 500 response = {KeyResponse: 'Exception: ' + str(e)} return makeJsonResponse(httpStatusCode, response)
def doGet(self, request): """ handle GET request for Pi system resources request: the RequestContext data object must return a Flask.Response object """ component = request.paths[1] httpStatusCode = 200 if len(component) == 0: response = self.pistats.get_all_info() elif KeyComponentCpu in component: response = self.pistats.get_cpu_info() elif KeyComponentMemmory in component: response = self.pistats.get_memory_info() elif KeyComponentStorage in component: httpStatusCode = 400 response = { KeyResponse: 'NotYetSupported' } else: httpStatusCode = 400 response = { KeyResponse: 'InvalidSysComponent' } return makeJsonResponse(httpStatusCode, response)
def doDelete(self, request): """ must be implemented by derived class to handle Delete request request: the RequestContext data object must return a Flask.Response object """ return makeJsonResponse(400, {'response': 'InvalidRequest'})