def init_bodies(self): self.body = Body(1., .1, 1., np.array([.0, .0, .0]), np.array([0., 0., 0.]), 10) self.ring_1 = Ring(np.array([0, 0, 10]), 10, 320) self.ring_2 = Ring(np.array([0, 0, -10]), 10, 320) self.E = np.array([0., 0., 0.]) self.F = (0., 0., 0.)
def processDeviceEvents(self, dev, event): if (event == None): self.debugLog( "Failed to get correct event data for deviceID:%s. Will keep retrying for now. " % doorbellId) return isNewEvent = True try: if (dev.states["lastEventTime"] != ""): try: isNewEvent = datetime.strptime( dev.states["lastEventTime"], '%Y-%m-%d %H:%M:%S') < event.now except: self.errorLog( "Failed to parse some datetimes. If this happens a lot you might need help from the developer!" ) if isNewEvent: self.debugLog("processing event for %s" % dev.pluginProps["doorbellId"]) try: self.updateStateOnServer(dev, "lastEventId", str(event.id)) except: self.de(dev, "lastEventId") try: self.updateStateOnServer(dev, "lastEvent", event.kind) except: self.de(dev, "lastEvent") try: self.updateStateOnServer(dev, "lastEventTime", str(event.now)) except: self.de(dev, "lastEventTime") try: self.updateStateOnServer(dev, "lastAnswered", event.answered) except: self.de(dev, "lastAnswered") if (event.kind == "motion"): try: self.updateStateOnServer(dev, "lastMotionTime", str(event.now)) except: self.de(dev, "lastMotionTime") else: try: self.updateStateOnServer(dev, "lastButtonPressTime", str(event.now)) except: self.de(dev, "lastButtonPressTime") except Exception as err: exc_type, exc_obj, exc_tb = sys.exc_info() Ring.logTrace(self.Ring, "Update Error", { 'Error': str(err), 'Line': str(exc_tb.tb_lineno) }) self.errorLog("Error: %s, Line:%s" % (err, str(exc_tb.tb_lineno)))
def _refreshStatesFromHardware(self, dev): try: doorbellId = dev.pluginProps["doorbellId"] #self.debugLog(u"Getting data for Doorbell : %s" % doorbellId) doorbell = Ring.GetDevice(self.Ring, doorbellId) if doorbell is None: self.errorLog("Failed to get devices from Ring.com") return #Always update the battery level. In the event we dont have motion but the battery level if hasattr(doorbell, 'batterylevel'): try: self.updateStateOnServer(dev, "batteryLevel", doorbell.batterylevel) except: self.de(dev, "batteryLevel") try: self.updateStateOnServer(dev, "name", doorbell.description) except: self.de(dev, "name") try: self.updateStateOnServer(dev, "firmware", doorbell.firmware_version) except: self.de(dev, "firmware") try: self.updateStateOnServer(dev, "model", doorbell.kind) except: self.de(dev, "model") if (doorbell.state is not None): try: dev.updateStateOnServer("onOffState", doorbell.state) except: self.de(dev, "onOffState") #Process Events for specific device events = Ring.GetDoorbellEventsforId(self.Ring, doorbellId) if (events != None): #self.debugLog("Device Event(s) found! Event Id: %s" % str(events.id)) self.processDeviceEvents(dev, events) self.retryCount = 0 except Exception as err: self.retryCount = self.retryCount + 1 exc_type, exc_obj, exc_tb = sys.exc_info() Ring.logTrace(self.Ring, "Update Error", { 'Error': str(err), 'Line': str(exc_tb.tb_lineno) }) self.errorLog( "Failed to get correct event data for deviceID:%s. Will keep retrying until max attempts (%s) reached" % (doorbellId, self.pluginPrefs.get("maxRetry", 5))) self.errorLog("Error: %s, Line:%s" % (err, str(exc_tb.tb_lineno)))
def __init__(self, pluginId, pluginDisplayName, pluginVersion, pluginPrefs): super(Plugin, self).__init__(pluginId, pluginDisplayName, pluginVersion, pluginPrefs) self.Ring = Ring(self) self.debug = pluginPrefs.get("debug", False) self.UserID = None self.Password = None self.deviceList = {} self.loginFailed = False self.retryCount = 0 self.keepProcessing = True self.restartCount = 0
def test1(): """Test the Ring data structure.""" from Ring import Ring a = Ring([0,1,2]) assert a[0] == 0 assert a[1] == 1 assert a[2] == 2 assert a.first() == 0 assert a.last() == 2 a.turn() assert a[0] == 1 assert a[1] == 2 assert a[2] == 0 assert a.first() == 1 assert a.last() == 0 a.turn() assert a[0] == 2 assert a[1] == 0 assert a[2] == 1 assert a.first() == 2 assert a.last() == 1
class Scene01: def __init__(self): # Init General Parameters self.ring_v = [] self.is_running = False self.is_paused = True self.dt = 1 / 60.0 self.dt_k = 1. self.target_dt = 1 / 30.0 self.t_total = 0 self.hud_enabled = True self.graphs_enabled = False self.vector_field_enabled = True # Init Bodies self.init_bodies() # Init Graphics Manager self.g_manager = OpenGLManager( "Sphere in a Electric Field | Scene 01 | By: Matheus Kunnen ") self.move_vector = np.array([0., 0., 0.]) self.rot_vector = np.array([0., 0., 0.]) self.cam_pos = np.array([0, 20, -5]) self.cam_rot = np.array([-40, 0, 0]) self.g_manager.cam_pos = self.cam_pos self.g_manager.cam_rot = self.cam_rot # Init Graphs self.init_graphs() # Init Vector Field (Graphical R) self.init_vector_field() def init_bodies(self): self.body = Body(1., .1, 1., np.array([0., 0., 0.]), np.array([0., 0., .0]), -10) self.ring = Ring(np.array([0, 0, 0]), 10, 320) self.E = np.array([0., 0., 0.]) self.F = (0., 0., 0.) def init_graphs(self): graphs_s = [600, 80] graphs_offset = [-10, -20] n_points = 1000 n = 1 self.graph_f_x = Graph( "Fx x t", ["t", "Fx"], n_points, np.array(graphs_s), np.array([ self.g_manager.display_size[0] - graphs_s[0] + graphs_offset[0], self.g_manager.display_size[1] - n * graphs_s[1] + n * graphs_offset[1] ])) n += 1 self.graph_f_y = Graph( "Fy x t", ["t", "Fy"], n_points, np.array(graphs_s), np.array([ self.g_manager.display_size[0] - graphs_s[0] + graphs_offset[0], self.g_manager.display_size[1] - n * graphs_s[1] + n * graphs_offset[1] ])) n += 1 self.graph_f_z = Graph( "Fz x t", ["t", "Fz"], n_points, np.array(graphs_s), np.array([ self.g_manager.display_size[0] - graphs_s[0] - 10, self.g_manager.display_size[1] - n * graphs_s[1] - n * 20 ])) def init_vector_field(self): self.v_field = VectorField([12., 12., 6.], [1., 1., .5], l_bodies=self.ring.bodies_v) self.v_field.update_vectors() def run(self): self.is_running = self.g_manager.init_display() self.t_total = 0 while self.is_running: t1 = time.time() self.g_manager.clear_buffer() self.check_events() if not self.is_paused: self.update() self.draw() self.g_manager.swap_buffers() t2 = time.time() self.update_dt(t1, t2) def draw(self): self.draw_hud() self.draw_graphs() self.body.draw(self.g_manager, True) self.g_manager.draw_vector(self.body.b_pos, self.F, [1., 0., .8, 1.]) # Forca sobre a particula self.ring.draw(self.g_manager) if self.vector_field_enabled: self.v_field.draw(self.g_manager) def draw_graphs(self): if not self.graphs_enabled: return self.graph_f_x.draw(self.g_manager) self.graph_f_y.draw(self.g_manager) self.graph_f_z.draw(self.g_manager) def update(self): self.E = self.ring.get_electric_field(self.body.b_pos) self.F = self.E * self.body.b_charge self.body.update(self.dt * self.dt_k) self.update_graphs() def update_graphs(self): self.graph_f_x.put(np.array([float(self.t_total), float(self.F[0])])) self.graph_f_y.put(np.array([float(self.t_total), float(self.F[1])])) self.graph_f_z.put(np.array([float(self.t_total), float(self.F[2])])) def draw_hud(self): if not self.hud_enabled: return txt_status = "Paused" if self.is_paused else "Running" self.g_manager.captions = [ "-> General Parameters", f" FPS: {round(1/self.dt, 0)}", f"Runtime: {round(self.t_total, 3)}s.", f" Play: x{round(self.dt_k,1)}", f"Cam. dP: {np.round(self.cam_pos, 2)}", f"Cam. dR: {np.round(self.cam_rot, 2)}", f" Status: {txt_status}", "", "-> Central Body ", f" P: {np.round(self.body.b_pos, 3)}", f" V: {np.round(self.body.b_vel, 3)}", f" A: {np.round(self.body.b_aceleration, 3)}", f" E(P): {np.round(self.E, 3)}", f" Q: {np.round(self.body.b_charge, 3)}", "", "-> Ring", f" P: {np.round(self.ring.r_pos, 3)}", f"Radius: {round(self.ring.r_radius,3)}", f" Q: {round(self.ring.r_charge,3)}", f"N. Sph: {round(self.ring.n_bodies,3)}", f" Q Sph: {round(self.ring.q_bodies,3)}" ] self.g_manager.draw_captions() def update_dt(self, t1, t2): self.dt = t2 - t1 self.t_total += self.dt if not self.is_paused else 0. if self.dt > self.target_dt: pass #print(f"FPS {round(1/self.dt,1)} | {round((self.dt - self.target_dt)/self.target_dt,1)} frames missed") else: self.g_manager.wait(self.target_dt - self.dt) def get_sim_dt(self): return self.target_dt * Consts.DT_K def check_events(self): for event in pygame.event.get(): if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: self.move_vector[ 0] = Consts.MOVE_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_RIGHT: self.move_vector[ 0] = -Consts.MOVE_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_DOWN: self.move_vector[ 1] = Consts.MOVE_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_UP: self.move_vector[ 1] = -Consts.MOVE_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_q: self.move_vector[ 2] = Consts.MOVE_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_e: self.move_vector[ 2] = -Consts.MOVE_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_a: self.rot_vector[ 1] = -Consts.ROT_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_d: self.rot_vector[ 1] = Consts.ROT_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_w: self.rot_vector[ 0] = -Consts.ROT_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_s: self.rot_vector[ 0] = Consts.ROT_K if event.type == pygame.KEYDOWN else 0. elif event.key == pygame.K_h and event.type == pygame.KEYDOWN: self.hud_enabled = not self.hud_enabled elif event.key == pygame.K_v and event.type == pygame.KEYDOWN: self.vector_field_enabled = not self.vector_field_enabled elif event.key == pygame.K_PAGEUP and event.type == pygame.KEYDOWN: self.dt_k += Consts.DT_K elif event.key == pygame.K_PAGEDOWN and event.type == pygame.KEYDOWN and round( self.dt_k - Consts.DT_K, 1) > 0: self.dt_k -= Consts.DT_K elif event.key == pygame.K_p and event.type == pygame.KEYDOWN: self.is_paused = not self.is_paused elif event.key == pygame.K_g and event.type == pygame.KEYDOWN: self.graphs_enabled = not self.graphs_enabled elif event.key == pygame.K_b and event.type == pygame.KEYDOWN: self.v_field.set_draw_control( not self.v_field.draw_control) elif event.key == pygame.K_k and event.type == pygame.KEYDOWN: self.v_field.move_draw_plane(1.) elif event.key == pygame.K_m and event.type == pygame.KEYDOWN: self.v_field.move_draw_plane(-1.) if event.type == pygame.QUIT: is_running = False pygame.quit() quit() if self.is_paused: self.cam_pos = [ self.cam_pos[0] + self.move_vector[0], self.cam_pos[1] + self.move_vector[1], self.cam_pos[2] + self.move_vector[2] ] self.cam_rot = [ self.cam_rot[0] + self.rot_vector[0], self.cam_rot[1] + self.rot_vector[1], self.cam_rot[2] + self.rot_vector[2] ] self.g_manager.move_cam(self.move_vector) self.g_manager.rotate_cam(self.rot_vector) else: self.body.b_pos = self.body.b_pos + self.move_vector
class Plugin(indigo.PluginBase): ######################################## def __init__(self, pluginId, pluginDisplayName, pluginVersion, pluginPrefs): super(Plugin, self).__init__(pluginId, pluginDisplayName, pluginVersion, pluginPrefs) self.Ring = Ring(self) self.debug = pluginPrefs.get("debug", False) self.UserID = None self.Password = None self.deviceList = {} self.loginFailed = False self.retryCount = 0 self.keepProcessing = True self.restartCount = 0 def _refreshStatesFromHardware(self, dev): try: doorbellId = dev.pluginProps["doorbellId"] #self.debugLog(u"Getting data for Doorbell : %s" % doorbellId) doorbell = Ring.GetDevice(self.Ring, doorbellId) if doorbell is None: self.errorLog("Failed to get devices from Ring.com") return #Always update the battery level. In the event we dont have motion but the battery level if hasattr(doorbell, 'batterylevel'): try: self.updateStateOnServer(dev, "batteryLevel", doorbell.batterylevel) except: self.de(dev, "batteryLevel") try: self.updateStateOnServer(dev, "name", doorbell.description) except: self.de(dev, "name") try: self.updateStateOnServer(dev, "firmware", doorbell.firmware_version) except: self.de(dev, "firmware") try: self.updateStateOnServer(dev, "model", doorbell.kind) except: self.de(dev, "model") if (doorbell.state is not None): try: dev.updateStateOnServer("onOffState", doorbell.state) except: self.de(dev, "onOffState") #Process Events for specific device events = Ring.GetDoorbellEventsforId(self.Ring, doorbellId) if (events != None): #self.debugLog("Device Event(s) found! Event Id: %s" % str(events.id)) self.processDeviceEvents(dev, events) self.retryCount = 0 except Exception as err: self.retryCount = self.retryCount + 1 exc_type, exc_obj, exc_tb = sys.exc_info() Ring.logTrace(self.Ring, "Update Error", { 'Error': str(err), 'Line': str(exc_tb.tb_lineno) }) self.errorLog( "Failed to get correct event data for deviceID:%s. Will keep retrying until max attempts (%s) reached" % (doorbellId, self.pluginPrefs.get("maxRetry", 5))) self.errorLog("Error: %s, Line:%s" % (err, str(exc_tb.tb_lineno))) #Update the device properties in Indigo, Called from global events and per device events def processDeviceEvents(self, dev, event): if (event == None): self.debugLog( "Failed to get correct event data for deviceID:%s. Will keep retrying for now. " % doorbellId) return isNewEvent = True try: if (dev.states["lastEventTime"] != ""): try: isNewEvent = datetime.strptime( dev.states["lastEventTime"], '%Y-%m-%d %H:%M:%S') < event.now except: self.errorLog( "Failed to parse some datetimes. If this happens a lot you might need help from the developer!" ) if isNewEvent: self.debugLog("processing event for %s" % dev.pluginProps["doorbellId"]) try: self.updateStateOnServer(dev, "lastEventId", str(event.id)) except: self.de(dev, "lastEventId") try: self.updateStateOnServer(dev, "lastEvent", event.kind) except: self.de(dev, "lastEvent") try: self.updateStateOnServer(dev, "lastEventTime", str(event.now)) except: self.de(dev, "lastEventTime") try: self.updateStateOnServer(dev, "lastAnswered", event.answered) except: self.de(dev, "lastAnswered") if (event.kind == "motion"): try: self.updateStateOnServer(dev, "lastMotionTime", str(event.now)) except: self.de(dev, "lastMotionTime") else: try: self.updateStateOnServer(dev, "lastButtonPressTime", str(event.now)) except: self.de(dev, "lastButtonPressTime") except Exception as err: exc_type, exc_obj, exc_tb = sys.exc_info() Ring.logTrace(self.Ring, "Update Error", { 'Error': str(err), 'Line': str(exc_tb.tb_lineno) }) self.errorLog("Error: %s, Line:%s" % (err, str(exc_tb.tb_lineno))) def updateStateOnServer(self, dev, state, value): if dev.states[state] != value: self.debugLog(u"Updating Device: %s, State: %s, Value: %s" % (dev.name, state, value)) dev.updateStateOnServer(state, value) def de(self, dev, value): x = 1 #self.debugLog("[%s] No value found for device: %s, field: %s" % (time.asctime(), dev.name, value)) ######################################## def startup(self): self.debug = self.pluginPrefs.get('showDebugInLog', False) self.debugLog(u"startup called") self.updateFrequency = float( self.pluginPrefs.get('updateFrequency', 24)) * 60.0 * 60.0 self.debugLog(u"updateFrequency = " + str(self.updateFrequency)) self.next_update_check = time.time() self.login(False) def login(self, force): if self.Ring.startup(force) == False: indigo.server.log( u"Login to Ring site failed. Canceling processing!", isError=True) self.loginFailed = True return else: self.loginFailed = False self.buildAvailableDeviceList() def shutdown(self): self.debugLog(u"shutdown called") self.keepProcessing = False def stopConcurrentThread(self): self.debugLog(u"stopConcurrentThread called") self.keepProcessing = False ######################################## def runConcurrentThread(self): try: while self.keepProcessing: if self.loginFailed == False: if (self.updateFrequency > 0.0) and (time.time() > self.next_update_check): self.next_update_check = time.time( ) + self.updateFrequency self.version_check() #We need to get global events that are not device specific lastEvents = Ring.GetDoorbellEvent(self.Ring) if (lastEvents == False): self.errorLog("Error getting events. ") self.retryCount = self.retryCount + 1 if (int(self.pluginPrefs.get("maxRetry", 5)) != 0 and self.retryCount >= int( self.pluginPrefs.get("maxRetry", 5))): self.errorLog( "Reached max retry attempts. Won't Refresh from Server. !" ) self.errorLog( "You may need to contact Mike for support. Please post a message at http://forums.indigodomo.com/viewforum.php?f=235" ) self.sleep(36000) #Get Device specific Events for dev in indigo.devices.iter("self"): if not dev.enabled: #Skip disabled devices continue #Get the doorbell id for the current device doorbellId = dev.pluginProps["doorbellId"] if (int(self.pluginPrefs.get("maxRetry", 5)) != 0 and self.retryCount >= int( self.pluginPrefs.get("maxRetry", 5))): self.errorLog( "Reached max retry attempts. Won't Refresh from Server. !" ) self.errorLog( "You may need to contact Mike for support. Please post a message at http://forums.indigodomo.com/viewforum.php?f=235" ) self.sleep(36000) #Check to see if we have any global events for this device if len(lastEvents) != 0: for k, v in lastEvents.iteritems(): if (str(v.doorbot_id) == str(doorbellId)): event = v self.processDeviceEvents(dev, event) break self._refreshStatesFromHardware(dev) self.restartCount = self.restartCount + 1 if (self.restartCount > 10000): self.restartCount = 0 indigo.server.log( u"Memory Leak Prevention. Restarting Plugin. - This will happen until I find and fix the leak" ) serverPlugin = indigo.server.getPlugin(self.pluginId) serverPlugin.restart(waitUntilDone=False) break time.sleep(5) except self.StopThread: self.debugLog("shutdown requested") ######################################## def validateDeviceConfigUi(self, valuesDict, typeId, devId): indigo.server.log(u"validateDeviceConfigUi \"%s\"" % (valuesDict)) return (True, valuesDict) def validatePrefsConfigUi(self, valuesDict): self.debugLog(u"Vaidating Plugin Configuration") errorsDict = indigo.Dict() if valuesDict[u"maxRetry"] == "": errorsDict[u"maxRetry"] = u"Please enter retry value." else: try: int(valuesDict[u"maxRetry"]) except: errorsDict[u"maxRetry"] = u"Please enter a valid Retry Value." if len(errorsDict) > 0: self.errorLog(u"\t Validation Errors") return (False, valuesDict, errorsDict) else: self.debugLog(u"\t Validation Succesful") return (True, valuesDict) return (True, valuesDict) ######################################## def deviceStartComm(self, dev): if self.loginFailed == True: return self.initDevice(dev) dev.stateListOrDisplayStateIdChanged() def deviceStopComm(self, dev): # Called when communication with the hardware should be shutdown. pass def closedPrefsConfigUi(self, valuesDict, userCancelled): if not userCancelled: #Check if Debugging is set try: self.debug = self.pluginPrefs[u'showDebugInLog'] except: self.debug = False try: if (self.UserID != self.pluginPrefs["UserID"]) or \ (self.Password != self.pluginPrefs["Password"]): indigo.server.log("[%s] Replacting Username/Password." % time.asctime()) self.UserID = self.pluginPrefs["UserID"] self.Password = self.pluginPrefs["Password"] except: pass indigo.server.log("[%s] Processed plugin preferences." % time.asctime()) self.login(True) return True def validateDeviceConfigUi(self, valuesDict, typeId, devId): #self.debugLog(u"validateDeviceConfigUi called with valuesDict: %s" % str(valuesDict)) return (True, valuesDict) def initDevice(self, dev): self.debugLog("Initializing Ring device: %s" % dev.name) #if (dev.states["lastEventTime"] == "") dev.states["lastEventTime"] = str( datetime.strptime('2016-01-01 01:00:00', '%Y-%m-%d %H:%M:%S')) def buildAvailableDeviceList(self): self.debugLog("Building Available Device List") self.deviceList = self.Ring.GetDevices() indigo.server.log("Number of devices found: %i" % (len(self.deviceList))) for (k, v) in self.deviceList.iteritems(): indigo.server.log("\t%s (id: %s)" % (v.description, k)) def showAvailableDevices(self): indigo.server.log("Number of devices found: %i" % (len(self.deviceList))) for (id, details) in self.deviceList.iteritems(): indigo.server.log("\t%s (id: %s)" % (details.description, id)) def doorbellList(self, filter, valuesDict, typeId, targetId): self.debugLog("deviceList called") deviceArray = [] deviceListCopy = deepcopy(self.deviceList) for existingDevice in indigo.devices.iter("self"): for id in self.deviceList: self.debugLog("States: %s" % existingDevice.address) self.debugLog("\tcomparing %s against deviceList item %s" % (existingDevice.address, id)) if str(existingDevice.address) == str(id): self.debugLog("\tremoving item %s" % (id)) del deviceListCopy[id] break if len(deviceListCopy) > 0: for (id, value) in deviceListCopy.iteritems(): deviceArray.append((id, value.description)) else: if len(self.deviceList): indigo.server.log("All devices found are already defined") else: indigo.server.log( "No devices were discovered on the network - select \"Rescan for Doorbells\" from the plugin's menu to rescan" ) self.debugLog("\t DeviceList deviceArray:\n%s" % (str(deviceArray))) return deviceArray def selectionChanged(self, valuesDict, typeId, devId): self.debugLog("SelectionChanged") if int(valuesDict["doorbell"]) in self.deviceList: self.debugLog("Looking up deviceID %s in DeviceList Table" % valuesDict["doorbell"]) selectedData = self.deviceList[int(valuesDict["doorbell"])] valuesDict["address"] = valuesDict["doorbell"] valuesDict["doorbellId"] = valuesDict["doorbell"] valuesDict["name"] = selectedData.description valuesDict["kind"] = selectedData.kind valuesDict["firmware"] = selectedData.firmware_version #self.debugLog(u"\tSelectionChanged valuesDict to be returned:\n%s" % (str(valuesDict))) return valuesDict def checkForUpdates(self): self.version_check() def updatePlugin(self): self.version_check() #def forceUpdate(self): #self.updater.update(currentVersion='0.0.0') def actionControlDevice(self, action, dev): doorbellId = dev.pluginProps["doorbellId"] indigo.server.log(u"Current state is \"%s\"" % (dev.onState), isError=False) ###### TURN ON ###### if action.deviceAction == indigo.kDeviceAction.TurnOn: # Command hardware module (dev) to turn ON here: sendSuccess = self.Ring.SetFloodLightOn(str(doorbellId)) #sendSuccess = True # Set to False if it failed. if sendSuccess: # If success then log that the command was successfully sent. indigo.server.log(u"sent \"%s\" %s" % (dev.name, "on")) # And then tell the Indigo Server to update the state. dev.updateStateOnServer("onOffState", True) else: # Else log failure but do NOT update state on Indigo Server. indigo.server.log(u"send \"%s\" %s failed" % (dev.name, "on"), isError=True) ###### TURN OFF ###### elif action.deviceAction == indigo.kDeviceAction.TurnOff: # Command hardware module (dev) to turn OFF here: sendSuccess = self.Ring.SetFloodLightOff(str(doorbellId)) if sendSuccess: # If success then log that the command was successfully sent. indigo.server.log(u"sent \"%s\" %s" % (dev.name, "off")) # And then tell the Indigo Server to update the state: dev.updateStateOnServer("onOffState", False) else: # Else log failure but do NOT update state on Indigo Server. indigo.server.log(u"send \"%s\" %s failed" % (dev.name, "off"), isError=True) ###### TOGGLE ###### elif action.deviceAction == indigo.kDeviceAction.Toggle: # Command hardware module (dev) to toggle here: indigo.server.log(u"Current state is \"%s\"" % (dev.onState), isError=True) newOnState = not dev.onState sendSuccess = True # Set to False if it failed. if sendSuccess: # If success then log that the command was successfully sent. indigo.server.log(u"sent \"%s\" %s" % (dev.name, "toggle")) # And then tell the Indigo Server to update the state: dev.updateStateOnServer("onOffState", newOnState) else: # Else log failure but do NOT update state on Indigo Server. indigo.server.log(u"send \"%s\" %s failed" % (dev.name, "toggle"), isError=True) def _setLightsOn(self, pluginAction): self.debugLog(u"\t Set %s - Ligths On" % pluginAction.pluginTypeId) dev = indigo.devices[pluginAction.deviceId] doorbellId = dev.pluginProps["doorbellId"] sendSuccess = self.Ring.SetFloodLightOn(str(doorbellId)) if sendSuccess: # If success then log that the command was successfully sent. indigo.server.log(u"sent \"%s\" %s" % (dev.name, "on")) # And then tell the Indigo Server to update the state: dev.updateStateOnServer("onOffState", True) else: # Else log failure but do NOT update state on Indigo Server. indigo.server.log(u"send \"%s\" %s failed" % (dev.name, "on"), isError=True) def _setLightsOff(self, pluginAction): self.debugLog(u"\t Set %s - Ligths Off" % pluginAction.pluginTypeId) dev = indigo.devices[pluginAction.deviceId] doorbellId = dev.pluginProps["doorbellId"] sendSuccess = self.Ring.SetFloodLightOff(str(doorbellId)) if sendSuccess: # If success then log that the command was successfully sent. indigo.server.log(u"sent \"%s\" %s" % (dev.name, "off")) # And then tell the Indigo Server to update the state: dev.updateStateOnServer("onOffState", False) else: # Else log failure but do NOT update state on Indigo Server. indigo.server.log(u"send \"%s\" %s failed" % (dev.name, "off"), isError=True) def _setSirenOn(self, pluginAction): self.debugLog(u"\t Set %s - Siren On" % pluginAction.pluginTypeId) dev = indigo.devices[pluginAction.deviceId] doorbellId = dev.pluginProps["doorbellId"] sendSuccess = self.Ring.SetSirenOn(str(doorbellId)) if sendSuccess: # If success then log that the command was successfully sent. indigo.server.log(u"sent Siren \"%s\" %s" % (dev.name, "on")) else: # Else log failure but do NOT update state on Indigo Server. indigo.server.log(u"send Siren \"%s\" %s failed" % (dev.name, "on"), isError=True) def _setSirenOff(self, pluginAction): self.debugLog(u"\t Set %s - Siren Off" % pluginAction.pluginTypeId) dev = indigo.devices[pluginAction.deviceId] doorbellId = dev.pluginProps["doorbellId"] sendSuccess = self.Ring.SetSirenOff(str(doorbellId)) if sendSuccess: # If success then log that the command was successfully sent. indigo.server.log(u"sent Siren \"%s\" %s" % (dev.name, "off")) else: # Else log failure but do NOT update state on Indigo Server. indigo.server.log(u"send Siren \"%s\" %s failed" % (dev.name, "off"), isError=True) def _downloadVideo(self, pluginAction): self.debugLog(u"\t Download video - %s" % pluginAction.pluginTypeId) dev = indigo.devices[pluginAction.deviceId] doorbellId = dev.pluginProps["doorbellId"] filename = pluginAction.props.get('downloadFilePath', "") eventId = dev.states["lastEventId"] eventIdOption = pluginAction.props.get('eventIdOption', "lastEventId") if eventIdOption == "specifyEventId": eventId = pluginAction.props.get('userSpecifiedEventId', "") #Make sure we have an event ID to process if eventId == "": indigo.server.log(u"No Event ID specified to download for %s" % (dev.name), isError=True) return #Perform the work self.Ring.downloadVideo(dev, filename, eventId) def version_check(self): VS.versionCheck(self.pluginId, self.pluginVersion, indigo, printToLog="log")
def runConcurrentThread(self): try: while self.keepProcessing: if self.loginFailed == False: if (self.updateFrequency > 0.0) and (time.time() > self.next_update_check): self.next_update_check = time.time( ) + self.updateFrequency self.version_check() #We need to get global events that are not device specific lastEvents = Ring.GetDoorbellEvent(self.Ring) if (lastEvents == False): self.errorLog("Error getting events. ") self.retryCount = self.retryCount + 1 if (int(self.pluginPrefs.get("maxRetry", 5)) != 0 and self.retryCount >= int( self.pluginPrefs.get("maxRetry", 5))): self.errorLog( "Reached max retry attempts. Won't Refresh from Server. !" ) self.errorLog( "You may need to contact Mike for support. Please post a message at http://forums.indigodomo.com/viewforum.php?f=235" ) self.sleep(36000) #Get Device specific Events for dev in indigo.devices.iter("self"): if not dev.enabled: #Skip disabled devices continue #Get the doorbell id for the current device doorbellId = dev.pluginProps["doorbellId"] if (int(self.pluginPrefs.get("maxRetry", 5)) != 0 and self.retryCount >= int( self.pluginPrefs.get("maxRetry", 5))): self.errorLog( "Reached max retry attempts. Won't Refresh from Server. !" ) self.errorLog( "You may need to contact Mike for support. Please post a message at http://forums.indigodomo.com/viewforum.php?f=235" ) self.sleep(36000) #Check to see if we have any global events for this device if len(lastEvents) != 0: for k, v in lastEvents.iteritems(): if (str(v.doorbot_id) == str(doorbellId)): event = v self.processDeviceEvents(dev, event) break self._refreshStatesFromHardware(dev) self.restartCount = self.restartCount + 1 if (self.restartCount > 10000): self.restartCount = 0 indigo.server.log( u"Memory Leak Prevention. Restarting Plugin. - This will happen until I find and fix the leak" ) serverPlugin = indigo.server.getPlugin(self.pluginId) serverPlugin.restart(waitUntilDone=False) break time.sleep(5) except self.StopThread: self.debugLog("shutdown requested")
def __init__(self): self.linac = Linac() self.ring = Ring() self.tDeviceManager = None self.svgFile = None
class SvgDrawer: def __init__(self): self.linac = Linac() self.ring = Ring() self.tDeviceManager = None self.svgFile = None def loadSvg(self, svgPath): svgTree = etree.parse(svgPath) self.svgFile = svg.SVG() self.svgFile.setSvg(svgTree.getroot()) def saveSvg(self, svgPath): svgRoot = self.svgFile.getSvg() toWrite = etree.tostring(svgRoot, pretty_print=True) fd = open(svgPath, 'w') fd.write(toWrite) def addSectionToLinac(self, name, colour, width): return self.linac.addSection(name, colour, width) def addSectionToRing(self, name, colour, angle): return self.ring.addSection(name, colour, angle) def addSubsection(self, section, subsectionName, colour, widthOrAngle): section.addSubsection(subsectionName, colour, widthOrAngle) def drawAll(self): self.drawAccelerator() if TangoDeviceManager.canConnectToTango(): self.tDeviceManager = TangoDeviceManager() if self.tDeviceManager.initialized: devices = self.tDeviceManager.getDevices() self.drawIcons(devices) self.drawDevices(devices) def initializeBlankSvg(self): blankSVGpath = '../src/blank.svg' self.loadSvg(blankSVGpath) def drawAccelerator(self): self.linac.updateSvg() self.ring.updateSvg() def drawIcons(self, devices): icons = set() for device in devices: icons.add(device.icon) for icon in icons: icon.updateSvg() def drawDevices(self, devices): self.addDeviceToAccelerator(devices) devices = self.sortDevices() self.drawDevicesOnSvg(devices) def addDeviceToAccelerator(self, devices): for device in devices: if device.isLinacElement(): self.linac.addDevice(device) elif device.isRingElement(): self.ring.addDevice(device) self.ring.assignDevicesBeforeDrawing() self.linac.assignDevicesBeforeDrawing() def sortDevices(self): sortedDevices = list() sortedDevices.extend(self.linac.getAllDevicesSorted()) sortedDevices.extend(self.ring.getAllDevicesSorted()) return sortedDevices def drawDevicesOnSvg(self, devices): for device in devices: device.updateSvg() def getAllSections(self): sections = list() sections.extend(self.linac.sections) sections.extend(self.ring.sections) return sections
def init_solar_system(self): self.background_painter = BackgroundPainter('images/space5.png') solar_rotation = Rotation(angle=0, axes=np.array([0., 0., 1.0]), time=5000) self.solar_system = System( master=Star(center=np.array([0., 0., 0.]), radius=0.6, img_name='images/globes/sun.jpg', rot=solar_rotation)) asteroid_rotation = Rotation(angle=29, axes=np.array([0., 1.0, 1.0]), time=200) self.asteroid_proto = ModelPrototype('models/asteroid/Asteroid.obj', center=np.array([0.0, 0.0, 0.0]), scale=np.array( [0.001, 0.001, 0.001]), rot=asteroid_rotation) #self.solar_system.add_satellite(satellite=self.asteroid_proto, orbit_radius=0.7, orbit_time=400, # init_orbit_angle=1.9) mercury_rotation = Rotation(angle=7, axes=np.array([0., 0., 1.0]), time=10) mercury = Planet(center=np.zeros(3), radius=0.05, img_name='images/globes/mercury.jpg', rot=mercury_rotation) self.solar_system.add_satellite(satellite=mercury, orbit_radius=0.7, orbit_time=400, init_orbit_angle=1.1) venus_rotation = Rotation(angle=3, axes=np.array([0., 0., 1.0]), time=3000) venus = Planet(center=np.zeros(3), radius=0.06, img_name='images/globes/venus.jpg', rot=venus_rotation) self.solar_system.add_satellite(satellite=venus, orbit_radius=1.3, orbit_time=600, init_orbit_angle=0.5) earth_rotation = Rotation(angle=23, axes=np.array([0., 0., 1.0]), time=300) earth = Planet(center=np.zeros(3), radius=0.06, img_name='images/globes/earth.jpg', rot=earth_rotation) earth_subsystem = System(earth) moon = Planet(center=np.zeros(3), radius=0.01, img_name='images/globes/moon.jpg') earth_subsystem.add_satellite(satellite=moon, orbit_radius=0.1, orbit_time=200) self.solar_system.append_subsystem(subsystem=earth_subsystem, orbit_radius=2.3, orbit_time=900, init_orbit_angle=2.3) mars_rotation = Rotation(angle=25, axes=np.array([0., 0., 1.0]), time=301) mars = Planet(center=np.zeros(3), radius=0.04, img_name='images/globes/mars.jpg', rot=mars_rotation) self.solar_system.add_satellite(mars, orbit_radius=3.0, orbit_time=1200, init_orbit_angle=3.1) self.add_asteroid_belt(solar_system=self.solar_system, asteroid_proto=self.asteroid_proto, n_asteroids=self.n_asteroids, orbit_radius_limits=(4.0, 5.0), orbit_time_limits=(1000, 2000)) ganimede = Planet(np.zeros(3), 0.03, 'images/globes/ganimede.jpg') upiter_rotation = Rotation(angle=3, axes=np.array([0., 0., 1.0]), time=200) upiter = Planet(np.zeros(3), 0.2, 'images/globes/upiter.jpg', rot=upiter_rotation) upiter_subsystem = System(upiter) upiter_subsystem.add_satellite(satellite=ganimede, orbit_radius=0.3, orbit_time=200) self.solar_system.append_subsystem(subsystem=upiter_subsystem, orbit_radius=6.0, orbit_time=6000, init_orbit_angle=1.3) saturn_rotation = Rotation(angle=26, axes=np.array([0., 0., 1.0]), time=200) saturn_ring = Ring(center=np.zeros(3), inner_radius=0.23, outer_radius=0.4, img_name='images/globes/saturn_ring2.png') saturn = RingedPlanet(center=np.zeros(3), radius=0.19, img_name='images/globes/saturn.jpg', ring=saturn_ring, rot=saturn_rotation) self.solar_system.add_satellite(satellite=saturn, orbit_radius=7.0, orbit_time=6500, init_orbit_angle=3.4) uranus_rotation = Rotation(angle=82, axes=np.array([0., 0., 1.0]), time=200) uranus_ring = Ring(center=np.zeros(3), inner_radius=0.23, outer_radius=0.4, img_name='images/globes/uranus_ring.png') uranus = RingedPlanet(center=np.zeros(3), radius=0.19, img_name='images/globes/uranus.jpg', ring=uranus_ring, rot=uranus_rotation) self.solar_system.add_satellite(satellite=uranus, orbit_radius=8.2, orbit_time=8000, init_orbit_angle=2.624) neptune_rotation = Rotation(angle=29, axes=np.array([0., 0., 1.0]), time=200) neptune = Planet(center=np.zeros(3), radius=0.19, img_name='images/globes/neptune.jpg', rot=neptune_rotation) self.solar_system.add_satellite(satellite=neptune, orbit_radius=12.2, orbit_time=10000, init_orbit_angle=1.8) # self.x_wing = ModelPrototype('models/TIEFIGHTER/TF_3DS02.3ds', center=np.array([0.7, 0.7, 0.7]), # scale=np.array([0.01, 0.01, 0.01])) # self.destroyer = ModelPrototype('models/star wars star destroyer/star wars star destroyer.3ds', center=np.array([1.4, 1.4, 1.4]), # scale=np.array([0.01, 0.01, 0.01])) self.falcon = ModelPrototype( 'models/star_wars_falcon/star_wars_falcon.3ds', center=np.array([0.0, 0.0, 0.0]), scale=np.array([0.001, 0.001, 0.001]))