Permalink
Browse files

EventNotifications now supports a generalized message endpoint system…

… instead of specifically supporting jabber

You can now test an event notification by clicking its name in the config window
Fixed an unhandled exception in autotargeter
Added deactivateModule to common.eve and generalized the detection logic for checking whether you can activate/deactivate a module
Added chainCallbacks helper to common
Added attachDatabase to common.sql
Fixed some bugs related to dronehelper's automatic redeploy
Weaponhelper will now attempt to cycle weapons instead of pulsing them
  • Loading branch information...
1 parent fe86701 commit cc5c59a58fbded08e8278e639a7d5864c4047021 @kg committed Jan 11, 2011
View
2 ActiveTanker/activetanker.py
@@ -38,7 +38,7 @@ def notifyPrefsChanged(newPrefsJson):
class ActiveTankerSvc:
def __init__(self):
self.disabled = False
- self.__updateTimer = SafeTimer(500, self.updateHealth)
+ self.__updateTimer = SafeTimer(250, self.updateHealth)
def updateHealth(self):
if self.disabled:
View
3 AutoTargeter/autotargeter.py
@@ -295,7 +295,8 @@ def OnTarget(self, what, tid=None, reason=None):
if (reason == None) and (tid in self.__balls):
ball = self.__balls[tid]
del self.__balls[tid]
- self.__eligibleBalls.remove(ball)
+ if ball in self.__eligibleBalls:
+ self.__eligibleBalls.remove(ball)
if tid in self.__lockedTargets:
self.__lockedTargets.remove(tid)
setItemColor(tid, None)
View
9 Common/Common.cs
@@ -401,6 +401,15 @@ public Common (ScriptName name)
Console.WriteLine("Done playing {0}.", soundPath);
}
+ public IEnumerator<object> AttachDB (ProcessInfo process, string filename, string attachAs) {
+ filename = System.IO.Path.GetFullPath(Path.Combine(
+ Program.GetDataFolder(),
+ filename
+ )).ToLowerInvariant();
+
+ yield return Program.AttachDB(filename, attachAs);
+ }
+
public IEnumerator<object> CreateDBTable (ProcessInfo process, string tableName, string tableDef) {
yield return Program.CreateDBTable(tableName, tableDef);
}
View
69 Common/common.eve.py
@@ -306,7 +306,7 @@ def getTypeAttributes(typeID, obj=None):
return result
-def canActivateModule(module, targetID=None):
+def canActivateOrDeactivateModule(module, targetID=None):
import uix
from common.eve.state import isItemInsideForceField
@@ -342,9 +342,6 @@ def canActivateModule(module, targetID=None):
if not def_effect:
return (False, "passive module")
- if def_effect.isActive:
- return (False, "already active")
-
if bool(getattr(module, "goingOnline", False)):
return (False, "module going online")
@@ -367,6 +364,26 @@ def canActivateModule(module, targetID=None):
if module.state == uix.UI_DISABLED:
return (False, "button disabled")
+ return None
+
+def canActivateModule(module, targetID=None):
+ result = canActivateOrDeactivateModule(module, targetID)
+ if result is not None:
+ return result
+
+ if module.def_effect.isActive:
+ return (False, "already active")
+
+ return (True, "")
+
+def canDeactivateModule(module):
+ result = canActivateOrDeactivateModule(module)
+ if result is not None:
+ return result
+
+ if not module.def_effect.isActive:
+ return (False, "not active")
+
return (True, "")
def activateModule(module, pulse=False, targetID=None, actionThreshold=ActionThreshold):
@@ -416,6 +433,50 @@ def activateModule(module, pulse=False, targetID=None, actionThreshold=ActionThr
if oldautorepeat:
module.SetRepeat(oldautorepeat)
+def deactivateModule(module, actionThreshold=ActionThreshold):
+ import blue
+ import base
+ import uix
+
+ moduleInfo = module.sr.moduleInfo
+ moduleName = cfg.invtypes.Get(moduleInfo.typeID).name
+
+ canDeactivate = canDeactivateModule(module)
+ if not canDeactivate[0]:
+ return canDeactivate
+
+ def_effect = getattr(module, "def_effect", None)
+
+ timestamp = blue.os.GetTime(1)
+ lastAction = int(getattr(module, "__last_action__", 0))
+ if (ActionThreshold is not None and
+ abs(lastAction - timestamp) <= ActionThreshold):
+ return (False, "too soon to deactivate (lag protection)")
+
+ setattr(module, "__last_action__", timestamp)
+
+ try:
+ module.DeactivateEffect(effect=def_effect)
+ return (True, None)
+ except Exception, e:
+ log("Deactivating module %s failed: %r", moduleName, e)
+ return (False, "error")
+
+def isModuleActive(module, actionThreshold=ActionThreshold):
+ import blue
+
+ result = canActivateOrDeactivateModule(module)
+ if (result is not None) and (result[0] == False):
+ return None
+
+ timestamp = blue.os.GetTime(1)
+ lastAction = int(getattr(module, "__last_action__", 0))
+ if (ActionThreshold is not None and
+ abs(lastAction - timestamp) <= ActionThreshold):
+ return None
+
+ return module.def_effect.isActive
+
class MainThreadInvoker(object):
__notifyevents__ = [
"OnStateSetupChance",
View
23 Common/common.py
@@ -80,6 +80,27 @@ def showException(etype=None, value=None, tb=None):
))
)
+def chainCallbacks(*lambdas):
+ l = list(lambdas)
+
+ def step(f, r, e):
+ if e is not None:
+ raise Exception(e)
+
+ if len(l) < 1:
+ return
+
+ current = l.pop(0)
+ try:
+ next = current()
+ except:
+ showException()
+
+ if next:
+ next.addCallback(step)
+
+ step(None, None, None)
+
class RemoteCallResult(object):
def __init__(self, stack):
self.__stack = stack
@@ -140,7 +161,7 @@ def remoteCall(script, methodName, *args, **kwargs):
result = RemoteCallResult(stack)
_pendingRemoteCalls[id] = result
- callData.append(id)
+ callData.append(id)
channel = getChannel("remotecall")
channel.send(json.dumps(callData))
View
3 Common/common.sql.py
@@ -1,5 +1,8 @@
from shootblues.common import log, remoteCall
+def attachDatabase(filename, attachAs):
+ return remoteCall("Common.Script.dll", "AttachDB", filename, attachAs, async=True)
+
def createTable(name, tableDef):
return remoteCall("Common.Script.dll", "CreateDBTable", name, tableDef, async=True)
View
16 DroneHelper/dronehelper.py
@@ -39,6 +39,7 @@ def __init__(self, droneID):
ci = getCachedItem(droneID)
self.ci = ci
+ self.slimItem = ci.slimItem
self.target = None
self.actionTimestamp = self.timestamp = 0
self.shield = self.armor = self.structure = 1.0
@@ -54,10 +55,6 @@ def __init__(self, droneID):
def ball(self):
return self.ci.ball
- @property
- def slimItem(self):
- return self.ci.slimItem
-
def setState(self, newState, timestamp):
if timestamp > self.timestamp:
self.state = newState
@@ -421,13 +418,14 @@ def updateDrones(self):
ts, obj = self.__recalled[0]
while ts + redeployAfter <= timestamp:
- slimItem = ballpark.GetInvItem(obj.id)
+ slimItem = obj.slimItem
if not slimItem:
- slimItem = sm.services["godma"].GetItem(obj.id)
- if slimItem:
- dronesToRelaunch.append(slimItem)
-
+ log("Could not get item for id %r", obj.id)
+ break
+
+ dronesToRelaunch.append(slimItem)
self.__recalled.pop(0)
+
if len(self.__recalled):
ts, obj = self.__recalled[0]
else:
View
46 EventNotifications/EventNotifications.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text;
+using System.Linq;
using ShootBlues;
using Squared.Task;
using System.Windows.Forms;
@@ -21,8 +22,8 @@ public class EventEntry {
public bool BalloonTip = false;
[Column("messageBox")]
public bool MessageBox = false;
- [Column("jabberEndpoints")]
- public string JabberEndpoints = null;
+ [Column("endpoint")]
+ public string Endpoint = null;
public EventEntry () {
}
@@ -42,7 +43,6 @@ public EventNotifications (ScriptName name)
AddDependency("Common.script.dll");
AddDependency("eventnotifications.py");
- AddDependency("JabberGateway.script.dll", true);
CustomMenu = new ToolStripMenuItem("Event Notifications");
CustomMenu.DropDownItems.Add("Configure", null, ConfigureEventNotifications);
@@ -66,7 +66,7 @@ public EventNotifications (ScriptName name)
public override IEnumerator<object> Initialize () {
yield return Program.CreateDBTable(
"eventNotifications",
- "( key TEXT PRIMARY KEY NOT NULL, sound TEXT, balloonTip BOOLEAN NOT NULL, messageBox BOOLEAN NOT NULL, jabberEndpoints TEXT )"
+ "( key TEXT PRIMARY KEY NOT NULL, sound TEXT, balloonTip BOOLEAN NOT NULL, messageBox BOOLEAN NOT NULL, endpoint TEXT )"
);
}
@@ -79,27 +79,28 @@ public EventNotifications (ScriptName name)
}
protected override IEnumerator<object> OnPreferencesChanged (EventInfo evt, string[] prefNames) {
+ var endpointNames = new HashSet<string>(GetEndpointNames());
+
var cfgDict = new Dictionary<string, Dictionary<string, object>>();
EventEntry[] ee = null;
- using (var q = Program.Database.BuildQuery("SELECT * FROM eventNotifications WHERE key = ?"))
- foreach (var eventName in DefinedEvents) {
- var dict = new Dictionary<string, object>();
-
- yield return q.ExecuteArray<EventEntry>(eventName).Bind(() => ee);
+ using (var q = Program.Database.BuildQuery("SELECT * FROM eventNotifications")) {
+ yield return q.ExecuteArray<EventEntry>().Bind(() => ee);
foreach (var el in ee) {
+ var dict = new Dictionary<string, object>();
+
if (el.BalloonTip)
dict["balloonTip"] = true;
if (el.MessageBox)
dict["messageBox"] = true;
if (el.Sound != null)
dict["sound"] = el.Sound;
- if (el.JabberEndpoints != null)
- dict["jabberEndpoints"] = el.JabberEndpoints.Split(',');
- }
+ if ((el.Endpoint != null) && (endpointNames.Contains(el.Endpoint)))
+ dict["endpoint"] = el.Endpoint;
- cfgDict[eventName] = dict;
+ cfgDict[el.Key] = dict;
+ }
}
var serializer = new JavaScriptSerializer();
@@ -124,5 +125,24 @@ public EventNotifications (ScriptName name)
statusWindow.HideConfigurationPanel("Event Notifications");
yield break;
}
+
+ public string[] GetEndpointNames () {
+ var names = new HashSet<string>();
+
+ foreach (var instance in Program.GetScriptInstances<IMessageGateway>()) {
+ foreach (var name in instance.GetEndpoints())
+ names.Add(name);
+ }
+
+ return names.ToArray();
+ }
+
+ public void SendToEndpoint (ProcessInfo process, string endpoint, string message) {
+ foreach (var instance in Program.GetScriptInstances<IMessageGateway>())
+ if (instance.Send(endpoint, message))
+ return;
+
+ throw new Exception("No script could send your message to an endpoint of that name.");
+ }
}
}
View
5 EventNotifications/EventNotifications.csproj
@@ -49,6 +49,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
+ <Compile Include="Interfaces.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="EventNotifications.cs" />
<Compile Include="EventNotificationsConfig.cs">
@@ -90,10 +91,6 @@
<Name>ShootBlues</Name>
<Private>False</Private>
</ProjectReference>
- <ProjectReference Include="..\JabberGateway\JabberGateway.csproj">
- <Project>{A0CB0C2D-8768-4E72-80E5-3857F3000AB8}</Project>
- <Name>JabberGateway</Name>
- </ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
View
34 EventNotifications/EventNotificationsConfig.Designer.cs
@@ -23,12 +23,13 @@ partial class EventNotificationsConfig {
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent () {
+ System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
this.DataGrid = new System.Windows.Forms.DataGridView();
- this.Key = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.Key = new System.Windows.Forms.DataGridViewButtonColumn();
this.Sound = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.BalloonTip = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.MessageBox = new System.Windows.Forms.DataGridViewCheckBoxColumn();
- this.JabberEndpoints = new System.Windows.Forms.DataGridViewComboBoxColumn();
+ this.Endpoints = new System.Windows.Forms.DataGridViewComboBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.DataGrid)).BeginInit();
this.SuspendLayout();
//
@@ -47,7 +48,7 @@ partial class EventNotificationsConfig {
this.Sound,
this.BalloonTip,
this.MessageBox,
- this.JabberEndpoints});
+ this.Endpoints});
this.DataGrid.Dock = System.Windows.Forms.DockStyle.Fill;
this.DataGrid.Location = new System.Drawing.Point(0, 0);
this.DataGrid.MultiSelect = false;
@@ -59,14 +60,23 @@ partial class EventNotificationsConfig {
this.DataGrid.VirtualMode = true;
this.DataGrid.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(this.DataGrid_CellValueNeeded);
this.DataGrid.CellValuePushed += new System.Windows.Forms.DataGridViewCellValueEventHandler(this.DataGrid_CellValuePushed);
+ this.DataGrid.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DataGrid_CellContentClick);
//
// Key
//
this.Key.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
+ dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
+ dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Window;
+ dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.ControlText;
+ dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Window;
+ dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.ControlText;
+ this.Key.DefaultCellStyle = dataGridViewCellStyle1;
this.Key.HeaderText = "Name";
this.Key.Name = "Key";
this.Key.ReadOnly = true;
this.Key.Resizable = System.Windows.Forms.DataGridViewTriState.False;
+ this.Key.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
+ this.Key.ToolTipText = "Click to test notification";
//
// Sound
//
@@ -90,14 +100,14 @@ partial class EventNotificationsConfig {
this.MessageBox.Name = "MessageBox";
this.MessageBox.Width = 53;
//
- // JabberEndpoints
+ // Endpoints
//
- this.JabberEndpoints.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
- this.JabberEndpoints.HeaderText = "Jabber";
- this.JabberEndpoints.Name = "JabberEndpoints";
- this.JabberEndpoints.Resizable = System.Windows.Forms.DataGridViewTriState.True;
- this.JabberEndpoints.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
- this.JabberEndpoints.Width = 76;
+ this.Endpoints.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
+ this.Endpoints.HeaderText = "Gateway";
+ this.Endpoints.Name = "Endpoints";
+ this.Endpoints.Resizable = System.Windows.Forms.DataGridViewTriState.True;
+ this.Endpoints.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
+ this.Endpoints.Width = 91;
//
// EventNotificationsConfig
//
@@ -115,11 +125,11 @@ partial class EventNotificationsConfig {
#endregion
private System.Windows.Forms.DataGridView DataGrid;
- private System.Windows.Forms.DataGridViewTextBoxColumn Key;
+ private System.Windows.Forms.DataGridViewButtonColumn Key;
private System.Windows.Forms.DataGridViewTextBoxColumn Sound;
private System.Windows.Forms.DataGridViewCheckBoxColumn BalloonTip;
private System.Windows.Forms.DataGridViewCheckBoxColumn MessageBox;
- private System.Windows.Forms.DataGridViewComboBoxColumn JabberEndpoints;
+ private System.Windows.Forms.DataGridViewComboBoxColumn Endpoints;
}
}
View
53 EventNotifications/EventNotificationsConfig.cs
@@ -24,7 +24,7 @@ public EventNotificationsConfig (EventNotifications script)
public IEnumerator<object> LoadConfiguration () {
using (new ControlWaitCursor(this)) {
DataGrid.RowCount = 0;
- JabberEndpoints.Items.Clear();
+ Endpoints.Items.Clear();
EventEntry[] dbEvents = null;
yield return Program.Database.ExecuteArray<EventEntry>(
@@ -42,19 +42,13 @@ public EventNotificationsConfig (EventNotifications script)
var newEvents = dict.Values.ToArray();
Array.Sort(newEvents, (lhs, rhs) => lhs.Key.CompareTo(rhs.Key));
- try {
- var jg = Program.GetScriptInstance<JabberGateway>("JabberGateway.Script.dll");
- if (jg != null) {
- EndpointNames = jg.Endpoints.Keys.ToArray();
-
- JabberEndpoints.Items.Add(DBNull.Value);
- JabberEndpoints.Items.AddRange(EndpointNames);
- JabberEndpoints.Visible = true;
- } else {
- JabberEndpoints.Visible = false;
- }
- } catch {
- JabberEndpoints.Visible = false;
+ EndpointNames = Script.GetEndpointNames();
+ if (EndpointNames.Length > 0) {
+ Endpoints.Items.Add(DBNull.Value);
+ Endpoints.Items.AddRange(EndpointNames);
+ Endpoints.Visible = true;
+ } else {
+ Endpoints.Visible = false;
}
EventData = newEvents;
@@ -85,8 +79,8 @@ public EventNotificationsConfig (EventNotifications script)
e.Value = row.MessageBox;
break;
case 4:
- if (EndpointNames.Contains(row.JabberEndpoints))
- e.Value = row.JabberEndpoints;
+ if (EndpointNames.Contains(row.Endpoint))
+ e.Value = row.Endpoint;
else
e.Value = DBNull.Value;
break;
@@ -109,18 +103,39 @@ public EventNotificationsConfig (EventNotifications script)
row.MessageBox = (bool)e.Value;
break;
case 4:
- row.JabberEndpoints = (string)e.Value;
+ row.Endpoint = (string)e.Value;
break;
}
Start(FlushRow(row));
}
protected IEnumerator<object> FlushRow (EventEntry row) {
- using (var q = Program.Database.BuildQuery("REPLACE INTO eventNotifications (key, sound, balloonTip, messageBox, jabberEndpoints) VALUES (?, ?, ?, ?, ?)"))
- yield return q.ExecuteNonQuery(row.Key, row.Sound, row.BalloonTip, row.MessageBox, row.JabberEndpoints);
+ using (var q = Program.Database.BuildQuery("REPLACE INTO eventNotifications (key, sound, balloonTip, messageBox, endpoint) VALUES (?, ?, ?, ?, ?)"))
+ yield return q.ExecuteNonQuery(row.Key, row.Sound, row.BalloonTip, row.MessageBox, row.Endpoint);
Script.Preferences.Flush();
}
+
+ private void DataGrid_CellContentClick (object sender, DataGridViewCellEventArgs e) {
+ if (e.ColumnIndex != 0)
+ return;
+
+ if ((e.RowIndex < 0) || (e.RowIndex >= EventData.Length))
+ return;
+
+ if (Program.RunningProcesses.Count == 0) {
+ System.Windows.Forms.MessageBox.Show(this, "Cannot test; no processes running.", "Error");
+ return;
+ }
+
+ var process = Program.RunningProcesses.First();
+
+ var dict = new Dictionary<string, object>();
+ dict["title"] = "Testing";
+ dict["text"] = "Test Notification";
+
+ Program.CallFunction(process, "eventnotifications", "handleEvent", process.Process.Id, EventData[e.RowIndex].Key, dict);
+ }
}
}
View
2 EventNotifications/EventNotificationsConfig.resx
@@ -129,7 +129,7 @@
<metadata name="MessageBox.UserAddedColumn" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
- <metadata name="JabberEndpoints.UserAddedColumn" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <metadata name="Endpoints.UserAddedColumn" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>
View
11 EventNotifications/Interfaces.cs
@@ -0,0 +1,11 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ShootBlues.Script {
+ public interface IMessageGateway {
+ string[] GetEndpoints ();
+ bool Send (string endpoint, string message);
+ }
+}
View
18 EventNotifications/eventnotifications.py
@@ -5,12 +5,6 @@
import types
import json
-try:
- from shootblues.jabber import send as jabberSend
-except:
- def jabberSend(endpoint, text):
- pass
-
notificationSettings = {}
serviceRunning = False
@@ -65,11 +59,15 @@ def handleEvent(source, name, data):
if settings.get("messageBox", False):
showMessageBox(str(data.get("title", name)), text)
- endpoints = settings.get("jabberEndpoints", [])
- body = getLines(data.get("text", name))
- for endpoint in endpoints:
+ endpoint = settings.get("endpoint", None)
+ if endpoint:
+ endpoint = str(endpoint)
+ body = getLines(data.get("text", name))
for line in body:
- jabberSend(endpoint, line)
+ sendToEndpoint(endpoint, str(line))
+
+def sendToEndpoint(endpoint, body):
+ remoteCall("EventNotifications.Script.dll", "SendToEndpoint", endpoint, body)
def fireEvent(name, **extraData):
messageSend(name, **extraData)
View
26 JabberGateway/JabberGateway.cs
@@ -244,7 +244,7 @@ public class Endpoint : IDisposable {
}
}
- public class JabberGateway : ManagedScript {
+ public class JabberGateway : ManagedScript, IMessageGateway {
public const double SendInterval = 1.0;
ToolStripMenuItem CustomMenu;
@@ -255,6 +255,7 @@ public JabberGateway (ScriptName name)
: base(name) {
AddDependency("Common.script.dll");
+ AddDependency("EventNotifications.script.dll");
AddDependency("jabber.py");
CustomMenu = new ToolStripMenuItem("Jabber Gateway");
@@ -287,8 +288,13 @@ public JabberGateway (ScriptName name)
}
public override IEnumerator<object> Initialize () {
+ yield return Program.AttachDB(Path.Combine(
+ Program.GetDataFolder(),
+ "jabber.db"
+ ), "jabber");
+
yield return Program.CreateDBTable(
- "jabberEndpoints",
+ "jabber.endpoints",
@"(name TEXT PRIMARY KEY NOT NULL, server TEXT NOT NULL, username TEXT NOT NULL, password TEXT NOT NULL, resource TEXT NOT NULL, chatChannel TEXT, chatAlias TEXT, toUsername TEXT)"
);
@@ -306,9 +312,10 @@ public JabberGateway (ScriptName name)
// For some reason reiniting is flaky :(
public IEnumerator<object> InitGateways () {
DestroyEndpoints();
+ Endpoints.Clear();
EndpointSettings[] endpoints = null;
- using (var q = Database.BuildQuery("SELECT * FROM jabberEndpoints"))
+ using (var q = Database.BuildQuery("SELECT * FROM jabber.endpoints"))
yield return q.ExecuteArray<EndpointSettings>().Bind(() => endpoints);
foreach (var settings in endpoints)
@@ -371,5 +378,18 @@ public JabberGateway (ScriptName name)
statusWindow.HideConfigurationPanel("Jabber Gateway");
yield break;
}
+
+ string[] IMessageGateway.GetEndpoints () {
+ return Endpoints.Keys.ToArray();
+ }
+
+ bool IMessageGateway.Send (string endpoint, string message) {
+ if (Endpoints.ContainsKey(endpoint)) {
+ GetQueue(endpoint).Enqueue(message);
+ return true;
+ }
+
+ return false;
+ }
}
}
View
4 JabberGateway/JabberGateway.csproj
@@ -100,6 +100,10 @@
<Name>Common</Name>
<Private>False</Private>
</ProjectReference>
+ <ProjectReference Include="..\EventNotifications\EventNotifications.csproj">
+ <Project>{D854ABA8-763A-4DEB-B938-F93734E7606F}</Project>
+ <Name>EventNotifications</Name>
+ </ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="AddEndpointDialog.resx">
View
8 JabberGateway/JabberGatewayConfig.cs
@@ -27,7 +27,7 @@ public JabberGatewayConfig (JabberGateway script)
string[] names = null;
yield return Program.Database.ExecutePrimitiveArray<string>(
- "SELECT name FROM jabberEndpoints ORDER BY name ASC"
+ "SELECT name FROM jabber.endpoints ORDER BY name ASC"
).Bind(() => names);
List.Items.AddRange(names);
@@ -59,7 +59,7 @@ public JabberGatewayConfig (JabberGateway script)
questionMarks[i] = "?";
using (var q = Program.Database.BuildQuery(String.Format(
- "REPLACE INTO jabberEndpoints ({0}) VALUES ({1})", String.Join(", ", columnNames), String.Join(", ", questionMarks)
+ "REPLACE INTO jabber.endpoints ({0}) VALUES ({1})", String.Join(", ", columnNames), String.Join(", ", questionMarks)
)))
yield return q.ExecuteNonQuery(Mapper<EndpointSettings>.GetColumnValues(settings));
@@ -71,7 +71,7 @@ public JabberGatewayConfig (JabberGateway script)
private IEnumerator<object> RemoveEndpoint (string endpointName) {
using (new ControlDisabler(this)) {
- yield return Program.Database.ExecuteSQL("DELETE FROM jabberEndpoints WHERE name = ?", endpointName);
+ yield return Program.Database.ExecuteSQL("DELETE FROM jabber.endpoints WHERE name = ?", endpointName);
yield return LoadConfiguration();
@@ -82,7 +82,7 @@ public JabberGatewayConfig (JabberGateway script)
private IEnumerator<object> EditEndpoint (string endpointName) {
EndpointSettings[] endpoints = null;
- using (var q = Program.Database.BuildQuery("SELECT * FROM jabberEndpoints WHERE name = ?"))
+ using (var q = Program.Database.BuildQuery("SELECT * FROM jabber.endpoints WHERE name = ?"))
yield return q.ExecuteArray<EndpointSettings>(endpointName).Bind(() => endpoints);
if ((endpoints == null) || (endpoints.Length == 0))
View
40 WeaponHelper/weaponhelper.py
@@ -1,6 +1,6 @@
import shootblues
from shootblues.common import log
-from shootblues.common.eve import SafeTimer, getFlagName, getNamesOfIDs, findModules, getModuleAttributes, getTypeAttributes, activateModule, canActivateModule, ChanceToHitCalculator
+from shootblues.common.eve import SafeTimer, getFlagName, getNamesOfIDs, findModules, getModuleAttributes, getTypeAttributes, activateModule, canActivateModule, ChanceToHitCalculator, deactivateModule, canDeactivateModule, isModuleActive
from shootblues.common.service import forceStart, forceStop
import service
import json
@@ -48,6 +48,7 @@ def __init__(self):
self.__updateTimer = SafeTimer(250, self.updateWeapons)
self.__ammoChanges = {}
self.__hookedMethods = []
+ self.__activeModules = {}
self.__lastAttackOrder = None
def getChanceToHitCalculator(self, module):
@@ -167,23 +168,46 @@ def updateWeapons(self):
for moduleID, module in weaponModules.items():
if hasattr(module, "ChangeAmmo"):
self.ensureModuleHooked(module)
+
+ canActivate = canActivateModule(module)[0]
+ canDeactivate = canDeactivateModule(module)[0]
- if canActivateModule(module)[0]:
- uthread.pool("DoUpdateModule", self.doUpdateModule, moduleID, module)
+ currentTarget = self.__activeModules.get(moduleID, None)
+ if currentTarget:
+ isActive = isModuleActive(module)
+ if isActive == False:
+ del self.__activeModules[moduleID]
+ currentTarget = None
+
+ if (
+ ((currentTarget is not None) and canDeactivate) or
+ canActivate
+ ):
+ uthread.pool("DoUpdateModule", self.doUpdateModule, moduleID, module, currentTarget)
- def doUpdateModule(self, moduleID, module):
+ def doUpdateModule(self, moduleID, module, currentTarget):
ammoChange = self.__ammoChanges.get(module, None)
- if ammoChange:
+
+ if (ammoChange) and (currentTarget is None):
del self.__ammoChanges[module]
fn = ammoChange[0]
args = tuple(ammoChange[1:])
log("Changing ammo")
fn(*args)
- else:
+ else:
targetID = self.selectTarget(module)
- if targetID:
+
+ if (ammoChange or
+ (currentTarget is not None) and (targetID != currentTarget)
+ ):
+ deactivated, reason = deactivateModule(module)
+ if deactivated:
+ del self.__activeModules[moduleID]
+ elif targetID:
self.__lastAttackOrder = targetID
- activated, reason = activateModule(module, pulse=True, targetID=targetID)
+ activated, reason = activateModule(module, targetID=targetID)
+ if activated:
+ self.__activeModules[moduleID] = targetID
def initialize():
global serviceRunning, serviceInstance

0 comments on commit cc5c59a

Please sign in to comment.