class FlowerPi(object): def __init__(self): self.hardware = Hardware() a = Astral() a.solar_depression = 'civil' self.city = a['Kiev'] self.rpc_server = RPCServer(self.hardware) self.rpc_server.start() def process(self): now = datetime.now() print("Processing... Current time: {}".format(str(now))) sun = self.city.sun(date=now, local=True) sunrise = sun['sunrise'] sunset = sun['sunset'] if sunrise.hour == now.hour and sunrise.minute == now.minute: print("Sunrise. Time: {}".format(str(now))) self.hardware.turn_lamp_low() if sunset.hour == now.hour and sunset.minute == now.minute: print("Sunset. Time: {}".format(str(now))) self.hardware.turn_lamp_off()
def hardware(): hardware = Hardware(30) hardware.powerButton = MagicMock() hardware.powerButton.pressed.return_value = False type(hardware.accelerometer).acceleration = PropertyMock(return_value=(1, 1, 1)) hardware.speaker = MagicMock() hardware.speaker.audio = MagicMock() return hardware
def test_next_color_displays_to_next_color(): state = State(initial_mode=mode.COLOR_CHANGE, initial_color=colors.ALL_COLORS[0]) hardware = Hardware(30) hardware.powerButton = MagicMock() actions.saber = MagicMock() actions.next_color(hardware, state) actions.saber.on(hardware.strip, color=colors.ALL_COLORS[1]) hardware.powerButton.set_color.assert_called_with(colors.ALL_COLORS[1])
def test_swing_action_swells_light(): state = State(initial_mode=mode.ON, initial_color=colors.GREEN) hardware = Hardware(30) speaker_mock = MagicMock() hardware.speaker = speaker_mock actions.saber = MagicMock() actions.sound = MagicMock() actions.swing(hardware, state) actions.saber.swell.assert_called_with(hardware.strip, state.idle_color, state.color)
def test_activate_color_change_mode_displays_first_color(): state = State(initial_mode=mode.MODE_SELECT, initial_color=colors.GREEN) state.mode_selector.next() # select color change mode TODO improve this hardware = Hardware(30) speaker_mock = MagicMock() hardware.speaker = speaker_mock actions.saber = MagicMock() actions.sound = MagicMock() actions.activate_color_change_mode(hardware) actions.saber.on(hardware.strip, color=colors.ALL_COLORS[0])
def test_power_off_action_turns_off_lightsaber(): state = State(initial_mode=mode.ON, initial_color=colors.CYAN) state.sounds.off = lambda: 'offblah' hardware = Hardware(30) speaker_mock = MagicMock() hardware.speaker = speaker_mock actions.saber = MagicMock() actions.sound = MagicMock() actions.power_off(hardware, state) actions.saber.power.assert_called_with(hardware.strip, speaker_mock, 'offblah', 1.0, True, state.idle_color)
def test_clash_action_flashes_light(): state = State(initial_mode=mode.ON, initial_color=colors.PURPLE) hardware = Hardware(30) speaker_mock = MagicMock() hardware.speaker = speaker_mock actions.saber = MagicMock() actions.sound = MagicMock() actions.clash(hardware, state) actions.saber.flash.assert_called_with(hardware.strip, colors.WHITE, state.idle_color, num_of_flashes=1)
def test_mode_select_action_plays_wow(): state = State(initial_mode=mode.OFF, initial_color=colors.ORANGE) hardware = Hardware(30) hardware.powerButton.pressed = MagicMock( return_value=False) # Code needs to make sure the button is released speaker_mock = MagicMock() hardware.speaker = speaker_mock actions.saber = MagicMock() actions.sound = MagicMock() actions.mode_select(hardware, state) actions.sound.play_wav.assert_called_with('wow1', speaker_mock)
def test_cycle_idle_loop_stops_and_starts_idle_sound(): state = State(initial_mode=mode.ON, initial_color=colors.ORANGE) state.sounds.idle = lambda: 'idleblah' hardware = Hardware(30) hardware.speaker = MagicMock() hardware.speaker.audio = MagicMock() actions.saber = MagicMock() actions.sound = MagicMock() actions.cycle_idle_loop(hardware, state) hardware.speaker.audio.stop.assert_called_with() actions.sound.play_wav.assert_called_with('idleblah', hardware.speaker, loop=True)
def __init__(self): self.hardware = Hardware() a = Astral() a.solar_depression = 'civil' self.city = a['Kiev'] self.rpc_server = RPCServer(self.hardware) self.rpc_server.start()
def build(self, id='-1', state_interval=-1, componentsMapped=False): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time() * 1000) queueResult = self.actionQueue.result() nodeStatus = {"status": "HEALTHY", "cause": "NONE"} nodeStatus["alerts"] = [] heartbeat = { 'responseId': int(id), 'timestamp': timestamp, 'hostname': hostname.hostname(self.config), 'nodeStatus': nodeStatus } commandsInProgress = False if not self.actionQueue.commandQueue.empty(): commandsInProgress = True if len(queueResult) != 0: heartbeat['reports'] = queueResult['reports'] heartbeat['componentStatus'] = queueResult['componentStatus'] if len(heartbeat['reports']) > 0: # There may be IN_PROGRESS tasks commandsInProgress = True pass # For first request/heartbeat assume no components are mapped if int(id) == 0: componentsMapped = False logger.info( "Building Heartbeat: {responseId = %s, timestamp = %s, commandsInProgress = %s, componentsMapped = %s}", str(id), str(timestamp), repr(commandsInProgress), repr(componentsMapped)) if logger.isEnabledFor(logging.DEBUG): logger.debug("Heartbeat: %s", pformat(heartbeat)) hostInfo = HostInfo(self.config) if (int(id) >= 0) and state_interval > 0 and (int(id) % state_interval) == 0: nodeInfo = {} # for now, just do the same work as registration # this must be the last step before returning heartbeat hostInfo.register(nodeInfo, componentsMapped, commandsInProgress) heartbeat['agentEnv'] = nodeInfo mounts = Hardware.osdisks() heartbeat['mounts'] = mounts if logger.isEnabledFor(logging.DEBUG): logger.debug("agentEnv: %s", str(nodeInfo)) logger.debug("mounts: %s", str(mounts)) nodeStatus["alerts"] = hostInfo.createAlerts(nodeStatus["alerts"]) if self.collector is not None: heartbeat['alerts'] = self.collector.alerts() return heartbeat
def get_page(self, params): super().get_page(params) if not self.validate_params(params, ["name", "platform", "numcopies"]): return "" interactor = self.interactor_factory.create("SaveHardwareInteractor") hardware = Hardware.from_dict(params) interactor.execute(hardware=hardware, user_id=self.session.get_value("user_id"))
class Heartbeat: def __init__(self, actionQueue): self.actionQueue = actionQueue self.hardware = Hardware() def build(self, id="-1"): global clusterId, clusterDefinitionRevision, firstContact serverStatus = ServerStatus() timestamp = int(time.time() * 1000) queueResult = self.actionQueue.result() installedRoleStates = serverStatus.build() heartbeat = { "responseId": int(id), "timestamp": timestamp, "hostname": socket.gethostname(), "hardwareProfile": self.hardware.get(), "idle": self.actionQueue.isIdle(), "installScriptHash": self.actionQueue.getInstallScriptHash(), "firstContact": firstContact, } if len(queueResult) != 0: heartbeat["actionResults"] = queueResult if len(installedRoleStates) != 0: heartbeat["installedRoleStates"] = installedRoleStates firstContact = False return heartbeat
def main(): state = State(initial_mode=mode.LIGHTSABER, initial_color=colors.BLUE) hardware = Hardware(132) saber.off(hardware.strip) hardware.powerButton.set_color(state.color) while True: state = run(state, hardware)
class Register: """ Registering with the server. Get the hardware profile and declare success for now """ def __init__(self, config): self.hardware = Hardware() self.config = config def build(self, version, id='-1'): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time() * 1000) hostInfo = HostInfo(self.config) agentEnv = {} hostInfo.register(agentEnv, False, False) current_ping_port = self.config.get('agent', 'current_ping_port') register = { 'responseId': int(id), 'timestamp': timestamp, 'hostname': hostname.hostname(self.config), 'currentPingPort': int(current_ping_port), 'publicHostname': hostname.public_hostname(self.config), 'hardwareProfile': self.hardware.get(), 'agentEnv': agentEnv, 'agentVersion': version, 'prefix': self.config.get('agent', 'prefix') } return register
class Register: """ Registering with the server. Get the hardware profile and declare success for now """ def __init__(self, config): self.hardware = Hardware(config) self.agentInfo = AgentInfo(config) self.config = config def build(self, id='-1'): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time()*1000) hostInfo = HostInfo(self.config) agentEnv = { } hostInfo.register(agentEnv, False, False) version = self.agentInfo.version() current_ping_port = self.config.get('agent','current_ping_port') register = { 'responseId' : int(id), 'timestamp' : timestamp, 'hostname' : hostname.hostname(), 'currentPingPort' : int(current_ping_port), 'publicHostname' : hostname.public_hostname(), 'hardwareProfile' : self.hardware.get(), 'agentEnv' : agentEnv, 'agentVersion' : version } return register
class Register: """ Registering with the server. Get the hardware profile and declare success for now """ def __init__(self, config): self.hardware = Hardware() self.config = config def build(self, id='-1'): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time() * 1000) version = self.read_agent_version() register = { 'responseId': int(id), 'timestamp': timestamp, 'hostname': self.config.getLabel(), 'currentPingPort': 8670, 'publicHostname': hostname.public_hostname(), 'hardwareProfile': self.hardware.get(), 'agentEnv': {}, 'agentVersion': version } return register def read_agent_version(self): ver_file = self.config.getResolvedPath(AgentConfig.VERSION_FILE) f = open(ver_file, "r") version = f.read().strip() f.close() return version
class Register: """ Registering with the server. Get the hardware profile and declare success for now """ def __init__(self, config): self.hardware = Hardware() self.config = config def build(self, id='-1'): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time()*1000) hostInfo = HostInfo() agentEnv = { } hostInfo.register(agentEnv) version = self.read_agent_version() register = { 'responseId' : int(id), 'timestamp' : timestamp, 'hostname' : hostname.hostname(), 'publicHostname' : hostname.public_hostname(), 'hardwareProfile' : self.hardware.get(), 'agentEnv' : agentEnv, 'agentVersion' : version } return register def read_agent_version(self): data_dir = self.config.get('agent', 'prefix') ver_file = os.path.join(data_dir, 'version') f = open(ver_file, "r") version = f.read().strip() f.close() return version
class Register: """ Registering with the server. Get the hardware profile and declare success for now """ def __init__(self, config): self.hardware = Hardware() self.config = config def build(self, id='-1'): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time()*1000) version = self.read_agent_version() register = { 'responseId' : int(id), 'timestamp' : timestamp, 'hostname' : self.config.getLabel(), 'currentPingPort' : 8670, 'publicHostname' : hostname.public_hostname(), 'hardwareProfile' : self.hardware.get(), 'agentEnv' : {}, 'agentVersion' : version } return register def read_agent_version(self): ver_file = self.config.getResolvedPath(AgentConfig.VERSION_FILE) f = open(ver_file, "r") version = f.read().strip() f.close() return version
def __init__(self, logger): # Logger self._logger = logger # Hardware of OS self._hardware = Hardware(self._logger) # Kernel of OS self._kernel = KernelSO(self._logger, self._hardware, Scheduler())
def osdiskAvailableSpace(self, path): diskInfo = {} try: df = subprocess.Popen(["df", "-kPT", path], stdout=subprocess.PIPE) dfdata = df.communicate()[0] return Hardware.extractMountInfo(dfdata.splitlines()[-1]) except: pass return diskInfo
def __init__(self): try: self.routinepath = os.getcwd() + '/routines' for i in range(0, paras.jointqty): maxdeg = paras.jsetting[i]["maxdeg"] mindeg = paras.jsetting[i]["mindeg"] steplimit = paras.jsetting[i]["steplimit"] paras.jsetting[i]["degperstep"] = round( float((maxdeg - mindeg) / float(steplimit)), 8) for k, v in paras.tracksetting.items(): steplimit = paras.tracksetting[k]['steplimit'] length = paras.tracksetting[k]['length'] paras.tracksetting[k]['mmperstep'] = round( (length / steplimit), 8) self.hw = Hardware(values, paras) except Exception as e: print("Failed connect arm ", e) exit()
def test_swing_action_plays_sound(): state = State(initial_mode=mode.ON, initial_color=colors.GREEN) state.sounds.swing = lambda: 'swingblah' state.sounds.idle = lambda: 'idleblah' hardware = Hardware(30) speaker_mock = MagicMock() hardware.speaker = speaker_mock actions.saber = MagicMock() actions.sound = MagicMock() actions.swing(hardware, state) play_clash_call = call('swingblah', speaker_mock) play_idle_call = call('idleblah', speaker_mock, loop=True, override_current_sound=False) actions.sound.play_wav.assert_has_calls([play_clash_call, play_idle_call])
def build(self, id='-1', state_interval=-1, componentsMapped=False): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time()*1000) queueResult = self.actionQueue.result() nodeStatus = { "status" : "HEALTHY", "cause" : "NONE" } nodeStatus["alerts"] = [] heartbeat = { 'responseId' : int(id), 'timestamp' : timestamp, 'hostname' : hostname.hostname(self.config), 'nodeStatus' : nodeStatus } commandsInProgress = False if not self.actionQueue.commandQueue.empty(): commandsInProgress = True if len(queueResult) != 0: heartbeat['reports'] = queueResult['reports'] heartbeat['componentStatus'] = queueResult['componentStatus'] if len(heartbeat['reports']) > 0: # There may be IN_PROGRESS tasks commandsInProgress = True pass # For first request/heartbeat assume no components are mapped if int(id) == 0: componentsMapped = False logger.info("Building Heartbeat: {responseId = %s, timestamp = %s, commandsInProgress = %s, componentsMapped = %s}", str(id), str(timestamp), repr(commandsInProgress), repr(componentsMapped)) if logger.isEnabledFor(logging.DEBUG): logger.debug("Heartbeat: %s", pformat(heartbeat)) hostInfo = HostInfo(self.config) if (int(id) >= 0) and state_interval > 0 and (int(id) % state_interval) == 0: nodeInfo = { } # for now, just do the same work as registration # this must be the last step before returning heartbeat hostInfo.register(nodeInfo, componentsMapped, commandsInProgress) heartbeat['agentEnv'] = nodeInfo mounts = Hardware.osdisks() heartbeat['mounts'] = mounts if logger.isEnabledFor(logging.DEBUG): logger.debug("agentEnv: %s", str(nodeInfo)) logger.debug("mounts: %s", str(mounts)) nodeStatus["alerts"] = hostInfo.createAlerts(nodeStatus["alerts"]) return heartbeat
def test_power_on_action_turns_on_lightsaber(): hardware = Hardware(30) speaker_mock = MagicMock() hardware.speaker = speaker_mock actions.saber = MagicMock() actions.sound = MagicMock() state = State(initial_mode=mode.OFF, initial_color=colors.CONSULAR_GREEN) state.sounds.on = lambda: 'onblah' state.sounds.idle = lambda: 'idleblah' actions.power_on(hardware, state) actions.saber.power.assert_called_with(hardware.strip, speaker_mock, 'onblah', 1.0, False, state.idle_color) actions.sound.play_wav.assert_called_with('idleblah', speaker_mock, loop=True, override_current_sound=False)
def test_execute_action_loops_back_to_first_color_on_next_color_action(): state = State(initial_mode=mode.COLOR_CHANGE, initial_color=colors.ALL_COLORS[len(colors.ALL_COLORS) - 1]) hardware = Hardware(30) actions.saber = MagicMock() actions.next_color(hardware, state) actions.saber.on(hardware.strip, color=colors.ALL_COLORS[0])
def get_hardware_list_for_platform(self, params): """Get a list of all hardware for a platform in the user's collection param params: An instance of GetHardwareListInteractorParams returns: A list of instances of Hardware """ sorder = MongoSortDirectionMapper().map(params.sort_direction) mapped_sort_field = HardwareSortFieldMapper().map(params.sort_field) hardware = self.__db.hardware.find({"_Hardware__platform": params.platform, "user_id": str(params.user_id)}, limit=params.number_of_items) return list(map(lambda p: Hardware.from_mongo_result(p), hardware))
def get_hardware_list(self, params): """Get a list of all hardware in the user's collection :param params: An instance of GetHardwareListInteractorParams :returns: A list of instances of Hardware """ sorder = MongoSortDirectionMapper().map(params.sort_direction) mapped_sort_field = HardwareSortFieldMapper().map(params.sort_field) result = self.__db.hardware.find({"user_id": str(params.user_id)}, limit=params.number_of_items).sort( mapped_sort_field, sorder) return list(map(lambda p: Hardware.from_mongo_result(p), result))
def system_verification(env, component): import params hardware = Hardware().get() requirements = specs.requirements verify = Verifications(hardware, requirements) verify.mandatory_checks(component) if not params.skip_preinstall_verification: verify.preinstall_checks(component) if verify.get_messages(): raise Fail(verify.get_notice())
def get_hardware(self, hardware_id="", name="name", platform="platform", num_owned=0, num_boxed=0): hardware = Hardware() hardware.id = hardware_id hardware.name = name hardware.platform = platform hardware.num_owned = num_owned hardware.num_boxed = num_boxed return hardware
def __get_hardware(self, params): hardware = Hardware() hardware.name = params.get("name", "") hardware.platform = params.get("platform", "") hardware.num_owned = params.get("numcopies", "") hardware.num_boxed = params.get("numboxed", "") hardware.notes = params.get("notes", "") return hardware
def get_hardware_details(self, platform_id, user_id): """Gets the details of a specific item of hardware. :param hardware_id: The uuid of the item of hardware to retrieve. :param user_id: The uuid of the current user. :returns: An instance of Hardware containing the requested item of hardware. """ try: h = self.__db.hardware.find_one({ "_id": ObjectId(platform_id), "user_id": str(user_id) }) except InvalidId: raise HardwareNotFoundException() return Hardware.from_mongo_result(h)
def build(self, id='-1', state_interval=-1, componentsMapped=False): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time()*1000) queueResult = self.actionQueue.result() nodeStatus = { "status" : "HEALTHY", "cause" : "NONE"} heartbeat = { 'responseId' : int(id), 'timestamp' : timestamp, 'hostname' : hostname.hostname(), 'nodeStatus' : nodeStatus } commandsInProgress = False if not self.actionQueue.commandQueue.empty(): commandsInProgress = True if len(queueResult) != 0: heartbeat['reports'] = queueResult['reports'] heartbeat['componentStatus'] = queueResult['componentStatus'] if len(heartbeat['reports']) > 0: # There may be IN_PROGRESS tasks commandsInProgress = True pass # For first request/heartbeat assume no components are mapped if int(id) == 0: componentsMapped = False logger.info("Sending heartbeat with response id: " + str(id) + " and " "timestamp: " + str(timestamp) + ". Command(s) in progress: " + repr(commandsInProgress) + ". Components mapped: " + repr(componentsMapped)) logger.debug("Heartbeat : " + pformat(heartbeat)) if (int(id) >= 0) and state_interval > 0 and (int(id) % state_interval) == 0: hostInfo = HostInfo(self.config) nodeInfo = { } # for now, just do the same work as registration # this must be the last step before returning heartbeat hostInfo.register(nodeInfo, componentsMapped, commandsInProgress) heartbeat['agentEnv'] = nodeInfo logger.debug("agentEnv : " + str(nodeInfo)) mounts = Hardware.osdisks() heartbeat['mounts'] = mounts logger.debug("mounts : " + str(mounts)) return heartbeat
class Register: """ Registering with the server. Get the hardware profile and declare success for now """ def __init__(self): self.hardware = Hardware() def build(self, id='-1'): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time()*1000) register = { 'responseId' : int(id), 'timestamp' : timestamp, 'hostname' : socket.gethostname(), 'hardwareProfile' : self.hardware.get(), } return register
def get_page(self, params): """Handles Hardware Update requests (i.e. new values to save to a hardware record). This is really intended to be used as an ajax request rather than a webpage, so it doesn't give much in the way of user feedback. If the user is not currently logged in then it will redirect to the homepage. param params: A dictionary comprised of the following keys: + id -- The uuid of the item of hardware to save. + name -- The name of the item of hardware. Mandatory. + platform -- The plaform of the item of hardware. Mandatory. + numcopies -- The number of copies owned of the item of hardware. + numboxed -- The number of boxed copies owned of the item of hardware. + notes -- Miscellaneous notes added by the user. + hardwaretype -- The type of hardware returns: If one of the mandatory args keys is omitted then an empty string. Else None. """ super().get_page(params) if not self.validate_params(params, ["name", "platform"]): return "" interactor = self.interactor_factory.create("UpdateHardwareInteractor") interactor.execute(Hardware.from_dict(params), self.session.get_value("user_id"))
class Register: """ Registering with the server. Get the hardware profile and declare success for now """ def __init__(self, config): self.hardware = Hardware() self.config = config def build(self, id='-1'): global clusterId, clusterDefinitionRevision, firstContact timestamp = int(time.time()*1000) hostInfo = HostInfo(self.config) agentEnv = { } hostInfo.register(agentEnv, False, False) version = self.read_agent_version() current_ping_port = self.config.get('agent','current_ping_port') register = { 'responseId' : int(id), 'timestamp' : timestamp, 'hostname' : hostname.hostname(self.config), 'currentPingPort' : int(current_ping_port), 'publicHostname' : hostname.public_hostname(self.config), 'hardwareProfile' : self.hardware.get(), 'agentEnv' : agentEnv, 'agentVersion' : version, 'prefix' : self.config.get('agent', 'prefix') } return register def read_agent_version(self): data_dir = self.config.get('agent', 'prefix') ver_file = os.path.join(data_dir, 'version') f = open(ver_file, "r") version = f.read().strip() f.close() return version
def __init__(self): id = "hw" Hardware.__init__(self, id)
from kivy.clock import Clock from kivy.uix.floatlayout import FloatLayout from kivy.uix.popup import Popup from SitePriorities import SitePriorities from Hardware import Hardware from datetime import datetime class WindowManager(ScreenManager): pass sitePriorities = SitePriorities() siteHardware = Hardware() hardwareType = "" package = "" onboarding = "" #Algorithm for reading the lookup table into a 2d list lookupTable = [] file = open("LookUpTable.txt", "r") for x in file: lookupTable.append(x.split(" ")) file.close()
def __init__(self, config): self.hardware = Hardware() self.config = config
def __init__(self, config): self.hardware = Hardware(config) self.agentInfo = AgentInfo(config) self.config = config
@app.route('/getscanvars') def getScanVars(): result = g_Hardware.getScanVars() return Response(json.dumps(result), content_type='text/plain; charset=utf-8') @app.route('/setscanvar/<var>/<value>') def setScanVar(var, value): result = g_Hardware.setScanVar(var, value) return Response(json.dumps(result), content_type='text/plain; charset=utf-8') @app.route('/worm/startscan') def startScan(): result = g_Hardware.startScan() return Response(json.dumps(result), content_type='text/plain; charset=utf-8') @app.route('/worm/getlastmeasurements') def getLasMeasurements(): result = g_Hardware.getLastMeasurements() return Response(json.dumps(result), content_type='text/plain; charset=utf-8') if __name__ == "__main__": if len(sys.argv) >= 2 and sys.argv[1] == "stub": from HardwareStub import HardwareStub g_Hardware = HardwareStub(app.logger, "config/config.ini") else: from Hardware import Hardware g_Hardware = Hardware(app.logger, "config/config.ini") app.run(host='0.0.0.0', port=7778, debug=True)
class Kernel: hw = None routinepath = "" routineextenstion = ".json" methodname = "" resource = "" subresource = "" req = {} def __init__(self): try: self.routinepath = os.getcwd() + '/routines' for i in range(0, paras.jointqty): maxdeg = paras.jsetting[i]["maxdeg"] mindeg = paras.jsetting[i]["mindeg"] steplimit = paras.jsetting[i]["steplimit"] paras.jsetting[i]["degperstep"] = round( float((maxdeg - mindeg) / float(steplimit)), 8) for k, v in paras.tracksetting.items(): steplimit = paras.tracksetting[k]['steplimit'] length = paras.tracksetting[k]['length'] paras.tracksetting[k]['mmperstep'] = round( (length / steplimit), 8) self.hw = Hardware(values, paras) except Exception as e: print("Failed connect arm ", e) exit() ######################################################################## ######################## process http route ############################ ######################## return result in json ######################### ######################################################################## # display welcome msg def api_index(self): return { "status": "OK", "msg": "Welcome index page of AR3 webservice, you can call /info now" } # display robot arm environment data def api_info(self): result = {} result = self.hw.checkMachineStatus() # result['xyz'] = self.getEndPointPosition(result['jointvalues']) return result def api_calibrate(self): # display calibration options x = self.resource if x == "setrest": result = self.overrideRestPosition() elif x == "all": result = self.calibrateAll() elif len(x) == 2 and self.left(x, 1) == 'j': result = self.calibrateJoints(x) elif x is None: return log.getMsg( 'OK', 'You can calibrate all joint with /calibrate/all, calibrate single joint (j1-j6) like /calibrate/j1, set new rest position /calibrate/setrest' ) else: return log.getMsg('ERR_CALIBRATION_UNKNOWN', x + " is not valid calibration command") return log.getMsg(result, "") def api_movetorestposition(self): result = self.moveToRestPosition([1, 1, 1, 1, 1, 1]) return log.getMsg(result, "") def api_calibratetrack(self): if self.resource is None: tracks = self.hw.getAllTracks() separator = ',' txttracks = separator.join(tracks) return log.getMsg("OK", "Available travel track is " + txttracks) else: result = self.calibrateTrack(self.resource) return log.getMsg(result, "") def api_movetrack(self): if self.resource is None: tracks = self.hw.getAllTracks() separator = ',' txttracks = separator.join(tracks) return log.getMsg("OK", "Available travel track is " + txttracks) else: mm = self.req.get("mm") movetype = self.req.get("movetype") result = self.moveTrack(self.resource, mm, movetype) return log.getMsg(result, "") def api_servo(self): if self.resource is None: servos = self.hw.getAllServos() separator = ',' txtservos = separator.join(servos) return log.getMsg("OK", "Available servo is " + txtservos) else: value = self.req.get("value") result = self.moveServo(self.resource, value) return log.getMsg(result, "") def api_move_j(self): if self.resource is None: return log.getMsg( "OK", "You can move joint j1-j6, like /move_j/j1?movetype=absolute/move°ree=10" ) else: degree = self.req.get("degree") movetype = self.req.get("movetype") result = self.moveJoint(self.resource, degree, movetype) return log.getMsg(result, "") def api_move_l(self): x = self.req.get('x') y = self.req.get('y') z = self.req.get('z') result = self.moveLinear(x, y, z) return log.getMsg(result, "") def api_getpositionurl(self): result = self.getPositionUrl() return log.getMsg("OK", result) def api_setposition(self): allparas = {} for k, v in self.req.items(): allparas[k] = v result = self.setPosition(allparas) return log.getMsg(result, "") def api_setspeed(self): result = self.setSpeed(self.req.get('percent')) return log.getMsg(result, "") def api_io(self): l = self.getAllIO() if self.resource is None: return log.getMsg( "OK", "Only support digital input/output at the moment", { 'inputpin': l['input'], 'outputpin': l['output'] }) elif self.subresource is None: operation = self.resource.lower() if operation == 'on' or operation == 'off': return log.getMsg( "OK", "You can output digital signal to following pins", {'pins': l['output']}) elif operation == 'read': return log.getMsg( "OK", "You can read digital input from following pins", {'pins': l['input']}) else: return log.getMsg("ERR_IO_INVALIDOPERATION", "") else: operation = self.resource.lower() pinno = int(self.subresource) if operation == 'read': result = self.readDigitalInput(pinno) if self.isErrorCode(result): return log.getMsg(result, "") else: return log.getMsg("OK", "", {"value": result}) #write digital io elif operation == 'on' or operation == 'off': result = self.sendDigitalOutput(pinno, operation) else: result = "ERR_IO_INVALIDOPERATION" return log.getMsg(result, "") def api_routine(self): if self.resource is None: list = self.getAllRoutines() separator = "," availableroutine = separator.join(list) return log.getMsg('OK', f"Available routines is {availableroutine}", {'routines': list}) routinename = self.resource othersinfo = self.subresource # direct give routine json content if othersinfo is None: result = self.getRoutineInfo(routinename) if not self.isErrorCode(result): return result else: return log.getMsg( result, f"Invalid json content, please check again {routinename}.json." ) elif othersinfo == "run": result = self.runRoutine(routinename) else: result = "ERR_ROUTINE_OPERATIONUNKNOWN" return log.getMsg(result, "") ######################################################################## ################## process robot arm operations ####################### ################## return result in string only ####################### ######################################################################## ################## calibration ####################### def showCalibrateGuide(self): return "OK" def overrideRestPosition(self): result = self.hw.writeARMPosition('rest', [1, 1, 1, 1, 1, 1]) return result def calibrateJoints(self, jname): jointno = int(self.right(jname, 1)) - 1 result = self.hw.calibrateJoint(jointno) return result def calibrateAll(self): joints = [1, 1, 1, 1, 1, 1] result = self.hw.goAllJointLimit(joints) if result == "OK": result2 = self.moveToRestPosition(joints) return result2 else: return result def calibrateTrack(self, trackname): return self.hw.setTrackValue(trackname, 0) def moveToRestPosition(self, joints=[1, 1, 1, 1, 1, 1]): for i in range(0, paras.jointqty): restpos = paras.jsetting[i]["restpos"] jname = 'J' + str(i + 1) if joints[i] == 1: result = self.moveJoint(jname, restpos, 'absolute') #if error, stop and move and return err code if self.isErrorCode(result): return result return "OK" ################# move arm ######################### def moveJoint(self, jname, degree, movetype): # validate movetype is received, and with proper value if type(movetype) is not str: return 'ERR_MOVE_INVALIDTYPE' else: movetype = movetype.upper() if movetype != 'MOVE' and movetype != 'ABSOLUTE': return 'ERR_MOVE_INVALIDTYPE' if degree is None: return "ERR_JOINT_NODEGREEDEFINED" elif type(degree) is str: degree = float(degree) jointname = jname.lower() if len(jointname) != 2 and self.left(jointname, 1) != 'j': return 'ERR_JOINT_WRONGNAME' joint_id = int(self.right(jointname, 1)) - 1 if joint_id < 0 and joint_id > paras.jointqty: return log.getMsg('ERR_JOINT_OUT_OF_RANGE', '') encoders = self.hw.refreshStepperMotorEncoderValue() if type(encoders) == str: return encoders if movetype == 'MOVE': newdegree = encoders[joint_id]['degree'] + degree else: # put joint into absolute degree, need add existing position # newdegree = currentdegree + changedegree newdegree = degree exisdegree = encoders[joint_id]['degree'] degree = newdegree - exisdegree newdegreestr = str(newdegree) result = self.hw.rotateJoint(joint_id, degree) maxdegstr = str(paras.jsetting[joint_id]["maxdeg"]) mindegstr = str(paras.jsetting[joint_id]["mindeg"]) return result # if result != 'OK': # jsondata = log.getMsg(result, jname + " shift " + str( # degree) + " become " + newdegreestr + " which is not within " + mindegstr + "/" + maxdegstr) # else: # jsondata = log.getMsg(result, jname + " shift " + str( # degree) + " become " + newdegreestr + " which is within " + mindegstr + "/" + maxdegstr) # log.info("done rotateJoint") def moveLinear(self, x, y, z): if x is None or y is None or z is None: return "ERR_MOVEL_UNDEFINEDPARA" if type(x) == str: x = float(x) if type(y) == str: y = float(y) if type(z) == str: z = float(z) return self.hw.moveLinear(x, y, z) ################# move track ######################### def moveTrack(self, trackname, mm, movetype): # at the moment, any trackname also convert to track1 if not self.checkKey(paras.tracksetting, trackname): return 'ERR_TRACK_INVALID' # validate movetype is received, and with proper value if type(movetype) is not str: return 'ERR_MOVE_INVALIDTYPE' else: movetype = movetype.upper() if movetype != 'MOVE' and movetype != 'ABSOLUTE': return 'ERR_MOVE_INVALIDTYPE' trackdata = self.hw.getTrackValues()[trackname] bufferlength = 10 lengthlimit = paras.tracksetting[trackname]['length'] - bufferlength if mm is None: return "ERR_MOVE_INVALIDMM" if type(mm) is str: if mm.strip('-').isnumeric(): mm = float(mm) else: return "ERR_TRACK_WRONG_DATA_TYPE" if movetype == 'MOVE': newmm = trackdata['mm'] + mm else: # put joint into absolute degree, need add existing position # newdegree = currentdegree + changedegree newmm = mm exismm = trackdata['mm'] mm = newmm - exismm newmmstr = str(newmm) if newmm < 0 or newmm > lengthlimit: return 'ERR_MOVETRACK_OVERLIMIT' else: result = self.hw.moveTrack(trackname, mm) return result ################# move servo ######################### def moveServo(self, servoname, value): degree = 0 # validate servo exists if (self.checkKey(paras.servosetting, servoname) == False): return 'ERR_SERVO_INVALIDSERVO' if value is None: return "ERR_SERVO_INVALIDVALUE" # if given value is position name, get position degree from servosetting, or direct use integer value valuestr = '' if type(value) is int or type(value) is float: degree = value valuestr = str(valuestr) elif type(value) is str and value != '': # doublecheck, maybe value is number but data type is string if value.strip('-').isnumeric(): degree = float(value) else: degree = paras.servosetting[servoname]['positions'][value] valuestr = value else: return 'ERR_SERVO_INVALIDVALUE' result = self.hw.setServo(servoname, degree) if result == "OK": return log.getMsg(result, "") else: maxdeg = paras.servosetting[servoname]['maxdeg'] mindeg = paras.servosetting[servoname]['mindeg'] return result # return log.getMsg(result, "assigned invalid value '" + valuestr + "' to servo '" + servoname + "', please check is it within " + str( # mindeg) + "/" + str(maxdeg) + ".") ################# modifying arm speed ################ def setSpeed(self, percent): if percent is None: return "ERR_SETSPEED_UNDEFINEDVALUE" if type(percent) == str: percent = float(percent) return self.hw.setSpeed(percent) ############### covert arm position as restful url #### def getPositionUrl(self): joinvalues = self.hw.refreshStepperMotorEncoderValue() if self.isErrorCode(joinvalues): return joinvalues servovalues = self.hw.getServoValues() trackvalues = self.hw.getTrackValues() txt = '/setposition?' for k, v in joinvalues.items(): txt = txt + 'J' + str(k + 1) + '=' + str(v['degree']) + '&' for k, v in servovalues.items(): txt = txt + k + '=' + str(v) + '&' for k, v in trackvalues.items(): txt = txt + k + '=' + str(v['mm']) + '&' return txt ################# move all arm parts in 1 go ######### def setPosition(self, allpara): print("allpara:") print(allpara) # sample url = /setposition?J1=19.71&J2=-90.22&J3=1.89&J4=-0.07&J5=-0.23&J6=-0.47&gripper1=0&t1=0& # commandCalc = "MJA"+J1dir+J1steps+"B"+J2dir+J2steps+"C"+J3dir+J3steps+"D"+J4dir+J4steps+"E"+J5dir+J5steps+"F"+J6dir+J6steps+"T"+TRdir+TRstep+"S"+newSpeed+"G"+ACCdur+"H"+ACCspd+"I"+DECdur+"K"+DECspd+"U"+str(J1StepCur)+"V"+str(J2StepCur)+"W"+str(J3StepCur)+"X"+str(J4StepCur)+"Y"+str(J5StepCur)+"Z"+str(J6StepCur)+"\n" jointdata = {} trackdata = {} servodata = {} loop = 0 for k, v in allpara.items(): loop = loop + 1 if type(v) is str or type(v) is int: v = float(v) if self.checkKey(paras.servosetting, k): servodata[k] = v elif self.checkKey(paras.tracksetting, k): trackdata[k] = v elif len(k) == 2 and (self.left(k, 1) == 'j' or self.left(k, 1) == 'J') and self.right( k, 1).isnumeric(): # j1,j2,j3,j4,j5,j6 jointno = int(self.right(k, 1)) - 1 # J1 => 0, J2=>1 jointdata[jointno] = v else: # dont know what is the parameter for, ignore it a = 1 if loop > 0: result = self.hw.changePosition(jointdata, trackdata, servodata) else: result = "ERR_SETPOSITION_NOPARA" return result ######################################################################## ################## process io operations ############################# ################## return value (mixed) ############################### ######################################################################## def readDigitalInput(self, pin): return self.hw.readDigitalInput(pin) def sendDigitalOutput(self, pin, value): digitalvalue = None if type(value) == str: if value.lower() in ['on', '1']: digitalvalue = 1 elif value.lower() in ['off', '0']: digitalvalue = 0 else: return 'ERR_IO_INVALIDVALUE' elif value: digitalvalue = 1 else: digitalvalue = 0 return self.hw.sendDigitalOutput(pin, digitalvalue) def waitDigitalInput(self, pin, value): digitalvalue = None if type(value) == str: if value.lower() in ['on', '1']: digitalvalue = 1 elif value.lower() in ['off', '0']: digitalvalue = 0 else: return 'ERR_WAITIO_INVALIDVALUE' elif value: digitalvalue = 1 else: digitalvalue = 0 return self.hw.waitDigitalInput(pin, digitalvalue) def getAllIO(self): result = { "input": self.hw.inputpins, "output": self.hw.outputpins, } return result ######################################################################## ################## process robot arm routines ######################## ################## return multiple type result ######################## ######################################################################## def getAllRoutines(self): files = [] for file in os.listdir(self.routinepath): if file.endswith(self.routineextenstion): routinename = file.replace(self.routineextenstion, '') files.append(routinename) return files def getRoutineInfo(self, routinename, getcleartext=False): rt = Routine(self) result = rt.load(routinename) return result #upload new routine.json def addRoutine(self): return "OK" #upload new routine and override existing def overrideRoutine(self, routinename): return "OK" def deleteRoutine(self, routinename): return "OK" def runRoutine(self, routinename): rt = Routine(self) success = rt.load(routinename) if not success: return "ERR_ROUTINE_INVALIDJSON" else: result = rt.execute() return result ######################################################################## ################## Others useful method not related arm ############## ################## return multiple type result ######################## ######################################################################## #### below store others function for string and data processing only #### def left(self, s, amount): return s[:amount] def right(self, s, amount): return s[-amount:] def checkKey(self, arr, key): if key in arr.keys(): return True else: return False def isErrorCode(self, data): if type(data) == str and self.left(data, 4) == 'ERR_': return True else: return False
def __get_hardware(self): return Hardware.from_dict(self.__get_params())
def __init__(self): self.hardware = Hardware()
def __init__(self, actionQueue): self.actionQueue = actionQueue self.hardware = Hardware()