-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
612 lines (538 loc) · 36.2 KB
/
Program.cs
File metadata and controls
612 lines (538 loc) · 36.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//#################################################################################################################################################################################################
//#
//#
//# . .. .... ... .. ... .... ........ ......... . . .. ........... ....
//# .. .
//# : ... .... .... ..
//# : ?YY! :YY7 :Y! .?J!~!J?. !YY^ ?J :JJ. .JJ. .JJY^ ~YJ? ~J?~~7J! ?Y. .Y? .7J~^~??. :
//# . ~5~7Y. :5JJ? :5! ?5: :5J 7Y?Y^ JY .YJ .YJ. .YJ75: ^57YJ :5? 75~ ?5: .YJ ~5? :
//# .. .Y? .Y? :5!.JJ :5! JY. .YJ 75:^5^ JY .J?J7 .YJ 7Y.:5~.YJ :57 !5! ?Y: .YJ :!??7~. :
//# . ?57^^J5~ :5! .JJ~Y! JY. .YJ 75: ^Y~JJ :YJ .YJ ?YY! YJ :57 !5~ ?5: .YJ .757 :
//# ... . !5!.:.:J5. :5! ?557 ^Y?^::?Y^ 75^ ^YYY .5J .YJ ~^ .YJ 7Y!::~Y?. :Y?^::?Y~ ^J7:.:7Y^ . . . ...
//# .. :: .:. :. ::. .:::. .:. .:. :. :. :. .::^:. .:::. .::::. ..
//# : ..
//# . !?7 77 !7 .!!77!!^ .!7!7!. !77 !77. .~7!!7: .!!77!!^ !7 !7 .7~ :7!!!!. !7! :?^ :?^ :?^ ~??: ^?7: 7! ^7!!77^ 77!!!!. :
//# : ~Y!Y~ JJ ?Y ?Y. .Y? ?Y JJJ7 ~Y?Y. ?Y. !5. ?Y. 7Y. :Y^ !Y. ^Y~ ~J~J^ ^Y~ ^5~ ^5~ :5!7Y. !5?Y: YJ ~5~ ^~. YY. :
//# . .Y! !Y. JJ ?Y ?Y .57 !5. J?.Y~:5:!Y. JJ ^5^ ?Y 7Y. 7J .J~ :J7~~~ .J~ !J. ^Y~ ^Y~ ^Y~ JJ .Y7 ~5:^5^ J? 75. JJ!~~: ..
//# : 7Y7^!Y? JJ ?Y ?Y .57 ?5. J? :Y5~ 7Y. JY ~5: ?Y 7J. .Y~~J :Y^ ?J!^!J7 ^Y~ ^Y~ ^Y~ ~Y?~~JY: ~5: ^Y!J? 75: .: JJ .
//# . ^Y^ ~Y: ^J7~!J^ 7J ~J!~!J^ ?? .: !Y. :?7~~?! ?J 7J. !JJ^ :J7~~~: ~J: . ^J^ :J7~~~^ :J?~!!^ :Y~ .J7 .JJ ~Y: :YY? .7J!~!J7. JJ!~~!. :
//# : ... .. ... ... . :
//# . .
//# : . ..:^^~~!!!!!!!!!!!~~^:.. .......................................................................................... .
//# : .:^!!!!~^:... ..:^~!!!!^:. :
//# .. .................. .:!7!~:. ..^~!!^. .................................................................................. :
//# : :!7!^. .:^^.. :~7!^. ............................................... :
//# : .!?!: .!?YYYYYJ?~. .:!7^. :
//# : ............. ^?7: ^?YYYYYYYYYYYY?^ :!7: .:....::::::::::::::::::::::::::::.......................................... :
//# : ~J!. :!!. :JYYYYYYYYYYYYYYYY?: ^!: .~7^ :
//# : .......... ~J~. !YY~ ~YYJYYYYYYYYYYYYYYJYY^ .?Y7. ^7^ ..::::::::::::.... ............................................... :
//# : :J7. .!:.JJ~ ^YYYYJ?!~^::::^~7?YYYYY: ^?Y~ !. ~?: .............:::::. .
//# : !J: :Y~.7^:: .YYJ!: .:7YYJ ..:7^.Y! .7! ....:.. ..
//# .. .J7 :Y? .^77. 7Y7. .?5^ ~7:. ^Y~ ^?: .... .
//# .. :Y~ .^ ?J.^JJ~ .Y! :~!!!^ ^!!!~. ?? :?J~.?J .~ .?^ ... ..
//# . :Y^ J: Y?77: !? :: ^. .J. :!??Y. J: .?^ .:. ..
//# .. :Y^ !5..J^.:: J: .:~~: .^!~: !~ ^:.^J: ?? .J: .. :
//# : .Y~ JY: .:J! :? ^^^~~^. .^^^:: .J 7?:. .JJ. :J. .::..!. ... ..
//# : 7? .YY..?Y^ ?: ^. J: ~J?..JJ. !? ................................^::... :
//# . :5. .: 7J~Y!. J. : . ?^ . .. ~! .7J^?7 . .J: ...::... ..
//# . 7? ^? .YJ..7. J: :?~. :!7!^. .^7! ?^ .~ :JJ. 7: !7 ...... ...:... ..
//# : Y^ ~Y~ ~.:Y7 .J. :^~!~~!7.~!~~~!^~ ^? 7?..! ^Y^ :J ...... ...... .
//# . :5. :YY: :YJ. :?. . .:^^.:~^.. :. ^7 .JJ. .JJ. .J. .... ... .
//# .. :Y. !Y? JY: .!^ . .Y! . ~^ :Y? ~Y~ J: .::::::.... .. ............ .. .
//# .. ^Y . ~Y7Y^ ~ .:^!7??7 :Y7 .7??7!^:. ~ ~Y~J~ : J: ............:....... :..... ......................... .::. :
//# .. :Y. !! .J? :Y: :~!?JYYYYYYYYJ. :5! .JYYYYYYYYJ?!^. .Y. J?. ~7 .Y. .^^............ :. ... :. .
//# .. .Y: .5?..: 7Y: ~YYYYYYYYYYYYYY? : .JYJJJJJJJJYYYYJ. ^Y! ^ .7Y: :J :.... .^ .: .............. ... ^ :
//# : J7 ~YY~ JY. .YYYYYYYYYYYYYYYY^ ~??. 7YJJJJJJJJJJJJJY! :Y? ^YY~ 77 ....::::::::::.... ^ : ..~: .
//# : ~Y :J5?.!Y..~ ~YYYYYYYYYYYYYYYYY. .Y? ~YYYYYYJJJJJJJJJYJ ~..Y!.?Y?: .Y. ........... .. :. : .
//# .. Y~ . :?J7Y. Y~ JYYYYYYYYYYYYYYYYY7 .Y? .YYYYYJJYJJJJJJJJJY: !J :J7J7: . 77 ^ ................... : ^ :
//# : ^Y. ^7: .^?^ ?Y: !YYYYYYYYYJYYYYYYYY^ 7YY: JYJYJJYYYJJYJYJJYY7. ^Y7 !?^..^7. ^J. .:.......... ^ ^ ..!. :
//# . 7J :JJ!:.. :YJ .!YYYYYYYYYYYYYYYYY..YYY7 7YJJJJJJJYYJYJYYJ!. JY. ..:7J7 .Y: :::::::::::::::..... .: :. :: ^ :
//# . ?7 ~JYJ!: ~Y: !^ .!JYYYYYYYYYYJJYY7!YYYJ!YYYYYYJJJJJJYYJ~ ^! ~Y: :7JY7: .J^ .~ :. .^ ^ ..
//# : ?7 .^7J?^!J J?. ^?YYYYYJJYYJJJYYJYYYYYYYYYJYYYYYY?^ :J? :J^^?J7^. .J^ ^ .. ^ .^ .: .
//# . 7? .:...::~~ !Y!. .~7JYYYYYYYYYYYYYYYYYYYYYYYJ?~. .7J^ .~^::...:. :?: ^ . :..........................: ^. .
//# . ~J: .~77!^:::. :!J7: .:~!7?JJJYYYYYJJJJ?7!^:. .^77^. .:.:^~77~. !7. .............. .:..............................................:: ..
//# .. .?! .^!?JJJJ7!7?7!:. ..:::::::::::::. .:!??777JJJJJ?7~. :?^ .............................................. .
//# . ~J^ .. ..:~7?JJ7~:^^~!^:~~~^:~7J?7!^:.. ....... .7!. ................. ... ....:::::::::::::::::::::::::::.:.........:.... ..
//# : ......... !?^ :~!!77?JYYYJ?~. :!~: .^!^..:~?JYYYJ?7!!~~^. .7!. . ..
//# .. .~?~. ..:^^:.. .!J~. :77: .:^^~^^.. ^7!. .. ... ... .
//# . :!7^. .?~ :7~ :!7^ ... ..
//# . .............. ^!7~. .:!!^. ....... . ............................. .. . .
//# . :~!!~:. .^~!~: ..
//# : .:~!!~^:. ..:^~!~^. :
//# . .~7?J?J????????????????7~:. ..:^~~~~~~~^^^^^^~~~~!~~~^:. .:~!7!~: .^ ::. :. .^ .:. .^ ::. .: :: ^ .:: ^ .:. .^ ::. .^ :. .:: :
//# : ~YYYYYYYYYYYYYYYYYYYYYYYYY5YY?7~^:......................:~7?JYYYYYYYY? ? ^: ! ^^ ? :~ !. ? ^: 7 .7 ! .7 !. 7 ^^ 7. .! !. ? .~ !. .7 :~ ! ^^ :
//# : JYJJJYYYJJJJYJ?7!!!!!!!!!!!!!777777?JJ??77777777???JJYYYYYYYJJJJJJJJJY^ .7 .^.^ ^~ 7. ~.~ 7. .:.~ .7 :::: !: ~.^. !: ~.~ 7. ~.~ .7 :~ ~.^. :
//# : JJJJJJJJYJYY!. .!YYYYYYYYYYYYYYYYYJJYYJJJJJJJJJJY^ :
//# : JYJJJJYYYYY^ ^JJJJJJJJJJJJJJJJJJJ?: ~YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY^ :
//# : JYJJJYYYYY^ !YYYYYYYYYYYYYYYYYYYYYY^ ^YYYYYYYYJJJJJJJJJJJJJJJJJJYYJY^ .7 ^~ !: .7 .7 .^.~ :! :::^ ^.:: 7. ~.~. .7 .~.~ .7 .^.^ ^^ ~.^. ~.~. :
//# : JYJJJYYYJ: 75YYYYYYYYYYYYYYYYYYYYYYY~ ^YYYYYYYY~ .JYJY^ ? .! ~^ ? 7 ^: 7 .7 !. ! ! .~ !: 7 ^: 7 .~ ! 7 ~. ! :~ ! ^: ! ~: :
//# : JYJJY7:. .......................... ..:!YYYY^ ?YJY^ .:. .: :: .:. :. ... .: .. .. :. ... :. ... .:. .. .: ... ... :
//# : JJJYJ JYYY^ :! JYYY^ :
//# : JYJYJ ~??7?7~ ~7????^ ?YYY^ ^..^..... :^ JYYY^ ^:^ .~ ^: ::^ .~ .^:. .::. ^: ^: ::^ ^:^ .~ .^:: .::: .::. ::^. ~. ::^ ^
//# : JJJYJ !JJYYJ? :::::::::^. ?JJJYY~ ?YYY^ ^. ^. . .: ?YJY^ .~ !. .? ^~ 7 :^ 7 ~. 7 7 ! :~ :~ 7 ^:.! ~. 7 ~. 7 !. 7 7 .! 7 .~ !. ! ~. ^
//# : JJJJJ ?YJY^ ..:7^ ?YJY^ ^.^ .! ^^ :.: .!. .::. .::. ^^ :^ :.^ ^.^ .! .::: .::: .::. :.^. ~: :.^ :
//# : JJJYJ ?YJY^ ?YJY^ :
//# : JYJYJ ^^^^^^^^^^^^^^^^^^^^^^^^^^. ?YYY!...............:JYJY^ ... .: .. .:. : .. .. .. .. ... .: .. .. :. .:. : ... ... :
//# : JJJYJ .YYYYYYYYYYYYYYYYYYYYYYYYY5^ JYJJYYYYYYYYYYYYYYYYYJJJY^ .! !. .7 7 .~ 7 ^: 7 ^: ! ^^ ^~ ! :^ ! ^: ? :! ^~ ~^ 7 :^ ? .! ! .! !. :
//# : JJJJY?~^::^?YJJJJJJJJJYJJYJJJYJJJYJJJY?^^^^^7YJJYYYJYYJYJJYJJJYJJJJJJY^ ~.~ .7 ^.:: ~.^. 7. .^.~ ^~ ^~ ~.^. ~.^. 7. :! :! ~^ ~.^. 7. ~.~ ~.~ :
//# : JYJJJYYYYYYYJJJJJJJJJJYJJJYYJJJJJJJJJJYYYYYYYJJJJYJYYYYJJJJJJJYJJJJJJY: .
//# : :JYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYJ^ .
//# .. :~!0x416E6F6E796D6F7573204175746F6D6F7469766520416C6C69616E6365!~: :! :::^ 7. ~.~ ~.~ .^.^ ^~ ~.^. .7. ~.~ :! :^.^ ::.^ ~: ^.^. .7 .7 .^.^ .
//# .. .7 !. ! !: .! ~.:~ ! ~. 7 :~ 7 :^ 7. .~ !. 7 ~. ! ~. 7 ^^ 7 .^ ? 7 ~. 7 ..
//# . .^ .. :. ... ... :. :: .:. ^. ... .^. :.. .:. :: .:: .^. ^. :.. :
//# ... ..
//# . ... . ................................. #
//#
//#
//#################################################################################################################################################################################################
using J2534;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Hosting;
using Newtonsoft.Json.Serialization;
using Owin;
using Swashbuckle.Application;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http.Formatting;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Windows.Forms;
namespace AAAAPI
{
// Token: 0x02000004 RID: 4
internal static class Program
{
[DllImport("kernel32.dll")] private static extern bool AllocConsole();
[DllImport("kernel32.dll")] private static extern bool FreeConsole();
[STAThread]
public static void Main(string[] args)
{
// If the project is a Windows app, spawn a console so we can see logs.
try { AllocConsole(); } catch { /* ignore */ }
const string baseUrl = "http://localhost:5000";
const int minSplashMs = 500000; // keep splash visible at least this long
var splash = default(Splash);
var splashShown = new ManualResetEvent(false);
var started = new ManualResetEvent(false);
var sw = Stopwatch.StartNew();
// 1) Show splash on its own STA thread
var splashThread = new Thread(() =>
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
splash = new Splash();
splashShown.Set();
Application.Run(splash); // blocks this UI thread
}
catch { /* don't kill process on UI exception */ }
});
splashThread.SetApartmentState(ApartmentState.STA);
splashThread.IsBackground = true;
splashThread.Start();
// Wait until splash window actually created (don’t race it)
splashShown.WaitOne();
try
{
// 2) Start web server
var webapp = WebApp.Start<Startup>(baseUrl);
started.Set();
// Enforce minimum splash duration
var remain = minSplashMs - (int)sw.ElapsedMilliseconds;
if (remain > 0) Thread.Sleep(remain);
// Close splash now that we’re listening
if (splash != null && !splash.IsDisposed)
{
try { splash.BeginInvoke(new Action(() => splash.Close())); } catch { }
}
// 3) Print to console, flush, and stay alive
Console.Title = "AAAAPI - J2534 HTTP API";
Console.WriteLine("===============================================");
Console.WriteLine("The Anonymous Automotive Alliance J2534 HTTP API");
Console.WriteLine("Listening at {0} (Swagger: /swagger)", baseUrl);
Console.WriteLine("Press CTRL + C to exit.");
Console.WriteLine("===============================================");
Console.Out.Flush();
// Keep process alive
Thread.Sleep(Timeout.Infinite);
// never hit, but dispose cleanly if you change the loop
webapp.Dispose();
}
catch (Exception ex)
{
// If server failed to start, keep splash a moment, then close it and complain loudly
if (!started.WaitOne(0))
{
// keep splash visible so you actually SEE there was a failure
var remain = Math.Max(750, minSplashMs - (int)sw.ElapsedMilliseconds);
if (remain > 0) Thread.Sleep(remain);
if (splash != null && !splash.IsDisposed)
{
try { splash.BeginInvoke(new Action(() => splash.Close())); } catch { }
}
}
var msg =
"Web server failed to start.\r\n\r\n" +
ex.GetType().FullName + ":\r\n" +
ex.Message + "\r\n\r\n" +
"Common causes:\r\n" +
" • Port in use\r\n" +
" • URL ACL not reserved (http.sys permissions)\r\n" +
" • Missing packages/references\r\n";
try { MessageBox.Show(msg, "AAAAPI", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch { }
Console.Error.WriteLine(msg);
Console.Error.WriteLine(ex);
Console.Error.Flush();
// keep the console open so you can read it
Console.WriteLine("Press ENTER to quit...");
Console.ReadLine();
try { FreeConsole(); } catch { }
}
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
var config = new HttpConfiguration();
// Attribute routing
config.MapHttpAttributeRoutes();
// Conventional routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}"
);
// JSON formatting (Newtonsoft)
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Swagger (Swashbuckle 5.x for Web API)
config.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "J2534 HTTP API");
c.PrettyPrint();
})
.EnableSwaggerUi();
// Register single host (simple static DI)
J2534Service.Instance = new J2534Host();
app.UseWebApi(config);
}
}
// Simple static locator for our host (keeps it dead simple)
public static class J2534Service
{
public static J2534Host Instance;
}
// ---------------- DTOs (plain classes; no records, no nullable refs) ----------------
public class LoadReq
{
public J2534Device Device { get; set; }
}
public class ConnectReq
{
public ProtocolID Protocol { get; set; } = ProtocolID.CAN;
public ConnectFlag Flags { get; set; } = ConnectFlag.NONE;
public BaudRate Baud { get; set; } = BaudRate.CAN_500000;
}
public class WriteReq
{
public ProtocolID Protocol { get; set; }
public TxFlag TxFlags { get; set; }
public string HexData { get; set; } // "02 10 01"
public int TimeoutMs { get; set; } = 100;
}
public class ReadReq
{
public int NumMsgs { get; set; } = 50;
public int TimeoutMs { get; set; } = 50;
public bool UntilTimeout { get; set; } = true;
}
public class ConfigReq
{
public Dictionary<ConfigParameter, ushort> Values { get; set; }
}
public class GetConfigReq
{
public List<ConfigParameter> Keys { get; set; }
}
public class StartFilterReq
{
public FilterType Type { get; set; }
public string MaskHex { get; set; }
public string PatternHex { get; set; }
public string FlowHex { get; set; }
}
public class StopFilterReq
{
public int FilterId { get; set; }
}
// ---------------- Controller (Web API classic) ----------------
[RoutePrefix("j2534")]
public class J2534Controller : ApiController
{
private J2534Host Host { get { return J2534Service.Instance; } }
[HttpGet, Route("state")]
public IHttpActionResult State() { return Ok(Host.Summary()); }
[HttpPost, Route("load")]
public IHttpActionResult Load([FromBody] LoadReq req)
{
Host.Load(req.Device);
return Ok(Host.Summary());
}
[HttpPost, Route("free")]
public IHttpActionResult Free() { Host.Free(); return Ok(Host.Summary()); }
[HttpPost, Route("open")]
public IHttpActionResult Open() { Host.Open(); return Ok(Host.Summary()); }
[HttpPost, Route("close")]
public IHttpActionResult Close() { Host.Close(); return Ok(Host.Summary()); }
[HttpPost, Route("connect")]
public IHttpActionResult Connect([FromBody] ConnectReq req) { Host.Connect(req); return Ok(Host.Summary()); }
[HttpPost, Route("disconnect")]
public IHttpActionResult Disconnect() { Host.Disconnect(); return Ok(Host.Summary()); }
[HttpPost, Route("write")]
public IHttpActionResult Write([FromBody] WriteReq req) { var sent = Host.Write(req); return Ok(new { sent = sent }); }
[HttpPost, Route("read")]
public IHttpActionResult Read([FromBody] ReadReq req) { var frames = Host.Read(req); return Ok(new { frames = frames }); }
[HttpPost, Route("set-config")]
public IHttpActionResult SetConfig([FromBody] ConfigReq req) { Host.SetConfig(req); return Ok(Host.Summary()); }
[HttpPost, Route("get-config")]
public IHttpActionResult GetConfig([FromBody] GetConfigReq req) { var cfg = Host.GetConfig(req); return Ok(cfg); }
[HttpPost, Route("filters/clear")]
public IHttpActionResult ClearFilters() { Host.ClearFilters(); return Ok(Host.Summary()); }
[HttpPost, Route("filters/start")]
public IHttpActionResult StartFilter([FromBody] StartFilterReq req) { var id = Host.StartFilter(req); return Ok(new { filterId = id }); }
[HttpPost, Route("filters/stop")]
public IHttpActionResult StopFilter([FromBody] StopFilterReq req) { Host.StopFilter(req.FilterId); return Ok(Host.Summary()); }
[HttpPost, Route("clear-tx")]
public IHttpActionResult ClearTx() { Host.ClearTx(); return Ok(); }
[HttpPost, Route("clear-rx")]
public IHttpActionResult ClearRx() { Host.ClearRx(); return Ok(); }
[HttpPost, Route("clear-periodic")]
public IHttpActionResult ClearPeriodic() { Host.ClearPeriodic(); return Ok(); }
[HttpGet, Route("vbatt")]
public IHttpActionResult VBatt() { var mv = Host.ReadVBattMilliVolts(); return Ok(new { millivolts = mv, volts = mv / 1000.0 }); }
[HttpGet, Route("vprog")]
public IHttpActionResult VProg() { var mv = Host.ReadVProgMilliVolts(); return Ok(new { millivolts = mv, volts = mv / 1000.0 }); }
}
// ---------------- Host (no nullable refs, C#7.3-friendly) ----------------
public class J2534Host
{
private readonly IJ2534Extended _api = new J2534FunctionsExtended();
private J2534Device _dev;
private uint _deviceId;
private uint _channelId;
private bool _dllLoaded;
private bool _opened;
private bool _connected;
public object Summary()
{
return new
{
dllLoaded = _dllLoaded,
opened = _opened,
connected = _connected,
deviceId = _deviceId,
channelId = _channelId,
device = _dev == null ? null : new { _dev.Name, _dev.Vendor, _dev.FunctionLibrary }
};
}
public void Load(J2534Device device)
{
if (device == null) throw new ArgumentNullException("device");
_dev = device;
_dllLoaded = _api.LoadLibrary(_dev);
if (!_dllLoaded) throw new Exception("Failed to load J2534 DLL: " + device.FunctionLibrary);
}
public void Free()
{
_api.FreeLibrary();
_dllLoaded = false;
}
public void Open()
{
EnsureDll();
var err = _api.PassThruOpen(IntPtr.Zero, ref _deviceId);
ThrowIfErr(err, "PassThruOpen");
_opened = true;
}
public void Close()
{
if (_opened)
{
var err = _api.PassThruClose(_deviceId);
ThrowIfErr(err, "PassThruClose");
}
_opened = false;
_deviceId = 0;
}
public void Connect(ConnectReq req)
{
EnsureOpen();
var err = _api.PassThruConnect(_deviceId, req.Protocol, req.Flags, req.Baud, ref _channelId);
ThrowIfErr(err, "PassThruConnect");
_connected = true;
}
public void Disconnect()
{
if (_connected)
{
var err = _api.PassThruDisconnect((int)_channelId);
ThrowIfErr(err, "PassThruDisconnect");
}
_connected = false;
_channelId = 0;
}
public int Write(WriteReq req)
{
EnsureConnected();
var bytes = HexToBytes(req.HexData);
var msg = new PassThruMsg(req.Protocol, req.TxFlags, bytes);
var p = msg.ToIntPtr();
try
{
int count = 1;
var err = _api.PassThruWriteMsgs((int)_channelId, p, ref count, req.TimeoutMs);
ThrowIfErr(err, "PassThruWriteMsgs");
return count;
}
finally { Marshal.FreeHGlobal(p); }
}
public List<string> Read(ReadReq req)
{
EnsureConnected();
List<PassThruMsg> msgs;
var ok = _api.ReadAllMessages((int)_channelId, req.NumMsgs, req.TimeoutMs, out msgs, req.UntilTimeout);
if (ok != J2534Err.STATUS_NOERROR && ok != J2534Err.ERR_TIMEOUT)
ThrowIfErr(ok, "ReadAllMessages");
var frames = new List<string>(msgs.Count);
for (int i = 0; i < msgs.Count; i++)
frames.Add(BitConverter.ToString(msgs[i].GetBytes()).Replace("-", " "));
return frames;
}
public void SetConfig(ConfigReq req)
{
EnsureConnected();
var list = new List<SConfig>();
foreach (var kv in req.Values)
list.Add(new SConfig { Parameter = kv.Key, Value = kv.Value });
var err = _api.SetConfig((int)_channelId, ref list);
ThrowIfErr(err, "SET_CONFIG");
}
public Dictionary<ConfigParameter, ushort> GetConfig(GetConfigReq req)
{
EnsureConnected();
var list = new List<SConfig>();
foreach (var key in req.Keys)
list.Add(new SConfig { Parameter = key, Value = 0 });
var err = _api.GetConfig((int)_channelId, ref list);
ThrowIfErr(err, "GET_CONFIG");
var result = new Dictionary<ConfigParameter, ushort>();
for (int i = 0; i < list.Count; i++) result[list[i].Parameter] = list[i].Value;
return result;
}
public void ClearFilters()
{
EnsureConnected();
var err = _api.ClearMsgFilters((int)_channelId);
ThrowIfErr(err, "CLEAR_MSG_FILTERS");
}
public int StartFilter(StartFilterReq req)
{
EnsureConnected();
IntPtr mask = IntPtr.Zero, pattern = IntPtr.Zero, flow = IntPtr.Zero;
int filterId = 0;
try
{
if (!string.IsNullOrEmpty(req.MaskHex))
mask = BuildMsgPtr(HexToBytes(req.MaskHex), ProtocolID.CAN);
if (!string.IsNullOrEmpty(req.PatternHex))
pattern = BuildMsgPtr(HexToBytes(req.PatternHex), ProtocolID.CAN);
if (!string.IsNullOrEmpty(req.FlowHex))
flow = BuildMsgPtr(HexToBytes(req.FlowHex), ProtocolID.CAN);
var err = _api.PassThruStartMsgFilter((int)_channelId, req.Type, mask, pattern, flow, ref filterId);
ThrowIfErr(err, "PassThruStartMsgFilter");
return filterId;
}
finally
{
if (mask != IntPtr.Zero) Marshal.FreeHGlobal(mask);
if (pattern != IntPtr.Zero) Marshal.FreeHGlobal(pattern);
if (flow != IntPtr.Zero) Marshal.FreeHGlobal(flow);
}
}
public void StopFilter(int filterId)
{
EnsureConnected();
var err = _api.PassThruStopMsgFilter((int)_channelId, filterId);
ThrowIfErr(err, "PassThruStopMsgFilter");
}
public void ClearTx() { EnsureConnected(); ThrowIfErr(_api.ClearTxBuffer((int)_channelId), "CLEAR_TX_BUFFER"); }
public void ClearRx() { EnsureConnected(); ThrowIfErr(_api.ClearRxBuffer((int)_channelId), "CLEAR_RX_BUFFER"); }
public void ClearPeriodic() { EnsureConnected(); ThrowIfErr(_api.ClearPeriodicMsgs((int)_channelId), "CLEAR_PERIODIC_MSGS"); }
public int ReadVBattMilliVolts()
{
EnsureOpen();
int v = 0;
var err = _api.ReadBatteryVoltage((int)_deviceId, ref v);
ThrowIfErr(err, "READ_VBATT");
return v;
}
public int ReadVProgMilliVolts()
{
EnsureOpen();
int v = 0;
var err = _api.ReadProgrammingVoltage((int)_deviceId, ref v);
ThrowIfErr(err, "READ_PROG_VOLTAGE");
return v;
}
// Helpers
private void EnsureDll()
{
if (!_dllLoaded) throw new InvalidOperationException("J2534 DLL not loaded. POST /j2534/load first.");
}
private void EnsureOpen()
{
EnsureDll();
if (!_opened) throw new InvalidOperationException("Device not opened. POST /j2534/open first.");
}
private void EnsureConnected()
{
EnsureOpen();
if (!_connected) throw new InvalidOperationException("Not connected. POST /j2534/connect first.");
}
private static void ThrowIfErr(J2534Err err, string op)
{
if (err != J2534Err.STATUS_NOERROR)
throw new InvalidOperationException(op + " failed: " + err);
}
private static byte[] HexToBytes(string hexish)
{
if (string.IsNullOrWhiteSpace(hexish)) return new byte[0];
var sb = new StringBuilder();
var s = hexish.Trim();
for (int i = 0; i < s.Length; i++)
{
char ch = s[i];
if (Uri.IsHexDigit(ch)) sb.Append(ch);
}
string clean = sb.ToString();
if (clean.Length % 2 != 0) throw new ArgumentException("Hex length must be even.");
var bytes = new byte[clean.Length / 2];
for (int i = 0; i < bytes.Length; i++)
bytes[i] = Convert.ToByte(clean.Substring(i * 2, 2), 16);
return bytes;
}
private static IntPtr BuildMsgPtr(byte[] payload, ProtocolID proto)
{
var msg = new PassThruMsg(proto, TxFlag.NONE, payload);
return msg.ToIntPtr();
}
}
}